I have a question about an exercise from my school, hope it is okey to ask you about it.
My task is to write a program that prints the days leading up to a sum of 7 and prints the probability that this would occur in 2021 by one percent. For example: the sum of 01/01/21 is 0 + 1 + 0 + 1 + 2 + 1 = 5
So, what days in 2021 have the sum 7?
And how likely is the date to have a total of 7, in percent?
I am thankful if you can help me with this or if you have an idea how I can begin. I guess I will need to use lists and loops?
Alright, so I wrote the script. Iām sure there are better ways of doing this, but I wanted something that is easy to understand and I just spent about 5 mins on the problem. Here is the code:
months_dict = {'01': '31', # create a dictionary with the month number and amount of days in string format
'02': '28',
'03': '31',
'04': '30',
'05': '31',
'06': '30',
'07': '31',
'08': '31',
'09': '30',
'10': '31',
'11': '30',
'12': '31'
}
count = 0 # create a variable for the amount of times the sum totals 7
for month in months_dict: # loop over every month
for day in range(1, int(months_dict[month]) + 1): # loop over every day for each month
sum_month = list(month) # create a variable that splits the month into 2 (example: 11 becomes [1, 1])
sum_day = list(str(day)) # create a variable that splits the day into 2
if len(sum_day) == 1: # add a 0 in front 1-9 (1 => 01) because we are using the day variable from the loop
sum_day.insert(0, '0')
if int(sum_month[0]) + int(sum_month[1]) + int(sum_day[0]) + int(sum_day[1]) + 2 + 1 == 7: # convert to int and sum
print(f'{day}/{month}/21') # print the day if it adds up to 7
count += 1 # increment count by 1
percent = round((count / 365) * 100, 2) # calculate percentage
print(f'There is a {percent}% likelihood of days totaling the sum of 7') # print percentage