Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from pathlib import Path
- from random import shuffle
- from collections import defaultdict
- from operator import itemgetter
- from argparse import ArgumentParser
- """
- Text der beschreiben soll was das Programm macht.
- """
- CLEAR_SCREEN = "\x1b[2J\x1b[H"
- def get_candidates(file):
- with open(file) as fd:
- for line in map(str.strip, fd):
- if line:
- yield line.strip().title()
- def make_dict(candidates):
- random_candidates = candidates.copy()
- shuffle(random_candidates)
- return {idx: candidate for idx, candidate in enumerate(random_candidates, start=1)}
- def ask(candidates_seq):
- results = defaultdict(int)
- while True:
- candidates = make_dict(candidates_seq)
- print("Es stehen folgende Kandidaten zur Wahl:")
- for idx, candidate in candidates.items():
- print(f"{idx:<3d} -> {candidate}")
- while True:
- user_input = input(
- "Bitte Kandidaten-Nr. zur Wahl eingeben oder q zum beenden: "
- )
- if user_input.strip().lower() == "q":
- return results
- try:
- value = int(user_input)
- except ValueError:
- print("Bitte eine Ganzzahl eingeben.")
- continue
- if value not in candidates:
- print(f"Einen Kandidaten mit der Nummer {value} gibt es nicht.")
- else:
- results[candidates[value]] += 1
- print(CLEAR_SCREEN)
- break
- def output_results(results):
- candidates = [
- candidate
- for candidate, _ in sorted(results.items(), key=itemgetter(1), reverse=True)
- ]
- for candidate in candidates:
- print(f"{candidate} hat {results[candidate]} Stimmen bekommen")
- def parse():
- parser = ArgumentParser(
- description="Ein ganz tolles Wahlprogramm, dass niemand benutzen möchte."
- )
- parser.add_argument(
- "kandidaten", type=Path, help="Datei mit Kandidaten. Ein Kandidat pro Zeile."
- )
- args = parser.parse_args()
- if not args.kandidaten.exists():
- raise RuntimeError("Datei Existiert nicht")
- return args
- if __name__ == "__main__":
- args = parse()
- print(CLEAR_SCREEN)
- try:
- candidates = list(get_candidates(args.kandidaten))
- except RuntimeError as e:
- print(e)
- else:
- results = ask(candidates)
- output_results(results)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement