簡體   English   中英

檢查列表中兩個數字中的哪個數字可以使總和等於 k

[英]Check which number out of two numbers in the list can make the sum equals to k

我正在解決一個編程問題,但我被困在一個地方..

import itertools

N=int(input())
#finding all prime between a range
primes=[x for x in range(2, N) if all(x % y != 0 for y in range(2, x))]
print(primes)
try:
    pairs=[min(p for p in itertools.combinations(primes, 2) if sum(p) == N)]
except:
    pairs=[(p for p in itertools.combinations(primes, 2) if sum(p) == N)]

print(*pairs)

在這段代碼中,我想找到價值最小的一對素數,它們可以加起來等於 N 的值

例如:案例 1)如果我輸入 74 然后它返回 [71,3] 盡管 74 甚至可以通過其他組合來計算但是有 3 個是所有組合中最少的

case2) 如果我輸入 4,此代碼將返回 [2,3] 作為答案,我知道為什么 .. 預期答案是 [2,2]..說明只有這種組合才有可能獲得等於 N 的總和

你得到空生成器 object 作為響應不是[2, 3]這是素數列表

您的工作解決方案使用itertools.combinations_with_replacement

import itertools

N = int(input())
#finding all prime between a range
primes = [x for x in range(2, N) if all(x % y != 0 for y in range(2, x))]
print(primes)
try:
    pairs = [min(p for p in itertools.combinations_with_replacement(primes, 2) if sum(p) == N)]
except:
    pairs = [p for p in itertools.combinations_with_replacement(primes, 2) if sum(p) == N]

for pair in pairs:
    print(pair)

Output:

[2, 3] # list of prime number for input 4
(2, 2) # solution

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM