早些时候我有很多优秀的程序员帮我完成了一个函数。然而,老师希望它在一个循环中,所有的工作解决方案都使用多个循环。在
我写了另一个程序,几乎解决了这个问题。与使用循环来比较所有值不同,您必须使用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)
我只需要通过查看当前元素是否存在于元素列表中,使这段代码无需迭代就可以找到求和。在
您可以使用collections.Counter函数代替
level5.charCount
我不知道你为什么要检查
if level5.charCount(theList).get(a):
。我觉得没必要。a
是从level5.charCount(theList)
获得的密钥所以我简化了代码:
也可以像这样使用List Comprehension:
^{pr2}$相关问题 更多 >
编程相关推荐