Tae Min Kim
Tae Min Kim

Reputation: 35

Python recursive sequence related code

I am trying to make a code that produces numbers according to the following formula...

T[n] = 1 + T[n-1] * 2

numList = []
numLisst.append (1)
#Begins with a term 1.

def numSequence ():
    while True:
        for i in range (1,12):
            #Temporally set numbers from 1 to 12
            numList[i] == 1+(numList[i-1]*2)
            break
    print (numList)

numSequence()

First of all, this brings an error, list index out of index

I'd like to see this code produce the fibonacci sequences, for example,,

1, 3, 7, 15, 31, 63, 127 , ....

I hope if I use this recursive program, I would be able to find out specific order of the numbers in an array, e.g. If I'd like to find out 3rd number in the array, should be whether 7 or 15 (It would depend how I would set it)

Upvotes: 1

Views: 2397

Answers (2)

Mika72
Mika72

Reputation: 411

One way to solve this probem (not most Pythonic implementation, though...)

# T[n] = 1 + T[n-1] * 2

def nextFibonachi(n,i):
    n = 1 + n*2
    print(str(i)+": "+str(n))
    return n,i

fibArr = []
for i in range(0,100):
    if i == 0:
        n = 0
    n,i = nextFibonachi(n, i)
    fibArr.append(n)

print(fibArr)

m = 10
print("\n"+str(m)+": "+str(fibArr[m]))

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117856

The recursive implementation of your formula would be the following, assuming your base case was T(1) = 1

def T(n):
    if n == 1:
        return 1
    else:
        return 1 + T(n-1)*2

Some examples

>>> [T(i) for i in range(1,10)]
[1, 3, 7, 15, 31, 63, 127, 255, 511]
>>> T(15)
32767

Upvotes: 3

Related Questions