Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Collatz-problem
#1
Dear forum,
I got a question to my function below:
The problem is the return value of tau() is integer usually, but if I call tau() from test() the return value is None and not writable into my dictionary. Maybe you got an idea on how to solve this problem. Also as I am a python beginner I am open to any tips and considerations for the future.

def tau(i,count=0):
    """
    This function counts how many times it has to iterate a number to become 1. Its the function of the Collatz-Problem with a memory.
    """
    if i < 1:
        raise ValueError("n muss >=1 sein")
    if i in tau.cache:
        return count + tau.cache[i]
    else:
        tau(i // 2 if i % 2 == 0 else i * 3 + 1, count + 1)

tau.cache = {1: 0}

def test(N):
    """ 
    This function should write the value between 2 and N and his number of iterations into a dictionairy. 
    """
    for k in range(2,N):
        tau.cache[k] = tau(k)
    print(tau.cache)
Reply
#2
You're missing a return on line 10, so you're not returning the value of the recursive call.
Also, you can use functools.lru_cache (or functools.cache if using 3.9) to take care of memoization, which would make your implementation simpler.
Reply
#3
Aside from not returning a value from your recursion, you are doing the counting backward. You should return a count from tau, not pass a count to tau.
def tau(i):
    """This function counts how many times it has to iterate a number to become 1.
    Its the function of the Collatz-Problem with a memory.
    """
    if i < 1:
        raise ValueError("n muss >=1 sein")
    if i in tau.cache:
        return tau.cache[number]
    return tau(i // 2 if i % 2 == 0 else i * 3 + 1) + 1
I do not like how your cache works either. You only cache final results, so the cache doesn't provide much of a benefit. The tau function may make several recursive function calls, each calculating a count for some number. All of these partial results should be added tot he cache. That way each time you calculate tau() you will be making the next call to tau() run faster.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How can I found how many numbers are there in a Collatz Sequence that I found? cananb 5 3,774 Nov-23-2020, 05:15 PM
Last Post: cananb
  [split] The Collatz Sequence valencia 4 3,697 Jan-06-2019, 08:10 PM
Last Post: valencia
  The Collatz Sequence Truman 11 14,113 Dec-27-2018, 11:28 PM
Last Post: Truman

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020