我正在尝试编写代码,以确定一个数字数组中是否至少有3个相等的元素。
例如,如果我有数组:
[1,5,5,5]
然后输出:
True
示例2:
[5,5,5,5]
输出:
True
示例3:
[1,1,5,5]
输出:
False
我尝试过:
arr = [1,5,5,5]
count = 0
for i in range(len(arr)-1):
if arr[i] == arr[i+1]:
count +=1;
if count >=3:
print("True")
else:
print("False")
但是我得到了输出:
False
在这种情况下应该是正确的,因为数组中确实存在至少3个相等的元素。
答案 0 :(得分:2)
您的示例中有一个错字,请使用count>=2
:
if count >=2:
print("True")
else:
print("False")
请记住,如果找到第二个“ 5”,则增加+1;找到第三个“ 5”时,将进行另一次递增。
答案 1 :(得分:0)
使用Counter
def check(my_list):
from collections import Counter
counter = Counter(my_list)
return max(counter.values()) > = 3
答案 2 :(得分:0)
尝试使用计数器:
from collections import Counter
def has_3_repeats(arr):
counter = Counter(arr)
return any(val >= 3 for val in counter.values())
如果阵列数量巨大,您可以懒惰地执行此操作,并在需要时立即停止:
from collections import defaultdict
def has_3_repeats_lazy(arr):
counter = defaultdict(lambda: 0)
for x in arr:
counter[x] += 1
if counter[x] >= 3:
return True
return False
答案 3 :(得分:0)
1)
from collections import defaultdict
arr = [1,5,5,5] # True if arr = [1,5,5,7,5] then also it should print True
num_count_dict = defaultdict(int)
for num in arr:
num_count_dict[num]+= 1
if num_count_dict[num] == 3:
print("True")
break
else:
print("False")
2)
# They need to be consecutive
arr2 = [1,5,5,5] # True but if arr2 = [1,5,5,7,5] it should print False
count =0
for i in range(len(arr2)-1):
if arr2[i] == arr2[i+1]:
count += 1
else:
count = 1 # count of new number
if count == 3:
print("True")
break
else:
print("False")