繁体   English   中英

锦标赛冠军 python while 循环

[英]tournament winner python while loop

我制作了一个 function 'Match',它需要两个国家并根据我的算法返回一个获胜者。
前任)

def Match(England, Brazil) ----> England, 
def Match(Mexico, France) ---> France  

我需要编写 function 获胜者,其中包含 2^n 个国家的名单并举办锦标赛并找到获胜者。
前任)

def Winner([England, Brazil, Mexico, France]) ---> France 

England---Brazil,        Mexico---France  (Semifinal)

England---France (final)

France (winner) Return value

国家名单的长度不同,我无法制定获胜者选择算法。 如果代码使用while循环而不是for循环^^,那就太好了。

您的tournament方法应该在连续的玩家对之间进行匹配,对于["a", "b", "c", "d", "e", "f", "g", "h"]它应该a/bc/de/fg/h

您可以通过切片和zip来实现这些

  • countries[::2]对 2 取 1 所以["a", "c", "e", "g"]

  • countries[1::2]相同但从 1 开始所以["b", "d", "f", "h"]

  • zip将这 2 个列表配对以创建对手配对

保留每场比赛的获胜者,并与包含一半玩家的下一轮玩家递归调用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)

使用list-comprehension for-loop 和return可以替换为

return tournament([match(p1, p2) for p1, p2 in zip(countries[::2], countries[1::2])])

改进完整代码

经过一段时间和 OP 的讨论,这里有一个主要规则的完整代码的重大改进:

  • 不要在循环中调用完全相同的方法,在外面做
  • 如果方法相同,请不要一次又一次地调用方法,将数据存储在某处

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM