3
  • I want to print Fibonacci Series using lambda() function with map() or reduce() function in Python.

Note: I did search on SO, but could only find questions related to Printing nth Fibonacci number. e.g Fibonacci numbers, with an one-liner in Python 3?

4
  • 1
    This is stackoverflow, not code golf. Commented May 4, 2014 at 5:53
  • What is the problem in sharing a tricky situation, I faced with all. ? ... even SO recommends it read: blog.stackoverflow.com/2011/07/… Commented May 4, 2014 at 5:56
  • 1
    It's okay (and encouraged) to ask and answer your own on-topic questions. This is a bad question, any way you slice it. This site is about solving programming problems, not a competition to see who can produce a "one liner". Commented May 4, 2014 at 5:59
  • @roppi ..See the link of the question I provided in the text.. it was also similar but it did help other people.. Commented May 4, 2014 at 6:03

6 Answers 6

8

I have the following working solutions:

A. Using lambda() + reduce():

 >>> fib = lambda n: reduce(lambda x, _: x+[x[-1]+x[-2]], range(n-2), [0, 1])
 >>> fib(10)
 >>> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Note: Not able to use x.append(x[-1]+x[-2]). Gives AttributeError (Don't know why)

B. Using lambda() + map(): (Have to use a variable for result)

 >>> result = [0,1]
 >>> fib = lambda n: map(lambda _: result.append(result[-1] + result[-2]), xrange(n-2))
 >>> fib(10)                          ## Ignore its output ##
 >>> result                           ## Stores the result ##
 >> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Sign up to request clarification or add additional context in comments.

5 Comments

I see two problems with your lambda() + reduce() solution. The first is you avoid doing a reduction by ignoring the second lambda() argument and treat reduce() as a simple iterator . The second problem is that fib(1) and fib(2) produce the same result but they shouldn't.
about your note, that is because x.append(...) return None because is a operation in place of list, while reduce expect your the function to return a value that is going to be used in the next iteration, for that you can do this (x.append(...),x)[1]
I see two problems with your lambda() + map() solution. The first is that it doesn't work in Python 3 as its extreme lazy evaluation doesn't fill out result until something consumes the result of map(). (E.g. try wrapping your map() in an any()) The second problem is that fib(1) and fib(2) produce the same result but they shouldn't.
the solution to problem that cdlane mention, is to add [:n] to the list [0,1] -> [0,1][:n]
@Copperfield fib = lambda n: reduce(lambda x, _: x+[x[-1]+x[-2]], range(n-1), [0, 1])[:-1] also works.
2

Fibonacci using reduce() and lambda()

from functools import reduce

def fibonacci(count):
    sequence = (0, 1)

    for _ in range(2, count):
        sequence += (reduce(lambda a, b: a + b, sequence[-2:]), )

    return sequence[:count]

print(fibonacci(10))

OUTPUT

(0, 1, 1, 2, 3, 5, 8, 13, 21, 34)

Fibonacci using map() and lambda()

def fibonacci(count):
    sequence = [0, 1]

    any(map(lambda _: sequence.append(sum(sequence[-2:])), range(2, count)))

    return sequence[:count]

print(fibonacci(10))

OUTPUT

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

1 Comment

in the first version I rather use a list and append
1

Code Snippet:

fibonacci = lambda number: number if number <= 1 else fibonacci(number - 1) + fibonacci(number - 2);
listOfFibonacciNumbers = list(map(fibonacci, range(0, 20, 1)));
print(listOfFibonacciNumbers);

Output:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]

In place of 20, you can give your number. I hope this helps:)

Comments

0

yo can try this for Fibonacci using reduce() and lambda()

def Fib(count):
    first =[0,1]
    for i in range(0,count-2):
        first.append(reduce(lambda x,y : x+y,first[-2:]))

    print(first) 
Fib(10)

output

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34] 

Comments

0

Here's what might help you! Implemented using reduce() and lambda

from functools import reduce

fibonacci_seq = [0, 1]
n = 10

reduce(lambda a, b: len(fibonacci_seq) < n and (fibonacci_seq.append(a+b) or a+b), fibonacci_seq)

(fibonacci_seq.append(a+b) or a+b) : as the <any_list>.append(ele) returns None, I'm using it to append the next element in the series to the fibonacci_seq. oring it with a+b allows to return a+b as the result to the reduce() function to operate on it with the next element in the sequence.

len(fibonacci_seq) < n : The list stops growing once the len(list) reaches n.

OUTPUT

print(fibonacci_seq)

>>> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] 

The above method returns the right sequence for n = 2 onwards.

Comments

-2

try this code which prints the first 10 Fibonacci numbers using LAMBDA

fib = lambda n: n if n<=1 else fib(n-1)+fib(n-2)

for i in range(10):print(fib(i))

1 Comment

Hi and welcome to SO. Please edit your answer and format your code as code. Also some description would be nice, it's not "look how clever one liner I wrote" site.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.