【问题标题】:inputting to a list and finding longest streak of the same input python输入到列表并找到相同输入python的最长条纹
【发布时间】:2015-05-04 13:33:24
【问题描述】:

我正在编写一个程序,其中用户将值输入到列表中,直到想要结束它,程序会告诉用户他们输入的最长连续数字。例如,用户输入 7,7,7,6,6,4,end 会得到输出:你最长的连续是 3。因为 7 连续输入了 3 次。

到目前为止,我有这个,它似乎不想结束当前的运行,所以如果我输入 7、7、7、6、6、6、6、5、4,它会告诉我最长的连胜是 7就像它正在继续从 7 进入的连胜纪录。这就是我所拥有的:

mylist = []

run = 1

currentrun = 1

number = input('enter a number: ')
mylist.append(number)



while number != 'end' :
    number = input ('enter a number: ')
    mylist.append(number)
for i in range (len(mylist)):

    if mylist[i] == mylist[i-1] and mylist[i] == mylist[i+1] :
        currentrun = currentrun + 1
    else:
        currentrun = 0

    print (currentrun)
    if currentrun > run:
        run = currentrun

print (mylist)

print ('Your longest run was' ,run)

非常感谢任何帮助。

【问题讨论】:

    标签: python list casting int items


    【解决方案1】:

    试试这个

    mylist = []
    while True:
        mylist.append(int(raw_input("enter number:")))
    streak = 0
    cur, last = 0, None
    for num in mylist:
        if num == last:
            curr += 1
        else:
            streak = max(streak, cur)
            last = num
            cur = 0
    print("longest run was ",streak)
    

    【讨论】:

      【解决方案2】:

      假设您有一个诸如[7, 7, 7, 6, 6, 6, 6, 5, 4, 6, 7] 之类的列表,您可以使用groupby() 函数计算重复次数,然后在末尾打印最大次数。

      from itertools import groupby
      a = [7, 7, 7, 6, 6, 6, 6, 5, 4, 6, 7]
      lst = []
      for n,c in groupby(a):
         num,count = n,sum(1 for i in c)
         lst.append((num,count))
      
      maxx = max([y for x,y in lst])
      print 'Your longest run was {}'.format(maxx)
      

      在这种情况下,它返回 4,因为数字 6 连续重复了 4 次

      【讨论】:

        【解决方案3】:

        这是您所描述的如何完成的冗长版本。中途我意识到我正在使用 Python 16 运行它,所以它是向后兼容的!

        a = None # stores the last number seen
        b = 0 # stores the count of the last number
        result = [0, 0] # number, count result array
        for c in "7,7,7,6,6,6,6,5,4".split(','): # split string into array of
                                                 # just our numbers
            c = int(c) # change the character into a bast ten int
            if c != a: # check current number against last
                a = c # if different than last, remember current number as last
                b = 1 # start over counting at one
            else: # if current number is same as last
                b = b + 1 # increment counter
                if b > result[1]: result = a, b # if counter higher than highest
                                                # previous count, store the
                                                # current number and count
        print(("value: %i, count: %i" % result)) # print resulting number, count
        

        输出:

        value: 6, count 4
        

        如果您有任何问题,请随时发表评论。

        【讨论】:

          【解决方案4】:

          这将跟踪条纹的值。如果另一个条纹更长,它将用新的值和长度替换最后一个条纹。

          我对输入使用了异常处理。如果您输入一个非数字,它将忽略它并再次要求输入一个数字。如果您不输入任何内容,它将结束输入循环。

          请注意,我使用的是raw_input 而不是输入。

          while True:
              number = raw_input('enter a number: ')
              if number == '':
                break
          
              try:
                  number = int(number)
              except ValueError:
                  print ("'" + number + "' is not a number.")
                  continue
          
              mylist.append(number)
          
          if len(mylist) > 0:
              #print (mylist)
          
              # Chain is the current run we're tracking. Longest is the longest chain we've tracked so far.
              chain = longest = 1
              # Current is the value of the chain we're tracking now. Value is the value of the longest chain we've tracked so far. We use the first value of the list.
              current = value = mylist[0]
          
              # Starting with the second number in the list and iterating to the end we compare values.
              for number in mylist[1:]:
                  # Did we find another in our current chain?
                  if number == current:
                      chain += 1
                  else:
                      chain = 1
                      current = number
          
                  # This will require chains to exceed the previous longest chain to be chosen as the longest. Change this to >= to track the last chain (in the case of a tie).
                  if chain > longest:
                      longest = chain
                      value = current
          
              print ('Your longest run was', longest)
          

          【讨论】:

          • 你在吃东西ValueError;不好的做法。
          • @MotokoKusanagi 你在一个小小的技术问题上惹我生气。是的,我们应该通知用户他们输入了一个无效值。然而,我们也应该告诉用户如何退出循环。这是 OP 没有做的事情,我觉得不需要在答案中做。我把它留给 OP 来填补 UX 的空白。添加所有必需的错误检查和用户反馈不是问题的一部分。
          【解决方案5】:
          >>> from itertools import groupby
          >>> input_iter = iter(lambda: input('enter a number: '), 'end')
          >>> max(sum(1 for x in v) for k,v in groupby(input_iter))
          enter a number: 7
          enter a number: 7
          enter a number: 7
          enter a number: 6
          enter a number: 6
          enter a number: 4
          enter a number: end
          3
          

          【讨论】:

            猜你喜欢
            • 2019-01-06
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-03-24
            • 2014-06-24
            • 1970-01-01
            • 2021-06-27
            相关资源
            最近更新 更多