Typeerror: 'int' Object Is Not Subscriptable In Equation
Solution 1:
In this line:
dow = (date+ ((13* m-1)/5) +year[2:] + (year[2:]/4) + (year[:2]/4) -2*year[:2]) %7)
You are using year
(an integer) and trying to return a slice from it. As the error indicates, int
objects do not allow you to do this. In order to accomplish what you want, you would need to cast year
as a string.
However an easier solution may be to use the built-in features of the datetime
module to calculate the day of the week:
In [1]: import datetime
In [2]: my_date = datetime.date(2012, 11, 26)
In [3]: my_date.weekday()
Out[3]: 0
This uses Monday as the starting date (0). To keep with your current code, you can use isoweekday()
, where Monday = 1:
In [11]: import datetime
In [12]: my_date = datetime.date(2012, 11, 26)
In [13]: my_date.isoweekday()
Out[13]: 1
You can then use @JonClement's slick snippet above to return the string of the day:
In [14]: '{0:%A}'.format(my_date)
Out[14]: 'Monday'
Solution 2:
You must cast your int
to a string
first, with str()
in order to slice it.
Solution 3:
Don't cast your int to a string; use arithmetic:
century = year / 100lasttwo = year % 100dow = (date + ((13 * m-1)/5) + lasttwo + (lasttwo/4) + (century/4) - 2 * century) % 7)
And because I'm physically incapable of resisting such challenges, I tried to make the rest of the code a little more Pythonic:
#!/usr/bin/python"""Calculate the day of the week of dates"""defday_of_week(month, day, year):
"""Return the name of the weekday of the given date
>>> day_of_week(1, 1, 1970)
'Friday'
>>> day_of_week(11, 26, 2012)
'Monday'
"""
moff = (month + 9) % 12 + 1# Calculate the day of the week
century = year / 100
lasttwo = year % 100
dow = (day + (13 * moff - 1) / 5 + lasttwo + lasttwo / 4 + century / 4
- 2 * century) % 7# Formatting!return ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday")[dow]
defmain():
"""Test the program, then run it interactively"""import doctest
testresult = doctest.testmod()
if testresult.failed:
import sys
sys.exit(1)
try:
month = int(raw_input("What month were you born in (1-12)? "))
ifnot1 <= month <= 12:
raise Exception("Month must be between 1 and 12!")
day = int(raw_input("On what date were you born on? "))
year = int(raw_input("What year were you born in? "))
print("\nYou were born on a %s!" % day_of_week(month, day, year))
except ValueError:
print("You need to enter a number!")
if __name__ == '__main__':
main()
Notice that the actual logic is identical to your version. It just uses code that's a bit simpler. I presume that your end goal is more about learning Python than it is actually performing this calculation. If I'm wrong, scratch all of the above and use the datetime
module which is far simpler still.
Post a Comment for "Typeerror: 'int' Object Is Not Subscriptable In Equation"