📜  Python – 测试独特的频率

📅  最后修改于: 2022-05-13 01:55:22.657000             🧑  作者: Mango

Python – 测试独特的频率

给定一个列表,找出每个值元素的频率本身是否是唯一值。

方法 #1:使用循环 + set()
上述功能的组合提供了解决这个问题的蛮力方法。在此,我们通过增加值的索引来记住元素的频率。然后 set() 用于删除重复并测试它的长度是否与转换前相同。

Python3
# Python3 code to demonstrate working of
# Test for Unique Frequencies
# Using loop + set()
 
# initializing list
test_list = [4, 3, 2, 2, 3, 4, 4, 4, 1, 2]
 
# printing original list
print("The original list : " + str(test_list))
 
# Test for Unique Frequencies
res = False
temp = [0] * 5
for ele in test_list:
     
    # performing memoization in temp list
    temp[ele] += 1
mem_list = temp[1:]
 
# checking for set converted list length with original list
if len(list(set(mem_list))) == len(mem_list):
    res = True
     
# printing result
print("Are element's Frequencies Unique ? : " + str(res))


Python3
# Python3 code to demonstrate working of
# Test for Unique Frequencies
# Using setdefault() + values()
 
# initializing list
test_list = [4, 3, 2, 2, 3, 4, 4, 4, 1, 2]
 
# printing original list
print("The original list : " + str(test_list))
 
# Test for Unique Frequencies
# Using setdefault() + values()
temp = {}
for ele in test_list:
     
    # setting default value to 0
    temp.setdefault(ele, 0)
    temp[ele] += 1
 
# checking for values and keys equality
res = len(set(temp.values())) == len(temp)
     
# printing result
print("Are element's Frequencies Unique ? : " + str(res))


输出 :
The original list : [4, 3, 2, 2, 3, 4, 4, 4, 1, 2]
Are element's Frequencies Unique ? : True


方法 #2:使用 setdefault() + values()
上述功能的组合提供了另一种解决此问题的方法。在此,字典用于记忆,元素频率记录为值。最后,将提取值和字典键计数的类似步骤进行相等性比较。

Python3

# Python3 code to demonstrate working of
# Test for Unique Frequencies
# Using setdefault() + values()
 
# initializing list
test_list = [4, 3, 2, 2, 3, 4, 4, 4, 1, 2]
 
# printing original list
print("The original list : " + str(test_list))
 
# Test for Unique Frequencies
# Using setdefault() + values()
temp = {}
for ele in test_list:
     
    # setting default value to 0
    temp.setdefault(ele, 0)
    temp[ele] += 1
 
# checking for values and keys equality
res = len(set(temp.values())) == len(temp)
     
# printing result
print("Are element's Frequencies Unique ? : " + str(res))
输出 :
The original list : [4, 3, 2, 2, 3, 4, 4, 4, 1, 2]
Are element's Frequencies Unique ? : True