对于给定的数字列表(input.txt)我正在尝试使用output.txt打印出与每行关联的循环的数字和长度。
所以我到现在为止:
4 6
2 11
3 20
等...
def calc_cycle(number): count = 1 while number != 1: if number % 2 != 0: number = number * 3 + 1 else: number = number / 2 count = count + 1 return count
def max_cycle(n, m): max_value=1 for i in range(n, m+1): x = calc_cycle(i) if max_value < x: max_value = x return n, m, max_value
def read_input(list_of_urls): with open(list_of_urls) as f: for line in f: #n,m = [int(i) for i in line.split(' ')] n,m = line.split(' ') n=int(n) m=int(m) print n,m
基本上我被困在这个部分,我不知道如何得到一个看起来像这样的output.txt文件:
4 6 9 #9 being the max cycle for all the numbers between 4 and 9 2 11 20 #20 being the max cycle for all numbers between 2 and 11 3 20 21 #21 being the max cycle for numbers between 3 and 20
请指导!?
答案 0 :(得分:1)
def read_input(list_of_urls):
with open(list_of_urls) as f, open('output.txt', 'w+') as f2:
for line in f:
n,m = line.split(' ')
n=int(n)
m=int(m)
_,_,thisMaxCycle = max_cycle(n,m)
f2.write("{0} {1} {2} #{2} being the max cycle for all numbers between {0} and {1}\n".format(n,m,thisMaxCycle))