Advertisement
Guest User

football name chain generator, poorly done

a guest
Mar 22nd, 2023
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.81 KB | Sports | 0 0
  1. import re
  2. import collections
  3.  
  4. player_re = re.compile(r'^(?P<first>\S+)\s(?P<last>\S+)(?P<hof>\+?)\s(?P<pos>\([A-Z\-,/]*\))\s(?P<years>[\d\-]+)$', re.MULTILINE)
  5.  
  6. players = collections.defaultdict(list)
  7.  
  8.  
  9. class Player(object):
  10.    def __init__(self, first, last, hof='', pos='', years=''):
  11.       self.first = first
  12.       self.last = last
  13.       self.hof = hof
  14.       self.pos = pos
  15.       self.years = years
  16.  
  17.    def __str__(self):
  18.       return f"{self.first} {self.last}{self.hof} {self.pos} {self.years}"
  19.  
  20.  
  21. def load_players():
  22.    global players
  23.    fn = "foosball.txt"
  24.    with open(fn) as pf:
  25.       raw_players = pf.readlines()
  26.  
  27.    # filter out players who would break regex
  28.    raw_players = [p.strip() for p in raw_players if p.count(' ') == 3]  # First Last (Pos) Years
  29.  
  30.    for pstr in raw_players:
  31.       pm = player_re.match(pstr)
  32.       if not pm:
  33.          print("Regex failed on {!r}".format(pstr))
  34.          continue
  35.       P = Player(**pm.groupdict())
  36.       players[P.first].append(P)
  37.  
  38.  
  39. def print_chain(chain):
  40.    for i, n in enumerate(chain):
  41.       print(f'{i+1:03}. {n}')
  42.  
  43.  
  44. def traverse(name, chain):
  45.    if name not in players:
  46.       yield chain
  47.    for p in players[name]:  # todo could sort more greedily
  48.       if p not in chain:
  49.          for res in traverse(p.last, chain + [p]):
  50.             yield res
  51.    yield chain
  52.  
  53.  
  54. def main():
  55.    load_players()
  56.  
  57.    longest_chain = []
  58.    i = 0
  59.    for fn in sorted(players, key=lambda n: len(players[n]), reverse=True):  # start with most common names
  60.       chain = []
  61.       print(i)
  62.       for res in traverse(fn, chain):
  63.          if len(res) > len(longest_chain):
  64.             print("\n{}. new longest chain ({}):".format(i, len(res)))
  65.             print_chain(res)
  66.             longest_chain = res
  67.       i += 1
  68.  
  69.  
  70. if __name__ == "__main__":
  71.    main()
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement