1. Rock-paper-scissors¶
Implement rock_paper_scissors function which takes the player's rock-paper-scissors choice as an input (as integer), randomly selects the choice of the computer and reveals it (prints) and finally announces (prints) the result. The function should return PLAYER_WINS, COMPUTER_WINS or TIE.
# Constants, you should use these in your implementation
ROCK = 1
PAPER = 2
SCISSORS = 3
PLAYER_WINS = "Player wins!! Woop woop!"
COMPUTER_WINS = "Robocop wins :-("
TIE = "It's a tie!"
# Your implementation here
Once you have finished the implementation of rock_paper_scissors function, you can check if it works as expected by playing the game:
def play_rps():
print("Welcome to play rock-paper-scissors")
print("The options are:\nrock: 1\npaper: 2\nscissors: 3")
result = TIE
while result == TIE:
player_choice = input("Give your choice\n")
if not player_choice in ["1", "2", "3"]:
print("Invalid choice")
continue
result = rock_paper_scissors(int(player_choice))
if __name__ == "__main__":
play_rps()
If you copy the code from above cells into a single .py file, you have a rock-paper-scissor command line game!
2. Data analyzer¶
Implement DataAnalyzer class which has the following specification:
__init__takes one argument which is a path to the file to be analyzedtotal_samplesmethod returns the amount of the data samples in the fileaveragemethod returns the average of the data samples in the filemedianmethod returns the median of the data samples in the filemax_valuemethod returns the maximum value of the data samples in the filemin_valuemethod returns the minimum value of the data samples in the filecreate_reportmethod returns a report (string) of the file in the following format:
Report for <filename>
samples: x
average: x.xx
median: xx.xx
max: xx.xx
min: x.xx
Note that average, median, max, and min should be presented with two decimal places in the report.
The format of the input file is comma separated and the file contains only numeric values.
If there is no data in the input file (empty file), NoData exception should be raised. Note: NoData should be your custom exception.
# Your implementation here
Let's verify it works.
from pathlib import Path
WORKING_DIR = Path.cwd()
DATA_DIR = WORKING_DIR.parent / "data"
DATA_FILE = DATA_DIR / "random_data.txt"
da = DataAnalyzer(DATA_FILE)
assert da.total_samples() == 20
assert da.average() == 49.35
assert da.median() == 47.5
assert da.max_value() == 94
assert da.min_value() == 4
report = da.create_report()
print(report)
expected_report = (
"Report for random_data.txt\n"
"samples: 20\n"
"average: 49.35\n"
"median: 47.50\n"
"max: 94.00\n"
"min: 4.00"
)
assert report == expected_report
Let's check that it raises NoData with empty file.
EMPTY_FILE = DATA_DIR / "empty_file.txt"
try:
da_empty = DataAnalyzer(EMPTY_FILE)
except NoData:
print("All ok :)")
else: # There was no exception
assert False