Tagged Questions
0
votes
3answers
82 views
Dict comprehension, tuples and lazy evaluation
I am trying to see if I can pull off something quite lazy in Python.
I have a dict comprehension, where the value is a tuple. I want to be able to create the second entry of the tuple by using the ...
0
votes
4answers
30 views
Print out the index of a map function
I am trying to play around with some more of function programming parts of python and for a test I thought I would print out the sum of the first n integers for all numbers between 1 and 100.
for i ...
1
vote
1answer
81 views
Using map with multiple args
>>> map(max, 'spam', 'potato')
['s', 'p', 't', 'm', 't', 'o']
Python's map can take multiple iterables. Why is this there, can you give an example of a typical case where that's needed or ...
4
votes
6answers
171 views
is there any way to prevent side effects in python?
Is there any way to prevent side effects in python? For example, the following function has a side effect, is there any keyword or any other way to have the python complain about it?
def ...
8
votes
1answer
113 views
Any Functional Programming method of traversing a nested dictionary?
I am trying to find a better way to implement this:
d = {"a": {"b": {"c": 4}}}
l = ["a", "b", "c"]
for x in l:
d = d[x]
print (d) # 4
I am learning functional programming so I am just trying ...
0
votes
2answers
73 views
Recursively operating on a tree structure: How do I get the state of the “entire” tree?
First, context:
As a side project, I'm building a computer algebra system in Python that yields the steps it takes to solve an equation.
So far, I've been able to parse algebraic expressions and ...
2
votes
3answers
62 views
What does this mean: [ x[1:] for x in self.files if x != '/']
What does this mean:
[x[1:] for x in self.files if x != '/']
If possible would you mind explaining it in imperative equivalent?
2
votes
6answers
80 views
Any pythonic way to do “[['a', 2], ['b',1]] + [['b', 2], ['c', 1]] = [['b', 3], ['a', 2], ['c', 1]]”?
input:
[['a', 2], ['b',1]] (sorted by value)
[['b', 2], ['c', 1]]
output:
[['b', 3], ['a', 2], ['c', 1]]
Any pythonic way? Of course, in Python! (better for 2.6x)
Thanks!
0
votes
1answer
23 views
create seperate instances in each element in list/dict comprehension in Python
My codes are like this:
widgets = {x: Select2Widget(attrs={"style": "width: 300px;"}) for x in
['paper', 'factor', 'cell_line', 'cell_type']}
This will cause error because all the ...
0
votes
3answers
65 views
Write pure and functional code in Python using the concept higher-order functions like in JavaScript
How would one use higher-order functions (functions returning other functions) in Python?
This is my JavaScript example, whose programming concept I would like to use in Python as well.
Let's say, ...
5
votes
4answers
112 views
How to judge (or how to write) a python function with no side effects?
The answer equals the definition of side effects.
Up to now, I don't find out a precise answer. The python doc says:
Functional style discourages functions with side effects that modify internal ...
1
vote
5answers
72 views
python reduce to find the union of sets
I am trying to find the union of set of sets. Specifically I want the union of the list of nodes for each key in the dictionary of networkx graphs called periodic_gs. I would like to use the reduce ...
0
votes
3answers
88 views
Python functional programming self-exercise
I realise that using a functional paradigm everywhere does not always result in very readable code -- the code segment below is something I'm doing just as an exercise. What I'm trying to do is as ...
1
vote
2answers
208 views
Javascript vs Python with respect to Python 'map()' function
In Python there is a function called map that allows you to go: map(someFunction, [x,y,z]) and go on down that list applying the function. Is there a javascript equivalent to this function?
I am ...
-1
votes
2answers
42 views
Python function for boolean “and” operator?
I'm suprised not to find the boolean (not bitwise) and operator in the operator module:
http://docs.python.org/2/library/operator.html
Why is that so? Is there a workaround?
-2
votes
1answer
52 views
“Removing” a node from a functional linked list
I'm looking for a function that returns a linked list that doesn't contain a specific node.
Here is an example implementation:
Nil = None # empty node
def cons(head, tail=Nil):
...
-2
votes
3answers
69 views
Python: Map calling a function not working
Map not calling the function being passed.
class a:
def getDateTimeStat(self,datetimeObj):
print("Hello")
if __name__ == "__main__":
obj = a()
print("prog started")
data = ...
-1
votes
1answer
148 views
Python: Understanding reduce()'s 'initializer' argument
I'm relatively new to Python and am having trouble
with Folds or more specifically, reduce()'s 'initializer' argument
e.g. reduce(function, iterable[, initializer])
Here is the function...
>>> ...
3
votes
5answers
221 views
Translating a simple imperative algorithm to functional style
I recently made a small algorithm to strip out function arguments from a snippet of code and only keep the outermost functions.
I found that this algorithm was very easy to design in an imperative ...
2
votes
3answers
121 views
Converting an imperative algorithm into functional style
I wrote a simple procedure to calculate the average of the test coverage of some specific packages in a Java project. The raw data in a huge html file is like this:
<body>
package pkg1 ...
2
votes
2answers
48 views
multiple self-contained filters applied during a single iteration
Lets say I have a data structure that's very expensive to iterate through and I need to collect it's elements into lists depending on certain criteria.
#fake data. pretend it's hard to access
import ...
1
vote
5answers
90 views
Generating iterables of iterables with python itertools. (using the repeat function)
While experimenting with functional programming in python i have noticed a difference between two expression I believe should have the same results.
In particular what I want to to is to have an ...
2
votes
2answers
197 views
Python: Difference between filter(function, sequence) and map(function, sequence)
I'm reading through the Python documentation to really get in depth with the Python language and came across the filter and map functions. I have used filter before, but never map, although I have ...
1
vote
1answer
25 views
Enumerating all possibilites for a nondeterministic list
I'm working with lists that could have "ambiguous" values in certain places. The lists are small enough that implementing backtracking search seems silly. Currently, I'm representing ambiguous values ...
3
votes
1answer
69 views
Recursive generator in Pythonic way?
Below is a generator that can create all combinations made of one character from a number of strings:
('ab', 'cd', 'ef') => 'ace', 'acf', 'ade', 'adf', 'bce', 'bcf', 'bde', 'bdf'.
However, I ...
3
votes
4answers
114 views
Inconsistent behavior of python generators
The following python code produces [(0, 0), (0, 7)...(0, 693)] instead of the expected list of tuples combining all of the multiples of 3 and multiples of 7:
multiples_of_3 = (i*3 for i in ...
4
votes
5answers
192 views
Map method in python
class FoodExpert:
def init(self):
self.goodFood = []
def addGoodFood(self, food):
self.goodFood.append(food)
def likes(self, x):
return x in self.goodFood
def ...
7
votes
3answers
153 views
Functional vs. imperative style in Python
I've been spending some of my spare time lately trying to wrap my head around Haskell and functional programming in general. One of my major misgivings has been (and continues to be) what I perceive ...
2
votes
1answer
76 views
Python, functional programming, mapping to a higher level
Does anybody know how to map in Python easily a function to a higher level in a nested list, i.e. the equivalent to Map[f, expr, levelspec] in Mathematica.
2
votes
2answers
136 views
python equivalent of quote in lisp
In python what is the equivalent of the quote operator? I am finding the need to delay evaluation. For example, suppose in the following lisp psuedocode I have:
a = '(func, 'g)
g = something
(eval a)
...
2
votes
4answers
57 views
python evaluate functions with parameters given by a dictionary
With python how can I evaluate a dictionary of functions with their associate parameters. To be more specific, the keys are the functions and the values are a list of paramters.
for example, consider ...
1
vote
4answers
111 views
python evaluate commands in form of strings
In Python I am trying to figure out how to evaluate commands given as strings in a program. For example, consider the built in math functions sin, cos and tan
Say I am given these functions as a ...
2
votes
1answer
97 views
recursive dict comprehension
I am building out a complex dictionary with some unconventional code. I'm just curious if there is some way to check the current dictionary's value or even the current list's values while building it ...
1
vote
1answer
89 views
Count non-empty end-leafs of a python dicitonary/array data structure - recursive algorithm?
I'm looking for a function to find all the non-empty end-points of a kind of complex dictionary/array structure. I think that because I don't know the number of nested arrays or their locations, it ...
1
vote
2answers
87 views
Confusing double usage of python asterisk notation (as a function argument, or as a function definition)
I'm a bit confused. Let's create a function called x. I know that by putting * before the y, this means that we can add as many arguments as we want.
def x(*y):
return y
However.
Case 1:
...
1
vote
2answers
84 views
How to supply a default value iff a value is None?
Is there an operator or a library function such that v ??? d
evaluates to v if v is distinct from None and doesn't evaluate d, or
evaluates to d if v is equal to None.
(where by ??? I denote the ...
0
votes
2answers
81 views
How to map over a value iff it's distinct from None?
Is there a concise way how to map over a value if and only if it's not None? Something like
def fmapMaybe(f, v):
if v is not None:
f(v)
else:
None
Update: I'm looking for a ...
0
votes
1answer
61 views
Python functional transformation of JSON list of dictionaries from long to wide
I have a JSON object that I'm trying to refit to analyze differently, and I'm looking for a functional transformation to aggregate one field on the basis of two uniquely keyed fields.
My data set ...
4
votes
2answers
80 views
How to achieve python's any() with a custom predicate?
>>> l = list(range(10))
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> if filter(lambda x: x > 10, l):
... print "foo"
... else: # the list will be ...
1
vote
2answers
58 views
replace functions with a different function in python
I have a function called get_account(param1,param2)
in run time I need to replace this function with the function mock_get_account(param1,param2)
so when the system calls get_account(param1,param2) I ...
0
votes
1answer
47 views
Applying method to all methods, using result
When dabbling in functional languages, I recall a way to call a method on a list of objects, where the next method call used the result of the previous call as input as well as the next list item.
In ...
2
votes
2answers
255 views
Python list of dictionaries projection, filter, or subset?
I'm trying to create what I think is a 'projection' from a larger dictionary space onto a smaller dimension space. So, if I have:
mine = [
{"name": "Al", "age": 10},
{"name": "Bert", "age": 15},
...
2
votes
1answer
192 views
Python multiprocessing map function error
I have a simple multiprocessing example that I'm trying to create. The ordinary map() function version works, but when changed to Pool.map, I'm getting a strange error:
from multiprocessing import ...
0
votes
2answers
127 views
Sorting strings with integer values in python
I have some code that I find clumsy.
Given:
sample_lists = [(u'1', u'penguin'), (u'2', u'kelp'), (u'5', u'egg')],
[(u'3', u'otter'), (u'4', u'clam')]
I want the result: ['penguin', ...
2
votes
5answers
429 views
correct style for element-wise operations on lists without numpy (python)
I would like to operate on lists element by element without using numpy, for example, i want add([1,2,3], [2,3,4]) = [3,5,7] and mult([1,1,1],[9,9,9]) = [9,9,9], but i'm not sure which way of doing is ...
1
vote
3answers
99 views
Can someone explain to me the difference between a Function Object and a Closure
By "Function Object", I mean an object of a class that is in some sense callable and can be treated in the language as a function. For example, in python:
class FunctionFactory:
def __init__ ...
0
votes
1answer
112 views
Getting respective *args, **kwargs from collection of functions, then filling in the irregular 2d structure with provided 1d arguments
I have data like this:
args, kwargs = (('foo', 'bar', 'baz'), {'goo': 1})
And I have functions, inside an object, which want these data as arguments. They are to be provided via a method which has ...
5
votes
2answers
921 views
What are some Python libraries written to demostrate Functional Reactive Programming? [closed]
We handle huge data streams through our socket servers and in need of a non-block way to management callbacks to prevent race conditions.
Recently I came to know about functional reactive programming ...
0
votes
1answer
72 views
namedTuples definition across multiple chained functions
I am currently building a modular pipeline of functions to process some data in Python (2.7).
I'm sticking to a loosely functional style, without any objects (for the type of code and the routines ...
0
votes
2answers
64 views
Passing (grouped) keyword args to wrapped functions
I have a class which wraps a collection of functions so as to be called later:
class Wrapper(object):
def __init__(self, *funcs):
self.funcs = funcs
def callFuncs(self, *args):
...