簡體   English   中英

python:在數組中找到兩個乘以20的元素

[英]python: Find two elements in array that multiply to 20

我有一個元素數組,我想在其中找到兩個元素,乘以20。我需要幫助解決這個使用哈希表。 test_array的預期輸出應輸出4和5,產品為20.謝謝

test_array = [2,4,1,6,5,40]

counts = {}

for element in test_array:
    if 20 % element == 0 
        counts[element] = 20/element
    else:
        None
print counts

您應該將除法的結果作為字典的鍵,而不是列表的當前元素。

for element in test_array:
    if 20 % element == 0:
        counts[20/element] = element
for element in test_array:
    if element in counts:
        print("%d * %d" % (element, counts[element]))
        break
else:
    print "No pair found"

如果你想要所有的元素和乘數

>>> dict((element, multiplier) for element in test_array for multiplier in test_array if element * multiplier == 20)
{4: 5, 5: 4}

你可以做一些其他細微的修改,但如果我理解正確,這似乎符合你的問題的要求......

如果你真的只想要4和5,因為這兩個元素都可以乘以20

[element for element in test_array for multiplier in test_array if element * multiplier == 20]
>>> [4, 5]

如果您的測試數組有所不同,並且您想要一個鍵值對,但可能不需要重復,那么您可以再做一些工作來檢查

for e in test_array:
    for m in test_array:
        if e * m == 20:
            if e in counts.values() and m in counts.keys():
                continue
            counts[e] = m

print(counts)
>>> {4: 5}

我強烈建議你,如果你想看看發生了什么,你就會分解理解並把打印聲明放進去。 謝謝

如果你想使用modulo和division,你可以刪除額外的for循環:

for element in test_array:
    if 20 % element == 0 and int(20/element) in test_array:
        if int(20/element) in counts.values() and element in counts.keys():
            continue
        counts[int(20/element)] = element

print(counts)

如果你想要很好地打印一切:

for k, v in counts.items(): print("%s * %s = 20" % (k, v))
{tuple(sorted((x, 20//x))) for x in test_array \
    if 20 % x == 0 and 20//x in test_array}

# {(4, 5)}

暫無
暫無

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

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