reduce

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

What is the 'pythonic' equivalent to the 'fold' function from functional programming? Question: What is the most idiomatic way to achieve something like the following, in Haskell: foldl (+) 0 [1,2,3,4,5] –> 15 Or its equivalent in Ruby: [1,2,3,4,5].inject(0) {|m,x| m + x} #> 15 Obviously, Python provides the reduce function, which is an implementation …

Total answers: 8

NameError: global name 'reduce' is not defined

NameError: global name 'reduce' is not defined Question: I’m new to Python. Would you please tell me what’s wrong with the following code? When I run it, I got an error message of “NameError: global name ‘reduce’ is not defined”. I asked Goolge but it’s useless. 🙁 def main(): def add(x,y): return x+y reduce(add, range(1, …

Total answers: 2

How does reduce function work?

How does reduce function work? Question: As far as I understand, the reduce function takes a list l and a function f. Then, it calls the function f on first two elements of the list and then repeatedly calls the function f with the next list element and the previous result. So, I define the …

Total answers: 9

Finding the average of a list

Finding the average of a list Question: How do I find the mean average of a list in Python? [1, 2, 3, 4] ⟶ 2.5 Asked By: Carla Dessi || Source Answers: For Python 3.8+, use statistics.fmean for numerical stability with floats. (Fast.) For Python 3.4+, use statistics.mean for numerical stability with floats. (Slow.) xs …

Total answers: 25

NameError: name 'reduce' is not defined in Python

NameError: name 'reduce' is not defined in Python Question: I’m using Python 3.2. Tried this: xor = lambda x,y: (x+y)%2 l = reduce(xor, [1,2,3,4]) And got the following error: l = reduce(xor, [1,2,3,4]) NameError: name ‘reduce’ is not defined Tried printing reduce into interactive console – got this error: NameError: name ‘reduce’ is not defined …

Total answers: 7

python histogram one-liner

python histogram one-liner Question: There are many ways to write a Python program that computes a histogram. By histogram, I mean a function that counts the occurrence of objects in an iterable and outputs the counts in a dictionary. For example: >>> L = ‘abracadabra’ >>> histogram(L) {‘a’: 5, ‘b’: 2, ‘c’: 1, ‘d’: 1, …

Total answers: 9