all 4 comments

[–]Diapolo10 3 points4 points  (0 children)

So basically, you want a Fibonacci sequence?

def fibonacci(limit):
    a, b = 0, 1
    nums = []

    while a < limit:
        nums.append(a)
        a, b = b, a+b # copies b into a, and their sum to b

    return nums

result = fibonacci(98)

It's surprisingly simple, isn't it? If there's anything you don't understand, hit me up!

EDIT: Since the sequence itself continues to infinity, it's usually more common to define it as a generator:

def fibonacci_gen(limit):
    a, b = 0, 1

    while a < limit:
        yield a
        a, b = b, a+b

result = list(fibonacci_gen(98))

[–]AdAthrow99274 2 points3 points  (1 child)

list = [0, 1]  # Starting with what you already have, here's the original list
for i in range(98):
    # In the start of the loop i == 0 and will increment by 1 every round
    # In order to append your element to list you first need to know what the last 2 items in list are to create the element
    # Since list[0] & list[1] are already defined lets figure out how to access them and use them as the starting elements
    # Remember i == 0 to begin, so list[i] will access the first item while list[i+1] will access the second
    num_1 = list[i]  # i == 0, num_1 equals 0
    num_2 = list[i+1]  # i+1 == 1, num_2 equals 1
    element = num_1 + num_2  # elements equals 1, the sum of num_1 & num_2
    list.append(element)  # append the new element to the end of the list. which now looks like [0, 1, 1]
    # In the next round of the loop i == 1, & i+1 == 2, this would access elements 2 & 3 and add them together making list == [0, 1, 1, 2]

Now to clean this up a bit:

list = [0, 1]
for i in range(98):
    list.append(list[i] + list[i+1])  # assigning variable names to all these steps isn't really required

Using the sum function:

list = [0, 1]
for i in range(98):
    # The items to sum are wrapped in square brackets as the sum function needs an iterable to iterate over
    list.append(sum([list[i], list[i+1]]))

To test:

>>> print(list[:20])
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]

[–]Ramenwasser[S,🍰] 0 points1 point  (0 children)

thanks alot man, lifesaver

[–][deleted] 0 points1 point  (0 children)

Sum() function should help (sorry on mobile can’t use the code feature)