[英]tournament winner python while loop
I made a function 'Match' which takes two country and return a winner according to my algorithm.我制作了一个 function 'Match',它需要两个国家并根据我的算法返回一个获胜者。
EX)前任)
def Match(England, Brazil) ----> England,
def Match(Mexico, France) ---> France
I need to write function Winner which takes list of 2^n nations and run a tournament and find a winner.我需要编写 function 获胜者,其中包含 2^n 个国家的名单并举办锦标赛并找到获胜者。
EX)前任)
def Winner([England, Brazil, Mexico, France]) ---> France
England---Brazil, Mexico---France (Semifinal)
England---France (final)
France (winner) Return value
The length of nation list differs and I cannot make a winner choosing algorithm.国家名单的长度不同,我无法制定获胜者选择算法。 The match-up is It would be great if the code uses while loop rather than for loop ^^.如果代码使用while循环而不是for循环^^,那就太好了。
Your tournament
method should make matches between consecutive pairs of players, for ["a", "b", "c", "d", "e", "f", "g", "h"]
it should be a/b
, c/d
, e/f
and g/h
您的tournament
方法应该在连续的玩家对之间进行匹配,对于["a", "b", "c", "d", "e", "f", "g", "h"]
它应该a/b
、 c/d
、 e/f
和g/h
You can achieve these with slicing and zip
您可以通过切片和zip
来实现这些
countries[::2]
takes 1 on 2 so ["a", "c", "e", "g"]
countries[::2]
对 2 取 1 所以["a", "c", "e", "g"]
countries[1::2]
same but starting at 1 so ["b", "d", "f", "h"]
countries[1::2]
相同但从 1 开始所以["b", "d", "f", "h"]
zip
pairs these 2 lists to create pairs of opponents zip
将这 2 个列表配对以创建对手配对
Keep the winner of each match, and call tournament
recursivly with the next round of players which contains half of players保留每场比赛的获胜者,并与包含一半玩家的下一轮玩家递归调用tournament
# FOR DEMO PURPOSER
def match(country_a, country_b):
return random.choice([country_a, country_b])
def tournament(countries):
n = len(countries)
if not ((n & (n - 1) == 0) and n != 0):
raise Exception("Size isn't power of 2")
if n == 2:
return match(*countries)
next_round = []
for player1, player2 in zip(countries[::2], countries[1::2]):
winner = match(player1, player2)
next_round.append(winner)
return tournament(next_round)
Using list-comprehension
the for-loop and return
can be replaced with使用list-comprehension
for-loop 和return
可以替换为
return tournament([match(p1, p2) for p1, p2 in zip(countries[::2], countries[1::2])])
After some time and discussion with the OP here's a major improvement of the full code with the major rules:经过一段时间和 OP 的讨论,这里有一个主要规则的完整代码的重大改进:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.