0

I am trying to calculate the number of days b/w two given days.The problem that I am facing is when the first day comes late as compared to the second day. Example-If the first day is Saturday and the second one is Monday so the number of days that exists b/w them should be 3 but my code fails to do this.

a="saturday monday 1 2"
f=a.split(" ")
l=["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]
g=abs(l.index(f[0])-l.index(f[1]))+1
print(g)

2 Answers2

2

Subtract indexes for both days, and take a modulo 7. Putting this in a function, we have

def day_diff(a, b):
    l = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]

    return (l.index(b) - l.index(a))%7

print(day_diff('saturday', 'monday'))
#2
print(day_diff('monday', 'saturday'))
#5
print(day_diff('monday', 'monday'))
#0
print(day_diff('monday', 'sunday'))
#6
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
1

This will handle your problem:

a="saturday monday 1 2"
#a= "monday tuesday"
f=a.split(" ")
l=["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]
sym = (l.index(f[0])-l.index(f[1]))
if sym <= 0:
    g=abs(sym)+1
else:
    new_sym = 7 - sym
    g=abs(new_sym)+1
Rahul Agarwal
  • 4,034
  • 7
  • 27
  • 51