Gene101
Gene101

Reputation: 1

Recursive Collatz-Conjecture output challenge

I have a recursive function for calculating the collatz-conjecture. The code produces the right number, it calls itself recursively based on a counter. Once the counter is exhausted it should return the correct number - but it returns None.

def collatz_con(x, revs):
    print("start")
    print(x, revs)
    if (x%2 == 0) and (revs != 0):
        print("even and revs =" + str(revs))
        holder = x//2
        print(holder)
        collatz_con(holder, revs - 1)
    elif (revs != 0):
        print("odd  and revs =" + str(revs))
        holder = ((3*x) + 1)
        print(holder)
        collatz_con(holder, revs -1)
    else:
        print("else exercised")
        return x   
print(collatz_con(1071, 14))

Should the x variable be returned and printed out?

Upvotes: 0

Views: 81

Answers (1)

cdlane
cdlane

Reputation: 41895

You've made a common mistake where your recursive function collatz_con() returns a value, but when you call it recursively, you ignore that returned value. My guess is you want something more like:

def collatz_con(x, revs):
    print(x, revs)

    if x % 2 == 0 and revs != 0:
        print("even and revs =", revs)
        holder = x // 2
        print(holder)
        return collatz_con(holder, revs - 1)

    if revs != 0:
        print("odd and revs =", revs)
        holder = 3 * x + 1
        print(holder)
        return collatz_con(holder, revs - 1)

    print("else exercised")
    return x

Upvotes: 2

Related Questions