【问题标题】:I have a sorted list, and I would like to count the number of occurrence of each number without using count() function我有一个排序列表,我想在不使用 count() 函数的情况下计算每个数字的出现次数
【发布时间】:2018-08-06 13:51:40
【问题描述】:

我有一个排序列表,我想在不使用count() 函数的情况下计算每个数字出现的次数。

sameItem = 0
startPosition = 1

sortedList  = [13, 15, 15, 17, 18, 18, 18, 18, 19, 20, 20, 20, 20, 21, 22, 22, 22, 22, 23, 23, 23, 24, 24, 26, 26, 26, 27, 27, 27, 28]

for i in range(1, len(sortedList)):

    item1 = sortedList[i - 1]
    item2 = sortedList[i]
    countItems = 1
    sameItem = countItems

    if item1 == item2:
        startPosition = i
        while (sortedList[i - 1] == sortedList[startPosition]):
           sameItem += 1
           startPosition += 1

    else:
        sameItem = countItems

    print(str(item1) + " appears " + str(sameItem) + " times")

【问题讨论】:

  • 你有什么问题?
  • 一种方法是创建一个计数器数组并使其成为最大数的大小。所以在你的情况下 int countArray[29];现在您可以执行类似 countArray[13]++ 的操作来计算 13 出现的次数。然后将countArray的值相加。
  • 这可能会对您有所帮助。 Count occurrence in sorted array

标签: python-3.x count


【解决方案1】:

你可以使用itertools.groupby:

from itertools import groupby
for k, g in groupby(sortedList):
    print('%s appears %d times' % (k, len(list(g))))

或者如果您不想使用任何库函数:

count = 1
for i, n in enumerate(sortedList):
    if i == len(sortedList) - 1 or n != sortedList[i + 1]:
        print('%s appears %d times' % (n, count))
        count = 1
    else:
        count += 1

或者,如果您根本不想使用任何功能(实际上print 也是一个功能,但我认为您不能没有它):

last = None
for n in sortedList:
    if n != last:
        if last is not None:
            print('%s appears %d times' % (last, count))
        last = n
        count = 1
    else:
        count += 1
print('%s appears %d times' % (last, count))

以上所有输出:

13 appears 1 times
15 appears 2 times
17 appears 1 times
18 appears 4 times
19 appears 1 times
20 appears 4 times
21 appears 1 times
22 appears 4 times
23 appears 3 times
24 appears 2 times
26 appears 3 times
27 appears 3 times
28 appears 1 times

【讨论】:

  • 但我想将它转换为 mips...所以我不会使用任何库...有没有办法用我当前的代码来做(稍微调整一下)?
  • 我明白了。我已经用一个不使用库函数的解决方案更新了我的答案。
  • 有没有办法在不枚举的情况下做到这一点?因为我正在尝试编写一个不使用任何函数的算法..
  • 我已经用一个根本不使用任何功能的解决方案更新了我的答案。
  • 我在下面添加了我当前的解决方案..它们大多是正确的,除了最后几个输出
【解决方案2】:

i = 1

检查 = 假

sameItem = 0

while (i

if sortedList[i-1] == sortedList[i]:
    check = True
    j = i

    while (sortedList[i-1] == sortedList[j]) and (check == True):
        sameItem += 1
        j += 1

        if (sortedList[i-1] != sortedList[j]):
            check = False
        i = j

    print(str(sortedList[i-1]) + " appears " + str(sameItem) + " times")

else:
    sameItem = 1
    print(str(sortedList[i-1]) + " appears " + str(sameItem) + " times")

i += 1

【讨论】:

  • 坦率地说,您的解决方案过于复杂。当您总是只比较相邻项目时,无需维护两个索引。 check 标志也没有任何意义。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-28
  • 2018-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-28
  • 1970-01-01
相关资源
最近更新 更多