以下是一个可能的解决方案:
def is_prime(n: int) -> bool:
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
i = 3
while i**2 <= n:
if n % i == 0:
return False
i += 2
return True
cd = int(input("Enter the number of elements: "))
A = []
for i in range(cd):
el = int(input(""))
A.append(el)
# Dictionary `prime_counts` will contain the number of times that each prime
# number appears in list `A`. The dictionary will have the following structure:
# - Keys: prime number
# - Values: number of times the prime number appears on list `A`
prime_counts = {}
for el in A:
if is_prime(el): # Check if number is prime
# Add new key to the `prime_counts` dictionary if key doesn’t already
# exist..
if el not in prime_counts.keys():
prime_counts[el] = 0
# Add 1 to the prime counting
prime_counts[el] += 1
# Finding which prime number repeats the most
max_count = max(prime_counts.items(), key=lambda kv: kv[1]) # Returns a tuple, like (139, 121)
# Where:
# - 139: is the prime number that repeats the most
# - 121: frequency that the number repeats
print(f"The prime number {max_count[0]:,} repeats most frequently: {max_count[1]:,}")
# Prints something like:
# "The prime number 139 repeats most frequently: 121"
Testing
为了测试该解决方案,我们将使用random
包生成20000个值在0到200之间的随机数。
import random
cd = 20_000
A = [random.randint(0, 200) for _ in range(cd)]
prime_counts = {}
for el in A:
if is_prime(el):
if el not in prime_counts.keys():
prime_counts[el] = 0
prime_counts[el] += 1
max_count = max(prime_counts.items(), key=lambda kv: kv[1])
print(f"The prime number {max_count[0]:,} repeats most frequently: {max_count[1]:,}")
# Prints:
# "The prime number 173 repeats most frequently: 127"
Detailed Overview
我们可以将问题分解为几个步骤:
- Extract all prime numbers from the array.
- Count the occurrences of each prime number.
- Identify the prime number with the highest count.
您开始使用的代码并不完全正确,因为它试图检查列表中每个数字的素性,但它没有跟踪计数。
定义函数is_prime
有助于我们检查一个数字是否为素数:
def is_prime(n):
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
i = 3
while i * i <= n:
if n % i == 0:
return False
i += 2
return True
Next, we can modify your original code to create a list of prime numbers and
count their occurrences:
cd = int(input("Enter the number of elements: "))
A = []
for i in range(cd):
el = int(input(""))
A.append(el)
prime_counts = {}
for el in A:
if is_prime(el):
if el not in prime_counts.keys():
prime_counts[el] = 0
prime_counts[el] += 1
最后,使用max
函数,我们可以找到最常出现的素数:
max_count = max(prime_counts.items(), key=lambda kv: kv[1]) # Returns a tuple, like (139, 121)
# Note: kv stands for "key-value"
print(f"The prime number {max_count[0]:,} repeats most frequently: {max_count[1]:,}")