Zack
Zack

Reputation: 11

Recursive function to return the number of elements in a list that are followed directly by double that element

I am trying to write a recursive function to return the number of items in a list that are directly followed by that item doubled.

for example, the list I currently have, L = [1, 2, 4, 8, 16, 32, 64, 128, 256], returns the number 8.

I wrote out the non-recursive version of the function but I cannot figure out how to write it as a recursive function (a function that calls itself). What I have is shown below.

def countDouble(L):
    doubleCount = 0
    index = 0
    for num in range(0, len(L) - 1):
        if int(L[index + 1])/2 == int(L[index]):
            doubleCount += 1
        index += 1
    return doubleCount

L = [1, 2, 4, 8, 16, 32, 64, 128, 256]
print(countDouble(L))

Please help if you can.

Upvotes: 1

Views: 316

Answers (1)

Tim Roberts
Tim Roberts

Reputation: 54733

This solve the problem but it's silly.

def countDouble(L):
    if len(L) < 2:
        return 0
    if L[0]+L[0] == L[1]:
        return 1+countDouble(L[1:])
    return countDouble(L[1:])

L = [1,2,4,8,16,32,64,128,256]
print(countDouble(L))

Upvotes: 2

Related Questions