python 3 * n + 1 - 计算一个数字列表的最长周期

时间:2015-01-22 04:39:41

标签: python

对于给定的数字列表(input.txt)我正在尝试使用output.txt打印出与每行关联的循环的数字和长度。

所以我到现在为止:

  1. /input.txt看起来有点像这样:
  2.   

    4 6

         

    2 11

         

    3 20

    等...

    1. 计算周期长度的函数:
    2. 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
      
      1. 计算最大周期的函数:
      2. 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
        
        1. 一个读取input.txt文件并解析值的函数:
        2. 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
          

          请指导!?

1 个答案:

答案 0 :(得分:1)

string formating

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))