Sequence function error?

后端 未结 2 678
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-23 20:39

I\'m getting an error on line 3 \"TypeError: \'int\' object is not iterable,\" and its been bothering me. Any advice/fixes appreciated.

Example test: collatz_counts(4) →

相关标签:
2条回答
  • 2021-01-23 21:05

    This can be solved recursively:

    def collatz_length(n):
        if n == 1:
            return 1
        return 1 + collatz_length(3*n+1 if n%2 else n//2)
    

    Which lends itself to be memoized if you are going to be calling for a range of numbers, e.g. in Py3

    import functools as ft
    
    @ft.lru_cache(maxsize=None)
    def collatz_length(n):
        if n == 1:
            return 1
        return 1 + collatz_length(3*n+1 if n%2 else n//2)
    

    Which will run through the first million collatz sequences in about 2.31s vs about 28.6s for the iterative solution.

    0 讨论(0)
  • 2021-01-23 21:16

    Use a while loop. Just modify x in place until you get to 1 and keep track of the number of steps each time you run a cycle.

    def collatz_counts(x):
        steps = 0
        while x != 1:
            if x % 2:
                x = x * 3 + 1
            else:
                x = x // 2
            steps += 1
        return steps
    
    0 讨论(0)
提交回复
热议问题