I am learning python using a book called How to think like a computer scientist. There they gave an exercise:
Write a function that helps answer questions like “‘Today is Wednesday.
I leave on holiday in 19 days time. What day will that be?”’
So the function must take a day name and a delta argument — the number of days
to add — and should return the resulting day name:
test(day_add("Monday", 4) == "Friday")
test(day_add("Tuesday", 0) == "Tuesday")
test(day_add("Tuesday", 14) == "Tuesday")
test(day_add("Sunday", 100) == "Tuesday")
Hint: use the first two functions written above to help you write this one
Can your day_add function already work with negative deltas? For example, -1 would be yesterday, or -7 would be a week ago:
test(day_add("Sunday", -1) == "Saturday")
test(day_add("Sunday", -7) == "Sunday")
test(day_add("Tuesday", -100) == "Sunday")
I have written this program
import sys
def test(did_pass):
'''prints result of test at last'''
linenum=sys._getframe(1).f_lineno #gets call line
if did_pass:
msg='Test at line {0} PASS'.format(linenum)
else:
msg=('Test at line {0} FAIL.'.format(linenum))
print(msg)
def day_name(x):
'''converts day number to day'''
if x==0:
return 'Sunday'
elif x==1:
return 'Monday'
elif x==2:
return 'Tuesday'
elif x==3:
return 'Wednesday'
elif x==4:
return 'Thursday'
elif x==5:
return 'Friday'
elif x==6:
return 'Saturday'
else:
return
def day_num(y):
'''converts day to day number'''
if y=='Sunday':
return 0
elif y=='Monday':
return 1
elif y=='Tuesday':
return 2
elif y=='Wednesday':
return 3
elif y=='Thursday':
return 4
elif y=='Friday':
return 5
elif y=='Saturday':
return 6
else:
return
def day_add(today, stay):
'''input day name and remaining days to print day name'''
result=(stay)%7
answer=(result)+(day_num(today))
return day_name(answer)
def test_suite():
test(day_add("Sunday", -1) == "Saturday")
test(day_add("Sunday", -7) == "Sunday")
test(day_add("Tuesday", -100) == "Sunday")
test_suite()
so the first function is to test my program for bugs. The problem is first two tests are clear but last test fails even if it has the same negative value as the first two. I want to know what is the mistake which makes the first two tests pass but later fail. Im beginner so kindly use some easy statements.
Your calculations are wrong. Following How to debug small programs Change your code to
def day_add(today, stay):
'''input day name and remaining days to print day name'''
result = stay % 7
answer = result + day_num(today)
print(result, day_num(today), day_name(answer)) # DEBUG your code
return day_name(answer)
Output:
6 0 Saturday
Test at line 34 PASS
0 0 Sunday
Test at line 35 PASS
5 2 None # analyze this and fix it.
Test at line 36 FAIL.