English 中文(简体)
如果你有一个重复数值数据的数组,确定哪个素数重复得最多
原标题:If you have an array with repeated numerical data, determine which is the prime that is repeated the most

我想看看解决这个算法的路线图,我正在尝试:


cd = int(input("Enter the number of elements: "))
A = []
for i in range(cd):
 el = input("")
 A.append(el)

c = 0 
while c < cd:
 cm = 0
 c2 = 1
 while c2 < A[c]:
     if A[c] % c2 == 0:
         cm  = cm + 1  
     c2 += 1
 if cm == 2:
     P1 = A[c]
 c += 1

但后来我陷入了困境。注意代码的编写风格我希望看到解决方案的相同风格

restrictions: dictionaries are not allowed

问题回答

以下是一个可能的解决方案:

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

我们可以将问题分解为几个步骤:

  1. Extract all prime numbers from the array.
  2. Count the occurrences of each prime number.
  3. 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]:,}")




相关问题
How to add/merge several Big O s into one

If I have an algorithm which is comprised of (let s say) three sub-algorithms, all with different O() characteristics, e.g.: algorithm A: O(n) algorithm B: O(log(n)) algorithm C: O(n log(n)) How do ...

Grokking Timsort

There s a (relatively) new sort on the block called Timsort. It s been used as Python s list.sort, and is now going to be the new Array.sort in Java 7. There s some documentation and a tiny Wikipedia ...

Manually implementing high performance algorithms in .NET

As a learning experience I recently tried implementing Quicksort with 3 way partitioning in C#. Apart from needing to add an extra range check on the left/right variables before the recursive call, ...

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

Enumerating All Minimal Directed Cycles Of A Directed Graph

I have a directed graph and my problem is to enumerate all the minimal (cycles that cannot be constructed as the union of other cycles) directed cycles of this graph. This is different from what the ...

Quick padding of a string in Delphi

I was trying to speed up a certain routine in an application, and my profiler, AQTime, identified one method in particular as a bottleneck. The method has been with us for years, and is part of a "...

热门标签