Sequence function error?

后端 未结 2 679
爱一瞬间的悲伤
爱一瞬间的悲伤 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.

提交回复
热议问题