Sequence function error?

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

提交回复
热议问题