🐍 Python Weekly Coding Challenge - The tournament of kingdoms #154864
Unanswered
mecodeatlas
asked this question in
Programming Help
Replies: 2 comments
-
My solutioncode:# This function returns the list of kindoms battling
def create_kingdoms_list(battles: list):
list_of_kingdoms_battling: set = set()
for battle in battles:
# The ranging skips every score of the kingdoms
for kingdom in battle[0:3:2]:
list_of_kingdoms_battling.add(kingdom)
return list_of_kingdoms_battling
# This function returns a empty score card of all kingdoms with the points won by them as 0
def create_score_card(kingdoms_list):
kingdoms_score: dict = {}
for kingdom in kingdoms_list:
kingdoms_score[kingdom] = 0
return kingdoms_score
# This function sorts a dictionary based on the values i.e the points won by each kingdom
def sort_dictionary(dictionary):
return dict(sorted(dictionary.items(), key=lambda item: item[1], reverse=True))
# This function returns the dictionary of kingdoms and the total points won by them in the tournamet
def check_for_winners(battles, scores_of_kingdoms):
for battle in battles:
kingdomA, kingdomA_score = battle[0], battle[1]
kingdomB, kingdomB_score = battle[2], battle[3]
if kingdomA_score > kingdomB_score:
scores_of_kingdoms[kingdomA] += 3
elif kingdomA_score == kingdomB_score:
scores_of_kingdoms[kingdomA] += 1
scores_of_kingdoms[kingdomB] += 1
else:
scores_of_kingdoms[kingdomB] += 3
return scores_of_kingdoms
# This function returns the ranking table for the tornament in sorted manner
def generate_ranking_table(battles: list):
kingdoms: set = create_kingdoms_list(battles)
scores_of_kingdoms = create_score_card(kingdoms)
return sort_dictionary(check_for_winners(battles, scores_of_kingdoms))
battles = [
("Northern Kingdom", 3, "Southern Kingdom", 1),
("Eastern Kingdom", 2, "Western Kingdom", 2),
("Northern Kingdom", 1, "Eastern Kingdom", 2),
]
ranking_table = generate_ranking_table(battles)
# This code snippet prints the ranking table in the requested manner
for item in ranking_table.items():
print(item[0], ":", item[1], "points")
My approach for the problem:
|
Beta Was this translation helpful? Give feedback.
0 replies
-
|
Fun little problem. Here's how I did it: Filesmanager.pyfrom collections import defaultdict
from typing import List, NamedTuple, DefaultDict
class BattlesInput(NamedTuple):
kingdom_A: str
score_A: int
kingdom_B: str
score_B: int
class TournamentManager(object):
def __init__(self):
self.team_dict: DefaultDict[str, int] = defaultdict(int)
def _calculate_winner(self, battle: BattlesInput) -> None:
if battle.score_A == battle.score_B: # draw = 1 point per kingdom
self.team_dict[battle.kingdom_A] += 1
self.team_dict[battle.kingdom_B] += 1
elif battle.score_A > battle.score_B: # kingdom A wins
self.team_dict[battle.kingdom_A] += 3
self.team_dict[battle.kingdom_B] += 0
else: # kingdom B wins
self.team_dict[battle.kingdom_B] += 3
self.team_dict[battle.kingdom_A] += 0
def run_tournament(self, battles: List[BattlesInput]) -> None:
for battle in battles:
self._calculate_winner(battle)
def print_results(self) -> None:
f_s = '{0}: {1} points'
# ensure that we're getting the results sorted in descending order according to points totals
for kingdom, score in sorted(self.team_dict.items(), key=lambda val: val[1], reverse=True):
if score == 1:
print(f_s[:-1].format(kingdom, score))
else:
print(f_s.format(kingdom, score))main.py#!/usr/bin/env python3
import csv
from sys import argv, stderr, exit
from typing import List
from manager import BattlesInput, TournamentManager
if __name__ == '__main__':
scores: List[BattlesInput] = []
tm = TournamentManager()
if len(argv) != 2: # treat this like we want to handle a file
print("File needed to parse", file=stderr)
exit(1)
filename = argv[1]
with open(filename, 'r') as infile:
reader = csv.reader(infile)
next(reader)
for row in reader:
row = [ent.lstrip() for ent in row]
scores.append(BattlesInput(
kingdom_A=row[0],
score_A=int(row[1]),
kingdom_B=row[2],
score_B=int(row[3])
))
tm.run_tournament(scores)
tm.print_results()The goal was to keep the code for the scorecard as minimal as possible, which I think I was able to do in the class in |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
This is the second of four challenges designed to test and improve your Python skills. Each week, you'll tackle a new problem focusing on logic, data manipulation, and efficiency. Engage with others, share your ideas, and collaborate to find creative solutions—this is a space to learn and grow together! 🚀
General rules
Evaluation criteria (Total: 100 points)
Now, let’s dive into the first challenge! 🔥
The tournament of kingdoms
In a medieval world, several kingdoms compete in an annual tournament.
You have been assigned to develop a system that calculates each kingdom’s score based on battle results.
Objective
Create a program that processes battle results and generates a ranking table for the kingdoms.
Input & Output
Input: A list of tuples, where each tuple contains Kingdom A’s name, Kingdom A’s score, Kingdom B’s name, and Kingdom B’s score.
Example:
Expected Output:
Rules
Difficulty levels
Good luck :)
Guidelines
Beta Was this translation helpful? Give feedback.
All reactions