Python-3.x根据用户输入计算特定数字的频率

时间:2017-06-07 08:46:00

标签: python-3.x frequency

我正在尝试制作一个程序,用于输出用户输入的一系列数字(没有特定范围)出现数字7的次数每个号码都是一个单独的输入,而不是一个。

我搜索的范围很广,但我找到的解决方案涉及来自预制列表的字母,单词或数字,而不是来自用户输入的int,当我尝试修改时出错。我确定我错过了一些非常明显的东西,但我无法弄清楚如何做到这一点。

(我试过Counter,如果num == 100,count(100),i在范围内等等 - 但我显然走错路了)

我的出发点是尝试修改打印最高数字的那个,因为我的目标是采用类似的格式:

x = 0
done = False
while not done:
    print("Enter a number (0 to end): ")
    y = input()
    num = int(y)
    if num != 0:
        if num > x:
            x = num
    else:
        done = True
print(str(x))

感谢您对此提出的任何建议。

3 个答案:

答案 0 :(得分:3)

考虑

from collections import Counter

nums = []
c = Counter()
done = False
while not done:
    y = int(input("Enter a number (0 to end): "))
    if y == 0:
        done = True
    else:
        c.update([y])
        print(c)

示例输出:

Enter a number (0 to end): 1
Counter({1: 1})
Enter a number (0 to end): 2
Counter({1: 1, 2: 1})
Enter a number (0 to end): 2
Counter({2: 2, 1: 1})
Enter a number (0 to end): 2
Counter({2: 3, 1: 1})
Enter a number (0 to end): 0

如果用户输入非整数,这显然会中断。如果需要,请移除int(input..)或添加try-except

答案 1 :(得分:0)

您可以使用以下代码示例。它希望第一个输入作为您要在列表中搜索的数字。其次是每个单独的行列表。

x = 0
done = False
count = 0
i = input("Which number to search: ")
print("Enter list of numbers to search number",i,", enter each on separate line and 0 to end): ")
while not done:
        j = input()
        num = int(j)
        if int(j) == 0 :
                print("exitting")
                break
        else:
                if j == i:
                        count += 1
print("Found number",i,"for",count,"number of times")

答案 2 :(得分:0)

尝试以下方法:

x = ''
done = False
while not done:
    print("Enter a number (0 to end): ")
    y = input()
    if y != '0':
        x = x + y
    else:
        done = True

print(x.count('7'))
相关问题