Roh*_*ose 0 python recursion python-2.7
我想计算下面算法给出的系列中的术语数:
if n=1 STOP:
if n is odd then n=3n+1
else n=n/2
Run Code Online (Sandbox Code Playgroud)
例如,如果n为22,则系列将如下所示,系列的长度将为16:
22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
Run Code Online (Sandbox Code Playgroud)
我在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()
Run Code Online (Sandbox Code Playgroud)
这在大多数情况下都有效,但是在某些n值达到最大递归深度消息时失败.有替代方法吗?
| 归档时间: |
|
| 查看次数: |
347 次 |
| 最近记录: |