繁体   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