总和可能性,一个循环

时间:2012-06-13 00:46:29

标签: python

早些时候我有很多优秀的程序员帮我完成一项功能。但是教师希望它在一个循环中,并且所有工作解决方案都使用了多个循环。

我写了另一个几乎解决问题的程序。您不必使用循环来比较所有值,而是必须使用函数has_key来查看该特定键是否存在。对此的回答将使您无需通过字典查找匹配值,因为您可以知道它们是否匹配。 再次,charCount只是一个函数,它将自身的常量输入字典并返回字典。

def sumPair(theList, n):
    for a, b in level5.charCount(theList).iteritems():    
        x = n - a     
        if level5.charCount(theList).get(a):
            if a == x:
                if b > 1: #this checks that the frequency of the number is greater then one so the program wouldn't try to multiply a single possibility by itself and use it (example is 6+6=12. there could be a single 6 but it will return 6+6
                    return a, x
            else:
                if level5.charCount(theList).get(a) != x:
                    return a, x           
print sumPair([6,3,8,3,2,8,3,2], 9)  

我需要通过查看当前元素是否存在于元素列表中来使这段代码在没有迭代的情况下找到总和。

1 个答案:

答案 0 :(得分:4)

您可以使用collections.Counter功能代替level5.charCount

我不知道为什么你需要检查if level5.charCount(theList).get(a):。我认为没有必要。 a是您从level5.charCount(theList)

获得的关键

所以我简化了代码:

form collections import Counter

def sumPair(the_list, n):
    for a, b in Counter(the_list).iteritems():
        x = n - a
        if a == x and b >1:
            return a, x
        if a != x and b != x:
            return a, x

print sumPair([6, 3, 8, 3, 2, 8, 3, 2], 9)   #output>>> (8, 1)

也可以像这样使用List Comprehension

>>>result = [(a, n-a) for a, b in Counter(the_list).iteritems() if a==n-a and b>1 or (a != n-a and b != n-a)]
>>>print result
[(8, 1), (2, 7), (3, 6), (6, 3)]
>>>print result[0]   #this is the result you want
(8, 1)