[英]Reduce list of tuples
在學習python的過程中,我正在實施Bulls and Cows。
我有一個使用列表推導的有效實現,但我認為這可能是使用生成器並reduce()
最終結果的解決方案。
所以我有我的發電機:
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元組的計數。
我需要的是(bull + 1, cow + 1)
的替代品,我不知道如何構造它。
number
是隨機生成的數字,例如: 1234
given
的由用戶輸入,例如: 8241
bullsandcows(given, number)
將是: [('2', None), (None, '4'), (None, '1']
reduce
應該是: (1, 2)
這是所有非的計數None
所有非的第一個元素和計數的值None
第二元件的值 如果我正確地理解了該過程,那么您想計算哪些bull
不是None
,有多少cow
不是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)
例如,使用zip()
given
數字和number
配對。
演示:
>>> 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)
...
>>> given, number = 8241, 1234
>>> list(bullsandcows(given, number))
[('2', None), (None, '4'), (None, '1')]
>>> reduce(lambda (bcount, ccount), (b, c): (bcount + bool(b), ccount + bool(c)),
... bullsandcows(given, number), (0, 0))
(1, 2)
注意,從Python 3中刪除了函數參數的解包,並且內置的reduce()
已委托給庫函數; 您的代碼肯定僅是Python 2。
要使其在Python 3中工作,您需要導入functools.reduce()
並將lambda調整為不使用拆包:
from functools import reduce
reduce(lambda counts, bc: (counts[0] + bool(bc[0]), counts[1] + bool(bc[1])),
bullsandcows(given, number), (0, 0))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.