Python 减少元组列表
作为学习python之旅的一部分,我正在实现Bulls and Cows。Python 减少元组列表,python,tuples,reduce,Python,Tuples,Reduce,作为学习python之旅的一部分,我正在实现Bulls and Cows。 我有一个使用列表理解的工作实现,但我认为使用生成器和reduce()-ing最终结果可能是一个很好的解决方案 所以我有我的发电机: def bullsandcows(given, number): for i in range(given.__len__()): if given[i] == number[i]: yield (given[i], None)
我有一个使用列表理解的工作实现,但我认为使用生成器和
reduce()
-ing最终结果可能是一个很好的解决方案
所以我有我的发电机:
def bullsandcows(given, number):
for i in range(given.__len__()):
if given[i] == number[i]:
yield (given[i], None)
elif given[i] in number:
yield (None, given[i])
以及我的实施:
(bulls, cows) = reduce(\
lambda (bull, cow), (b, c): \
(bull + 1, cow + 1), bullsandcows(given, number), (0, 0))
其中,given
是用户输入,number
是随机生成的供用户猜测的数字
正如您所看到的,这并不是一个有效的实现,它只返回yield
ed元组的计数
我需要的是替换(牛+1,牛+1)
,我不知道如何构造它
是一个随机生成的数字,例如:number
1234
由用户输入,例如:给定的
8241
的结果将是:bullsandcows(给定,数字)
[('2',无),(无,'4'),(无,'1']
的结果应该是:reduce
,这是第一个元素的所有非(1,2)
值的计数和第二个元素的所有非None
值的计数None
- 如果我正确理解了这个过程,您需要计算哪些
bull
s不是None
,以及有多少cow
s不是None
:
reduce(lambda (bcount, ccount), (b, c): (bcount + (b is not None), ccount + (c is not None)),
bullsandcows(given, number), (0, 0))
仅当bull
或cow
值不是None
时,此测试才会增加计数器。该测试生成一个布尔值,它是int
的一个子类,具有False==0
和True==1;将一个整数和一个布尔值相加,得到另一个整数
由于您正在向其输入非空字符串,因此可以将其简化为:
reduce(lambda (bcount, ccount), (b, c): (bcount + bool(b), ccount + bool(c)),
bullsandcows(given, number), (0, 0))
我将bullsandcows()
重写为:
def bullsandcows(given, number):
given, number = map(str, (given, number))
for g, n in zip(given, number):
if g == n:
yield (g, None)
elif g in number:
yield (None, g)
e、 g.使用zip()
将给定的
和数字
的数字配对
演示:
请注意,函数参数中的解包已从Python3中删除,并且内置的reduce()
已委托给库函数;您的代码显然只是Python2
要使其在Python 3中工作,需要导入并调整lambda,使其不使用解包:
from functools import reduce
reduce(lambda counts, bc: (counts[0] + bool(bc[0]), counts[1] + bool(bc[1])),
bullsandcows(given, number), (0, 0))
当len(给定)
更清晰时,不要使用。
,当可以使用zip()时,不要使用范围()
相反。你是对的,修复了这个问题。它似乎没有忽略牛群和奶牛的输出。结果总是一个包含来自生成器的结果数的两元素元组。你忽略了lambda中的(b,c)
元组。这是正确的,这也是我的问题:)我不清楚输入是什么,以及您期望的输出是什么。elif g in str(number):
@mtadd:was get to that.:-)谢谢这完全解决了我的问题。我希望我能通过解释如何以及为什么我可以改进我的代码,为你投下另一张赞成票
from functools import reduce
reduce(lambda counts, bc: (counts[0] + bool(bc[0]), counts[1] + bool(bc[1])),
bullsandcows(given, number), (0, 0))