0

I am trying to use Fibonacci series and get Cubes of the series. My Fibonacci function is giving an output but I want that output to be in a List form. Following is my code

cube = lambda x : x ** 3
def fibonacci(n): 
    a = 0
    b = 1
    count = 0
    if n < 0: 
        print("Incorrect input") 
    elif n == 0: 
        return a 
    elif n == 1: 
        return b 
    else: 
        while count < n: 
            print(a)
            c = a + b 
            a = b 
            b = c 
            count += 1
if __name__ == "__main__":
    n = int(input())
    print(list(map(cube,fibonacci(n))))

I am getting the following output with error:

6
0
1
1
2
3
5

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-38-58624b7f0dd2> in <module>
      1 if __name__ == "__main__":
      2     n = int(input())
----> 3     print(list(map(cube,fibonacci(n))))

TypeError: 'NoneType' object is not iterable

I am very new to coding. Please help!

  • `map` takes a function and an iterable as parameters, the error is with your fibonacci function – RMPR May 26 '20 at 07:23

2 Answers2

1

If you'd your Fibonacci function to return a list, change it as follows:

def fibonacci(n): 
    a = 0
    b = 1
    count = 0
    res = []
    if n < 0: 
        print("Incorrect input") 
    elif n == 0: 
        return [a] 
    elif n == 1: 
        return [b] 
    else: 
        while count < n: 
            res.append(a)
            c = a + b 
            a = b 
            b = c 
            count += 1
        return res

You can then run:

n = 5
print(list(map(cube,fibonacci(n))))

Which results in:

[0, 1, 1, 8, 27]
Roy2012
  • 11,755
  • 2
  • 22
  • 35
0

While you could build a list right away as shown here, this task can be solved more efficiently using generators. The idea is that with the generator you do the computation when actually required and you do not (need to) store potentially large intermediate objects.

Also, note how swapping is done in Python and why name = lambda ... is an anti-pattern in Python.

def fibonacci(n): 
    a = 0
    b = 1
    count = 0
    if n < 0: 
        print("Incorrect input")
        return
    elif n == 0: 
        yield a 
    elif n == 1: 
        yield b 
    else: 
        while count < n: 
            yield a
            a, b = b, a + b 
            count += 1


def cube(x):
    return x ** 3


n = 8
print(list(fibonacci(n)))
# [0, 1, 1, 2, 3, 5, 8, 13]
print(list(map(cube, fibonacci(n))))
# [0, 1, 1, 8, 27, 125, 512, 2197]
norok2
  • 25,683
  • 4
  • 73
  • 99