Python 系列长度计算
我想计算以下算法给出的序列中的项数:Python 系列长度计算,python,python-2.7,recursion,Python,Python 2.7,Recursion,我想计算以下算法给出的序列中的项数: if n=1 STOP: if n is odd then n=3n+1 else n=n/2 例如,如果n为22,则序列如下,序列长度为16: 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 我在python中提出了以下递归函数: class CycleSizeCalculator(object): ''' Class to calculate the cycle coun
if n=1 STOP:
if n is odd then n=3n+1
else n=n/2
例如,如果n为22,则序列如下,序列长度为16:
22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
我在python中提出了以下递归函数:
class CycleSizeCalculator(object):
'''
Class to calculate the cycle count of a number. Contains the following
members:
counter - holds the cycle count
number - input number value
calculate_cycle_size() - calculates the cycle count of the number given
get_cycle_length() - returns the cycle count
'''
def calculate_cycle_size(self,number):
"""
Calculates the cycle count for a number passed
"""
self.counter+=1# count increments for each recursion
if number!=1:
if number%2==0:
self.calculate_cycle_size((number/2))
else:
self.calculate_cycle_size((3*number)+1)
def __init__(self,number):
'''
variable initialization
'''
self.counter = 0
self.number = number
self.calculate_cycle_size(number)
def get_cycle_length(self):
"""
Returns the current counter value
"""
return self.counter
if __name__=='__main__':
c = CycleSizeCalculator(22);
print c.get_cycle_length()
这在大多数情况下都有效,但当某些值达到n时,消息最大递归深度将失败。有其他的方法吗?这就是问题所在,我最后一次听说它在所有正整数起点上都收敛到1,这一点尚未得到证实。除非能证明收敛性,否则很难确定序列长度。对于某些数字,该序列可以任意大。因此,递归方法可能还不够。您可以简单地尝试迭代方法: def calculate_cycle_size(self,number): self.counter = 1 while number != 1: if number%2 == 0: number = number / 2 else: number = 3 * number + 1 self.counter += 1 def计算循环大小(自身、数量): self.counter=1 而数字!=1: 如果数字%2==0: 数字=数字/2 其他: 数字=3*数字+1 self.counter+=1
如果您希望递归地执行此操作,则可以这样做:
def get_count(n):
return 1 if n == 1 else 1 + get_count(3*n+1 if n%2 else n/2)
以及一个迭代版本:
def get_count(n):
i = 1
while n != 1:
(n, i) = (3*n+1 if n%2 else n/2, i + 1)
return i
好吧,因为那只是
返回1
?;^)@b或者这与上面的代码有相同的问题。该函数仍然是递归的,并且容易发生堆栈溢出。@0605002 true,但如果OP知道他的50行代码可能是2行,则该函数可能有用。该序列甚至不能保证是有限的,因此即使是循环也不能保证任何事。@pjs是,但至少迭代方法可以在递归将导致堆栈溢出的情况下找到长度。我听说现在还没有找到一个序列可以永远延续下去的数字。