The Dice Man¶
Try me¶
Problem definition¶
The Dice Man is a novel where a psychiatrist ends up making all his decisions casting dice. Everytime he faces a decision, he numbers his options from 1 to 6, casts dice, and guides his choices by the result. Let´s make the dice man bot! a digital assistant for anyone who would like to follow the same decision-making strategy as the Dice Man. The bot must ask the user to define up to 6 options, select one randomly, and show it to the user.
Solution¶
In our solution, we are going to use the library random and its function random.randint(a,b) which returns a random number between a and b:
[5]:
import random
options_list = [] # We will create an empty list to store the options
n = 0 # This variable keeps track of the number of options introduced by the user
print("I am the Dice Bot, what are your options?")
for i in range(6): # Let´s allow at most 6 options
option = input("Tell me an option (press Enter to stop): ")
if option: # We check that the option is not empty (an empty string computes to false)
options_list.append(option)
print(f"{i+1}: ´{options_list[i]}")
n+=1
else:
break
while True: # Let´s cast the dice until we have a valid option
decision = random.randint(1, 6) - 1 #We get a number from 1-6 from dice, then we subtract 1 to get a valid index
if decision < n:
print("The dice found an answer, you should choose:")
print(f"{decision+1}: ´{options_list[decision]}")
break
I am the Dice Bot, what are your options?
1: ´Go out
2: ´Study Python
The dice found an answer, you should choose:
2: ´Study Python
Analysis questions¶
These questions are designed to help you better understand the code above. Try to answer them by yourself before asking for help.
User Input Management: Why does the program use a loop to get user input for options? How does it determine when to exit the loop? Explain the condition
if option:. What purpose does it serveCode Adaptability: The code allows a user to input at most 6 options. Why is this number chosen, and how does it relate to the concept of dice rolls? How easy would it be to modify the program to work with a different number-sided die, for instance, a 12-sided die? What changes would be needed?
Decision Mechanism: Describe the process by which the program simulates a dice roll to make a decision. Why is the variable
decisionassigned the valuerandom.randint(1, 6) - 1How does the program ensure that only valid options are chosen?While Loop: The code contains the line
while True:. Why is this used? and how does the program ensure it doesn’t get stuck in an infinite loop?Randomness: How does the random.randint function ensure that the decision-making process is random and unbiased? Could the program be modified to make it biased towards certain options?