52
votes
7answers
9k views

Javascript equivalent of Python's zip function

Is there a javascript equivalent of Python's zip function? That is, given two arrays of equal lengths create an array of pairs. For instance, if I have three arrays that look like this: var array1 ...
73
votes
6answers
17k views

Python: Why is functools.partial necessary?

Partial application is cool. What functionality does functools.partial offer that you can't get through lambdas? >>> sum = lambda x, y : x + y >>> sum(1, 2) 3 >>> incr = ...
126
votes
6answers
68k views

List filtering: list comprehension vs. lambda + filter

I happened to find myself having a basic filtering need: I have a list and I have to filter it by an attribute of the items. My code looked like this: my_list = [i for i in my_list if i.attribute == ...
115
votes
8answers
29k views

Why isn't Python very good for functional programming?

I have always thought that functional programming can be done in Python. Thus, I was surprised that Python didn't get much of a mention in this question, and when it was mentioned, it normally wasn't ...
30
votes
8answers
3k views

Why program functionally in Python?

At work we used to program our Python in a pretty standard OO way. Lately, a couple guys got on the functional bandwagon. And their code now contains lots more lambdas, maps and reduces. I ...
86
votes
9answers
147k views

How to Use python map and other functional tools

This is quite n00bish, but I'm trying to learn/understand functional programming in python. The following code: foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3] def maptest(foo, bar): print foo, bar ...
66
votes
21answers
37k views

Useful code which uses reduce() in python

Do anyone here have any useful code which uses reduce() function of python? Is there any code other than the usual + and * that we see in the examples? Refer Fate of reduce() in Python 3000 by GvR
45
votes
9answers
5k views

Can you explain closures (as they relate to Python)?

I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as ...
4
votes
1answer
127 views

Callable object decorator applied to method doesn't get self argument on input

import functools class Decor(object): def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): def closure(*args, **kwargs): print args, ...
8
votes
1answer
142 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 ...
1
vote
1answer
549 views

Merge of lazy streams (using generators) in Python

I'm playing with functional capacities of Python 3 and I tried to implement classical algorithm for calculating Hamming numbers. That's the numbers which have as prime factors only 2, 3 or 5. First ...
6
votes
8answers
8k views

Python: calling functions dynamically

Suppose: fields = ['name','email'] def clean_name(): pass def clean_email(): pass How can I call clean_name() and clean_email() dynamically? For example: for field in fields: ...
14
votes
7answers
4k views

Modify bound variables of a closure in Python

Is there any way to modify the bound value of one of the variables inside a closure? Look at the example to understand it better. def foo(): var_a = 2 var_b = 3 def _closure(x): return var_a + ...
11
votes
6answers
3k views

Explaining persistent data structures in simple terms

I'm working on a library for Python that implements some persistent data structures (mainly as a learning exercise). However, I'm beginning to learn that explaining persistent data structures to ...
5
votes
5answers
3k views

python: get number of items from list(sequence) with certain condition

Assuming that I have a list with huge number of items. l = [ 1, 4, 6, 30, 2, ... ] I want to get the number of items from that list, where an item should satisfy certain condition. My first thought ...
5
votes
2answers
244 views

Conjoin function made in functional style

Recently, reading Python "Functional Programming HOWTO", I came across a mentioned there test_generators.py standard module, where I found the following generator: # conjoin is a simple backtracking ...
2
votes
3answers
95 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?
1
vote
1answer
137 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 ...
4
votes
3answers
137 views

function making

Hi I am new to functional programming. What i did is >>> g=lambda x:x*2 >>> f=g >>> g=lambda x:f(f(x)) >>> g(9) 36 Now, it is not creating g as a nonterminating ...
32
votes
13answers
11k views

Python vs F#: which language I should learn [closed]

Hey, I know this is an subjective question, but please don't vote to close it before I get the acceptable answer. I'm a .NET programmer (somewhat experienced), and really want to learn a functional ...
25
votes
4answers
1k views

Is “with” monadic?

Like many a foolhardy pioneer before me, I'm endeavoring to cross the trackless wasteland that is Understanding Monads. I'm still staggering through, but I can't help noticing a certain monad-like ...
18
votes
6answers
25k views

any() function in Python with a callback

The Python standard library defines an any() function that Return True if any element of the iterable is true. If the iterable is empty, return False. It checks only if the elements evaluate to ...
32
votes
2answers
6k views

How does this lambda/yield/generator comprehension work?

I was looking through my codebase today and found this: def optionsToArgs(options, separator='='): kvs = [ ( "%(option)s%(separator)s%(value)s" % {'option' : ...
25
votes
12answers
2k views

Which programming language or a library can process Infinite Series?

Which programming language or a library is able to process infinite series (like geometric or harmonic)? It perhaps must have a database of some well-known series and automatically give proper values ...
9
votes
16answers
2k views

What do we call this (new?) higher-order function?

I am trying to name what I think is a new idea for a higher-order function. To the important part, here is the code in Python and Haskell to demonstrate the concept, which will be explained afterward. ...
21
votes
10answers
8k views

python list comprehensions; compressing a list of lists?

guys. I'm trying to find the most elegant solution to a problem and wondered if python has anything built-in for what I'm trying to do. What I'm doing is this. I have a list, A, and I have a ...
5
votes
6answers
217 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 ...
9
votes
1answer
3k views

compose function and functional module

Python 3.2 documentation refers to Collin Winter's functional module which contains function compose: The compose() function implements function composition. In other words, it returns a wrapper ...
7
votes
5answers
413 views

Lazy transform in C++

I have the following Python snippet that I would like to reproduce using C++: from itertools import count, imap source = count(1) pipe1 = imap(lambda x: 2 * x, source) pipe2 = imap(lambda x: x + 1, ...
4
votes
1answer
835 views

Compute a chain of functions in python

I want to get the result of a chain of computations from an initial value. I'm actually using the following code: def function_composition(function_list, origin): destination = origin for ...
3
votes
3answers
137 views

Generator which leaves a placeholder at the beginning and at the end of the input iterator intact

Let's take a list as an example: a = [255, 255, 1, 255, 255, 255, 1, 2, 255, 255, 2, 255, 255, 3, 255, 3, 255, 255, 255] 255 is a special value in it. It's a placeholder. I've made a generator ...
8
votes
2answers
705 views

Does python have a built-in function for interleaving generators/sequences?

I noticed that itertools does not (it seems to me) have a function capable of interleaving elements from several other iterable objects (as opposed to zipping them): def leaf(*args): return ...
5
votes
6answers
256 views

String coverage optimization in Python

I have this initial string. 'bananaappleorangestrawberryapplepear' And also have a tuple with strings: ('apple', 'plepe', 'leoran', 'lemon') I want a function so that from the initial string and ...
4
votes
4answers
934 views

Is there a Python equivalent of the Haskell 'let'

Is there a Python equivalent of the Haskell 'let' expression that would allow me to write something like: list2 = [let (name,size)=lookup(productId) in (barcode(productId),metric(size)) ...
3
votes
3answers
950 views

Have Python 2.7 functions remember value and not reference? Closure Weirdness

I'm trying to return from a function a list of functions, each of which uses variables from the outside scope. This isn't working. Here's an example which demonstrates what's happening: a = [] for i ...
1
vote
0answers
132 views

Lazy parameter binding in Python

I tried to design a workflow using composite pattern, the sample codes looks like this: class CommandInterface(object): def __init__(self, name, template=None, tool=None, param : ...
9
votes
5answers
5k views

list.reverse does not return list?

The return object is named None for list.reverse(). So this code fails when I call solution(k). Is there any way I can get around making a temporary? Or how should I do it? fCamel = 'F' bCamel = 'B' ...
6
votes
2answers
431 views

Equivalent of Haskell scanl in python

I would like to know if there is a built in function in python for the equivalent Haskell scanl, as reduce is the equivalent of foldl. Something that does this: Prelude> scanl (+) 0 [1 ..10] ...
6
votes
5answers
1k views

Equivalent to F#’s Seq.scan() method in Python?

is there a function like a F#'s Seq.scan() in python? i want to do some cumsum() or cumproduct() kind of things without looping.
4
votes
1answer
261 views

Enforcing side effects in python

Is there a tool that enables you to annotate functions/methods as "pure" and then analyzes the code to test if said functions/methods are side effect free ?
3
votes
1answer
115 views

Correct use of a fold or reduce function to long-to-wide data in python or javascript?

Trying to learn to think like a functional programmer a little more---I'd like to transform a data set with what I think is either a fold or a reduce operation. In R, I would think of this as a ...
2
votes
0answers
275 views

Higher order functions: automatic generation vs manual definition

I'm trying to delay evaluation for a bit, and so I prefer to work with functions as long as possible. I have class Function which defines composition and pointwise arithmetics for functions: from ...
2
votes
1answer
126 views

Python deep zip

I am trying to write a function like zip. I am not good at explaining what I mean, so i will just show 'code' of what i'm trying to do. a = [1,2,3,[4,5]] b = a[:] zip(a, b) == [(1,1), (2,2), (3,3), ...
2
votes
2answers
970 views

Functional programming - for and while loops

I'm trying to write for and while loops in python - functional programming style. I think for construct is fine but while doesn't work, it runs infinitely. # for loop lst = [1, 2, 3] def fun(e): ...
2
votes
1answer
227 views

Few questions on generator expressions and speed efficient alternatives

Consider the following code, integral to my questions below: import functools N = 3 class Struct: """Create an instance with argument=value slots. This is for making a lightweight object ...
2
votes
1answer
585 views

How can I use functools.partial on multiple methods on an object, and freeze parameters out of order?

I find functools.partial to be extremely useful, but I would like to be able to freeze arguments out of order (the argument you want to freeze is not always the first one) and I'd like to be able to ...
1
vote
3answers
302 views

product of two functions

I have two functions, f and g. Both have the same signature: (x). I want to create a new function, z, with the same signature: def z(x): return f(x) * g(x) except that I'd like to be able to ...
1
vote
2answers
118 views

seek a better design suggestion for a trial-and-error mechanism in python?

See below data matrix get from sensors, just INT numbers, nothing specical. A B C D E F G H I J K 1 25 0 25 66 41 47 40 12 69 76 1 2 17 23 73 97 99 39 84 ...
1
vote
7answers
381 views

Is there a way to check whether function output is assigned to a variable in Python?

In Python, I'd like to write a function that would pretty-print its results to the console if called by itself (mostly for use interactively or for debugging). For the purpose of this question, let's ...
0
votes
1answer
44 views

call a function in python script then check if condition

I have this function: def ContentFunc(): storage = StringIO() c = pycurl.Curl() c.setopt(c.URL, url) c.setopt(c.WRITEFUNCTION, storage.write) c.perform() ...