Python Standard Library Challenges
Contents
- Dice Class
- Loaded Dice Class
- Prove that a dice is loaded
- Hangman game
- Calculate Factorial
- Calculate sin(x)
Dice Class
Create a Dice class with the following characteristics
- When you roll the dice, you get a random number between 1 and 6
from random import uniform class Dice: def __init__ (self) : pass def roll (self) : return round(uniform (1,7))
d = Dice() d.roll()
Loaded Dice Class
Create a Loaded Dice with the following characteristics
- Dice should be initialized with the load number ( Meaning, if the dice is loaded to show the number 5 higher number of times than the rest, it should be set at the time of initializing ).
- When you roll the dice, you get a random number between 1 and 6. However 50% of the time the dice should always return the loaded number.
from random import uniform class LoadedDice: def __init__ (self, load) : self.load = load def roll (self) : r = round(uniform(1,7)) if round(uniform(0,2)) == 1 : return r else : return self.load
d = LoadedDice(3) d.roll()
Prove that a dice is loaded
Test the Dice and LoadedDice and prove that statistically one class is unloaded and the other is loaded. Ideally, you should look at the histogram and verify that it is a normal distribution or not. However, for now just check that the mean of Dice is 3 or close to 3, while the mean of LoadedDice is not.
- Take the output of each of the classes a large number( say 10,000 ) times
- Calculate the mean of each of the samples.
# holds the output of dice d_list = [] # holds the output of loaded dice ld_list = [] d = Dice() ld = LoadedDice(6) for i in range(10000) : d_list.append(d.roll()) ld_list.append(ld.roll())
from statistics import mean print ( mean(d_list) ) print ( mean(ld_list) )
Calculate Factorial
Calculate Factorial of a number without using the built-in factorial function.
solutionnumber = int(input("enter number -")) factorial = 1 if number < 0 : print ("enter a positive number") elif number == 0 : print ( " factorial of 0 is 1") else : # assuming it is a positive integer ( and not a float ) for i in range(1, number + 1) : factorial = factorial * i print ( "Factorial of", number, " is", factorial)
Factorial of 30 is 265252859812191058636308480000000
Hangman game
Hangman is a word guessing game. The computer guesses a word (you can either use a list of words from a file or use a third party library like RandomWords) and asks you to guess the word one letter at a time. If you have guessed a correct letter, it shows you that you have guessed the letter correctly and positions the letter in the correct sequence in the word and shows it to you ( ofcourse keeping the remaining letters blank). As you get progressively closer to finding the correct letters in the word, the more easier it becomes. Of course the catch being that there are a limited number of tries. You can get more information on the wikipedia page.
solution# Play the game continously until the user enters Ctrl + C import sys from random_word import RandomWords rw = RandomWords() print ("Hangman game :") print ("Type 'exit' to quit the game") def get_indices (list_word, letter ) : indices = [] # iterate over the list for index, l in enumerate(list_word) : if letter == l : indices.append(index) print (indices) return indices try : # Play the game continously until the user enters Ctrl + C while True : word = rw.get_random_word(hasDictionaryDef = True, maxLength = 10) word = list(word.upper()) guessed_word = [" "] * len(word) print (word) # maximum of 20 tries for tries in range(20): if guessed_word == word : print ("Good job !! Lets move on to the next word") break # display the word with all blanks for index, val in enumerate(guessed_word) : if index == len(guessed_word) -1 : if val == " " : print ("_") else : print (val) else : if val == " " : print ("_",end=" ") else : print (val, end=" ") # ask the user to take a guess letter = input("\nTake a guess--> ").upper() if letter.upper() == "EXIT" : sys.exit(0) # if the letter the user entered is in the random word, remake the display_word to show it. if letter in word : indices = get_indices(word, letter) for index in indices : guessed_word[index] = letter else : print ("You have exceeded 20 tries. Try another word") # exit the game when the user presses Ctrl + c except KeyboardInterrupt : sys.exit(0)
Hangman game : Type 'exit' to quit the game ['T', 'R', 'E', 'P', 'I', 'D', 'A', 'N', 'C', 'Y'] _ _ _ _ _ _ _ _ _ _
Hangman game with words in file
Modify the Hangman game above to read the words from the file words.txt (location – ./data/words.txt).
solution# Play the game continously until the user enters Ctrl + C import sys from random import uniform # read the data from file words = [] f = open("./data/words.txt","r") for line in f : words.append(line) print ("Hangman game :") print ("Type 'exit' to quit the game") def get_indices (list_word, letter ) : indices = [] # iterate over the list for index, l in enumerate(list_word) : if letter == l : indices.append(index) return indices try : # Play the game continously until the user enters Ctrl + C while True : word = words[round(uniform(1,len(words)))] #strip the last letter ("\n") word = word.rstrip() word = list(word.upper()) guessed_word = [" "] * len(word) print (word) # maximum of 20 tries for tries in range(20): if guessed_word == word : print ("Good job !! Lets move on to the next word") break # display the word with all blanks for index, val in enumerate(guessed_word) : if index == len(guessed_word) -1 : if val == " " : print ("_") else : print (val) else : if val == " " : print ("_",end=" ") else : print (val, end=" ") # ask the user to take a guess letter = input("\nTake a guess--> ").upper() if letter.upper() == "EXIT" : sys.exit(0) # if the letter the user entered is in the random word, remake the display_word to show it. if letter in word : indices = get_indices(word, letter) for index in indices : guessed_word[index] = letter else : print ("You have exceeded 20 tries. Try another word") # exit the game when the user presses Ctrl + c except KeyboardInterrupt : sys.exit(0)
Hangman game : Type 'exit' to quit the game ['T', 'R', 'E', 'P', 'I', 'D', 'A', 'N', 'C', 'Y'] _ _ _ _ _ _ _ _ _ _
Calculate sin(x)
Python’s Math module has a built-in sin ( ) function. However, it can be calculated as follows. ( approximation)

Calculate sin (x) using the above formula until 20 terms.
solutionfrom math import factorial, pow, radians degrees = radians(float(input("Enter degrees to calculate sin(x) - "))) sign = "positive" sin_x = 0 for i in range(1,20) : if i%2 == 0 : continue else : value = pow(degrees, i) / factorial(i) if sign == "positive": sin_x = sin_x + value sign ="negative" else : sin_x = sin_x - value sign = "positive" print (value) print(sin_x)
6.283185307179586 41.341702240399755 81.60524927607504 76.70585975306136 42.058693944897634 15.094642576822984 3.8199525848482803 0.7181223017785001 0.10422916220813978 0.012031585942120619 -0.001048182796038511