【问题标题】:Python: returning a pair of each number and its frequency in given array using count-sorting algorithm [duplicate]Python:使用计数排序算法在给定数组中返回一对每个数字及其频率
【发布时间】:2017-11-27 10:55:16
【问题描述】:

我有一个给定的数组:

A = [9, 8, 7, 6, 5, 4]

我正在实现计数排序算法来在 Python 中对这个数组进行排序。 数组中的数字总是在 N 范围内。

我得到了每个元素的计数和列表的排序。

count = [0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
sorted = [4, 5, 6, 7, 8, 9]

现在,我想输出每个元素的计数: 例如:

4 1
5 1
6 1
7 1
8 1
9 1

如何将它们与列表 [count & array] 进行比较?

代码:

N = int(input())
A = list(map(int, input().split(" ")))

print(A)
m = N + 1

count = [0] * m

for a in A:
    # count occurences
    count[a] += 1
print(count)

i = 0
for a in range(m):
    for c in range(count[a]):
        A[i] = a
        i += 1
print(A, count)

print([i,j for i,j in zip(A,count)])

我尝试压缩,但效果不佳。我该怎么做?

【问题讨论】:

  • 数组中的数字总是在1到9之间?您的问题并未表明这一点,也不是很清楚。
  • python 列表!= 数组...

标签: python list sorting compare


【解决方案1】:

这行得通:

count = [0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
sorted = [4, 5, 6, 7, 8, 9]

for elem in sorted:
    print(elem, count[elem])

【讨论】:

  • 这很简单!谢谢!
  • 如果您喜欢我的回答,请投票给它,如果它是对您帮助最大的答案,请接受它。谢谢。
  • 此代码适用于小数据...但是当我将输入大小设置为 100 并将这些数字作为我的数组运行时:80 42 99 34 54 72 78 53 1 19 28 84 3 56 64 17 86 82 17 16 2 77 83 97 30 8 35 85 40 93 54 53 3 38 19 81 74 19 6 98 5 60 72 10 32 71 40 68 1 39 11 66 68 3 88 88 87 30 8 27 78 174 9 19 43 17 96 98 63 27 95 9 13 20 47 16 95 55 29 86 44 42 67 62 100 2 17 32 99 30 75 92 43 77 39 3 我得到错误的输出。为什么这样?任何的想法?你能运行我的代码并用这个数组检查它吗?
  • @TarakShah:小数据是什么意思?
  • 表示如果我的输入少于 9 个数字,它就可以工作。但是对于上面的大量数字,它会给出错误的输出..
猜你喜欢
  • 1970-01-01
  • 2021-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
  • 2020-12-27
  • 2011-01-31
  • 1970-01-01
相关资源
最近更新 更多