和可能性,一个循环

2024-09-28 05:26:17 发布

您现在位置: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)  

我只需要通过查看当前元素是否存在于元素列表中,使这段代码无需迭代就可以找到求和。在


Tags: the函数元素getreturnif字典is
1条回答
网友
1楼 · 发布于 2024-09-28 05:26:17

您可以使用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

^{pr2}$

相关问题 更多 >

    热门问题