0

我需要从用户那里得到 10 个数字,然后计算每个数字出现在所有数字中的次数。

我写了下面的代码:

# Reset variable
aUserNum=[]
aDigits=[]

# Ask the user for 10 numbers
for i in range(0,2,1):
    iNum = int(input("Please enter your number: "))
    aUserNum.append(iNum)

# Reset aDigits array
for i in range(0,10,1):
    aDigits.append(0)

# Calc the count of each digit
for i in range(0,2,1):
    iNum=aUserNum[i]
    print("a[i] ",aUserNum[i])
    while (iNum!=0):
        iLastNum=iNum%10
        temp=aDigits[iLastNum]+1
        aDigits.insert(iLastNum,temp)
        iNum=iNum//10

print(aDigits)

从结果中,我可以看到温度不起作用。当我写这个 temp=aDigits[iLastNum]+1 时,不应该说单元格 iLastNum 中的数组会得到单元格 +1 的值吗?

谢谢, 亚尼夫

4

2 回答 2

1

您可以连接所有输入以获取单个字符串并将其与collections.Counter()

import collections
ct = collections.Counter("1234567890123475431234")
ct['3'] == 4
ct.most_common() # gives a list of tuples, ordered by times of occurrence
于 2013-02-03T11:47:28.213 回答
0

你可以通过两种方式做到这一点。可以使用字符串,也可以使用整数。

aUserNum = []

# Make testing easier
debug = True

if debug:
    aUserNum = [55, 3303, 565, 55665, 565789]
else:
    for i in range(10):
        iNum = int(input("Please enter your number: "))
        aUserNum.append(iNum)

使用字符串,我们将所有的整数变成一个大字符串,然后计算“0”出现的次数,然后计算“1”的出现次数,等等。

def string_count(nums):
    # Make a long string with all the numbers stuck together
    s = ''.join(map(str, nums))

    # Make all of the digits into strings
    n = ''.join(map(str, range(10)))

    aDigits = [0,0,0,0,0,0,0,0,0,0]

    for i, x in enumerate(n):
        aDigits[i] = s.count(x)

    return aDigits

对于整数,我们可以使用可爱的整数除法技巧。此代码是为 Python 2.7 编写的,由于“假设浮动”更改,因此不适用于 3.x。为了解决这个问题,更改x /= 10tox //= 10并将打印语句更改为打印函数。

def num_count(nums):
    aDigits = [0,0,0,0,0,0,0,0,0,0]

    for x in nums:
        while x:
            # Add a count for the digit in the ones place
            aDigits[x % 10] += 1

            # Then chop off the ones place, until integer division results in 0
            # and the loop ends
            x /= 10

    return aDigits

这些输出相同。

print string_count(aUserNum)
print num_count(aUserNum)
# [1, 0, 0, 3, 0, 9, 4, 1, 1, 1]

为了更漂亮的输出,这样写。

print list(enumerate(string_count(aUserNum)))
print list(enumerate(num_count(aUserNum)))
# [(0, 1), (1, 0), (2, 0), (3, 3), (4, 0), (5, 9), (6, 4), (7, 1), (8, 1), (9, 1)]
于 2013-02-03T11:44:18.243 回答