从极客到极客有限范围阵列元件的频率问题



这是gfg必做题的练习。但是我的代码并没有通过所有的测试用例。有人能帮我吗。

Wrong Answer. !!!Wrong Answer
Possibly your code doesn't work correctly for multiple test-cases (TCs).
The first test case where your code failed:
Input:
37349
27162 38945 3271 34209 37960 17314 13663 17082 37769 2714 19280 17626 34997 33512 29275 25207 4706 12532 34909 23823 272 29688 19312 8154 5091 26858 30814 19105 14105 11303 16863 1861 2961 36601 10157 114 11491 31810 29152 2627 14327 30116 14828 37781 38925 16319 10972 4506 18669 19366 28984 6948 15170 24135 6256 38121 3835 38031 9855 25152 19132 23573 29587 1719 33440 26311 12647 23022 34206 39955 3791 18555 336 7317 12033 7278 27508 5521 24935 15078 915 35478 37253 6863 39182 23429 33867.................
Its Correct output is:
2 4 1 2 5 2 0 4 1 3 1 2 1 3 2 4 4 1 1 0 2 0 4 1 3 5 1 0 1 2 1 3 2 0 1 1 2 0 0 2 1 2 2 1 4 2 0 1 2 2 0 1 2 0 2 4 4 5 2 5 2 1 5 1 2 1 0 1 1 2 2 1 3 1 2 0 3 4 1 2 0 2 3 5 2 2 1 3 1 4 0 3 5 1 1 3 1 2 2 3 2 2 4 1 1 3 1 4 3 4 0 2 1 4 4 2 2 3 3 0 0 0 4 1 2 1 2 4 1 3 1 2 4 0 2 1 1 1 0 3 4 3 2 0 3 0 0 0 1 1 0 0 2 2 3 0 1 2 2 2 0 2 3 2 1 1 3 0 1 5 1 1 1 0 2 0 3 1 2 1 1 1 2 3 3 1 1 3 1 4 1 3 1 1 1 2 2 0 1 0 2 2 0 2 2 2 1 4 1 0 3 1 2 0 3 1 2 1 8 3 0 0 1 1 1 1 2 1 1 4 1 3 0 3 2 1 1 1 1 2 4 2 2 1 4 2 1 3 1 0 .................
And Your Code's output is:
1 0 0 0 1 0 0 1 0 2 1 2 0 0 1 1 2 1 1 0 0 0 2 1 2 2 0 0 1 0 1 2 2 0 1 1 1 0 0 1 0 1 0 0 1 0 0 0 1 1 0 1 1 0 1 2 3 3 2 2 2 1 3 1 1 1 0 1 0 1 0 0 1 1 2 0 1 3 1 0 0 2 1 4 0 1 0 1 0 3 0 1 2 0 0 1 1 1 1 3 1 0 2 1 0 3 1 3 2 2 0 2 0 2 3 1 0 0 1 0 0 0 3 0 0 0 1 3 1 2 0 1 2 0 2 0 0 0 0 2 2 2 1 0 0 0 0 0 1 0 0 0 2 2 2 0 0 0 1 2 0 0 2 1 1 1 2 0 1 3 0 1 0 0 1 0 1 1 1 0 0 0 1 1 0 1 0 2 0 2 1 3 1 0 1 2 0 0 1 0 1 1 0 1 2 1 0 3 0 0 1 0 1 0 2 0 2 1 4 2 0 0 1 0 0 1 2 0 0 1 0 2 0 2 2 1 0 0 0 0 2 0 1 0 2 1 0 2 0 0 .................

给定一个由n个正整数组成的数组A[],它可以包含从1到n的整数,其中元素可以重复,也可以不在数组中。你的任务是计算从1到n的所有元素的频率。

输入:n=5A[]={2,3,2,3,5}输出:0 2 2 0 1说明:计数每个阵列元素的频率我们有:1出现0次。2发生2次。3发生2次。4出现0次。5发生1次。

问题链接:https://practice.geeksforgeeks.org/problems/frequency-of-array-elements-1587115620/1

class Solution:
#Function to count the frequency of all elements from 1 to N in the array.
def frequencycount(self,A,N):
s = {}
for i in A:
if i in s:
s[i] += 1
else:
s[i] = 1
for i in range(1,len(A)+1):
if i in s:
A[i-1] = s[i]
else:
A[i-1]=0

return A
#{ 
#  Driver Code Starts
#Initial Template for Python 3
import math
if __name__=="__main__":
T=int(input())
while(T>0):
N=int(input())
A=[int(x) for x in input().strip().split()]
ob=Solution()
ob.frequencycount(A,N)
for i in range (len (A)):
print(A[i], end=" ")
print()
T-=1

# } Driver Code Ends

假设您有一个列表

l = [0,2,5,6,0,5,3]

然后你可以做:

res = [l.count(e) for e in range(max(l))]

这将给出一个数组,其中包含字母e在原始列表中出现的次数。

最新更新