i'm working on making a program in python that uses arrays since it's the new chapter i'm learning. The goal of my program will ask the user for month day and day and I seem to have it almost done except that i have an issue with 2 lines in this whole code. I will write a comment in where i'm getting the errors.
def calc_zellers_congruence(get_day: int, get_year: int, get_month: int) -> str:
# Calculates the month day and year
days = [""] * 7
day_Of_Week = 0
day_of_month = 0
century = 0
year_of_the_century = get_year % 100
days[1] = "Sunday"
days[2] = "Monday"
days[3] = "Tuesday"
days[4] = "Wednessday"
days[5] = "Thursday"
days[6] = "Friday"
days[0] = "Saturday"
dayOfWeek = day_of_month + 13 * get_month + int(1) / 5 + year_of_the_century + int(year_of_the_century) / 4 + int(
century) / 4 + 5 * century % 7
name_of_day = days[day_Of_Week]
return name_of_day
def displayResults():
print("Result" + day)
def get_day():
print("Enter a Day")
get_day = int(input())
return get_day
def get_month():
print("Enter a Month")
month = int(input())
return month
def get_year():
print("Enter a Year")
get_year: int(input())
return year
# Main
# This program will calculate birthdays using arrays and zellers congruence
# References...Programming Fundamentals WiKi, J Robinson, GeeksForGeek.com
year = get_year()
month = get_month()
day = get_day()
calc_Zeller_Congruence: calc_zellers_congruence(get_year, get_month, get_day)
displayResults(calc_zellers_congruence)
I've tried renaming them but have gotten more errors after switching them from uppercase to lowercase and also adding snake cases.
Related
I am trying to calculate the difference between the current date and a given (partially known) date. For example: Valid date formats (YYYY-MM-DD) are listed below.
YYYY-MM-DD
YYYY-MM-??
YYYY-??-??
????-??-??
Examples, for the current day (2021-07-04), the results would then be
2021-12-02 -> 0 years, 5 months, however many days.
2022-06-?? -> 1 year, however many months
2077-??-?? -> ~56 Years
????-??-?? -> Unknown
So basically, when there is a ??, that part is ignore and we only check the next higher part of the date, e.g. if the day is marked with ?? we only look at year and month etc.
Here is what I've thrown together so far:
#staticmethod
def calculate_time_left(release_date):
# Only year is known:
if re.match("([0-9]{4})-\?\?-\?\?", release_date):
release_year = int(re.search("([0-9]{4})-\?\?-\?\?", release_date).group(1))
current_year = int(datetime.datetime.now().year)
if release_year == current_year:
return "This year."
else:
return "~{} year(s).".format(release_year - current_year)
elif re.match("([0-9]{4})-([0-9]{2})-\?\?", release_date):
release_year = int(re.search("([0-9]{4})-([0-9]{2})-\?\?", release_date).group(1))
current_year = int(datetime.datetime.now().year)
release_month = int(re.search("([0-9]{4})-([0-9]{2})-\?\?", release_date).group(2))
current_month = int(datetime.datetime.now().month)
if release_year == current_year:
if release_month == current_month:
return "This month"
else:
return "~{} months".format(release_month - current_month)
else:
return "{} year(s) and {} months.".format(release_year - current_year, release_month - current_month)
elif re.match("([0-9]{4})-([0-9]{2})-([0-9]{2})", release_date):
release_year = int(re.search("([0-9]{4})-([0-9]{2})-([0-9]{2})", release_date).group(1))
current_year = int(datetime.datetime.now().year)
release_month = int(re.search("([0-9]{4})-([0-9]{2})-([0-9]{2})", release_date).group(2))
current_month = int(datetime.datetime.now().month)
release_day = int(re.search("([0-9]{4})-([0-9]{2})-([0-9]{2})", release_date).group(3))
current_day = int(datetime.datetime.now().day)
if release_year == current_year:
if release_month == current_month:
if release_day == current_day:
return "Today."
else:
return "{} days.".format(release_day - current_day)
else:
if release_day == current_day:
"~{} months.".format(release_month - current_month)
else:
return "~{} months and {} days.".format(release_month - current_month, release_day - current_day)
else:
if release_month == current_month:
if release_day == current_day:
return "{} year(s).".format(release_year - current_year)
else:
if release_day == current_day:
return "{} year(s) and {} months.".format(release_year - current_year, release_month - current_month)
else:
return "{} year(s), {} months and {} days.".format(release_year - current_year, release_month - current_month, release_day - current_day)
return "Release date unknown."
I am having a couple of problems here:
I am getting negative values for the differences of months and days. For example 2022-01-02 would return 1 year(s), -6 months and -2 days.
I feel like I don't need to do all this regex matching for every case. There is probably a better way to do this.
How do I solve this properly? I feel like my approach is pretty poor and error prone.
For the negative values, you can just use absolute value function to remove the negative. i am still looking at your code trying to figure out what you are trying to accomplish. Is this just for practice ? Also, since you are not using the script as an actual date for any real purpose, just treat the each part of the date (yyyy) (mm) (dd) , as a regular integer. No, I don't think you need regex just to figure this out but its good that you know a bit of regex. Treat the numbers as integers and just format them according to how you want to display the output. I am still learning python myself, just my two cents.
I'm not sure what your overall algo should return, but here is a way to evaluate the parts of the dates:
for date_string in ['2021-12-02', '2022-06-??', '2077-??-??', '????-??-??']:
year, month, day = date_string.split('-')
year_delta = month_delta = day_delta = 'unknown'
if year.count('?') == 0: # if there are no ? in the year string
year_delta = int(year) - datetime.now().year
if month.count('?') == 0:
month_delta = int(month) - datetime.now().month
if day.count('?') == 0:
day_delta = int(day) - datetime.now().day
I have an assignment in my computer science class and need help fixing a function but I have no clue what's wrong! The function is called 'days_left'. This function takes in three variables, Day, Month, and Year. It is supposed to output how many total days are left in that year. I have tried my best but cannot figure it out! Any help will be greatly appreciated. Here's the script:
def leap_year(year):
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
return True
else:
return False
else:
return True
else:
return False
def number_of_days(month, year):
days31 = [1, 3, 5, 7, 8, 10, 12]
days30 = [4, 6, 9, 11]
if month in days31:
return 31
elif month in days30:
return 30
else:
if not leap_year(year):
return 28
else:
return 29
def days_left(month, day, year):
days = 0
for i in range(1, month):
days += number_of_days(i, year)
days += day
for x in range(year):
if leap_year(year):
return 366 - days
else:
return 365 - days
if __name__ == '__main__':
print("Please enter a date: \n")
d = int(input("Day: "))
m = int(input("Month: "))
y = int(input("Year: "))
print("\nMenu:")
print("1) Calculate the number of days in the given month.")
print("2) Calculate the number of days left in the given year.")
selection = int(input())
if selection == 1:
print(number_of_days(m, y))
elif selection == 2:
print(days_left(d, m, y))
else:
print('')
def days_left(day, month, year):
It should be 'day, month' instead 'month, day' since you are calling function with days_left(d, m, y)
This is my first question here so please forgive and educate on any formatting errors. I am new to Python and going through automate the boring stuff. Decided to expand the date detection project by using the clipboard and formatting some things also. The problem I have is in any operation taken on the year part of the REGEX.
I have commented out my last attempt to validate the year and gave up and changed the REGEX to only find dates from 1000 to 2999 and skipped code validation of the dates.
I now need to validate leap years but I'm back to having to work with the year variable, but once again no operation has any effect.
Basically the problem is I can extract the year value and display it but I cannot modify it or do checks against it.
#! python3
#! detect dates in a block of text
import pyperclip
import re
#!import numpy as np
text = str(pyperclip.paste())
def datedetection(text):
dateRegex = re.compile(
r"""(
(\d|\d\d) #! match day
(/{1}) #! match /
(\d|\d\d) #! match month
(/{1}) #! match /
([1|2][0-9][0-9][0-9]) #! match year
)""",
re.VERBOSE,
)
matches = []
for groups in dateRegex.findall(text):
day = str(groups[1])
slash1 = str(groups[2])
month = str(groups[3])
slash2 = str(groups[4])
year = str(groups[5])
month_range_30 = ["04", "06", "09", "11"]
month_range_31 = ["01", "03", "05", "07", "08", "10", "12"]
month_range_Feb = ["02"]
#!year_range = np.arange(1000, 3000, 1).tolist()
if len(day) == 1:
day = "0" + day
else:
day = day
if len(month) == 1:
month = "0" + month
else:
month = month
if month in month_range_31:
if int(day) > 31:
day = "Too many days in a month with only 31 days."
slash1 = month = slash2 = year = ""
elif month in month_range_30:
if int(day) > 30:
day = "Too many days in a month with only 30 days."
slash1 = month = slash2 = year = ""
elif month in month_range_Feb:
if int(day) > 29:
day = "Too many days in February."
slash1 = month = slash2 = year = ""
elif int(month) > 12:
day = "Found an invalid month."
slash1 = month = slash2 = year = ""
elif month in month_range_Feb:
if (
int(day) == 29
and (int(year) % 4 == 0)
and (int(year) % 400 == 0)
and (int(year) % 100 == 0)
):
day = day
elif month in month_range_Feb:
if (
int(day) == 29
and (int(year) % 4 == 0)
and (int(year) % 100 != 0)
):
day = "Found an invalid leap year."
slash1 = month = slash2 = year = ""
#!elif year not in year_range:
#!day = "Year is out of range."
#!slash1 = month = slash2 = year = ""
dates = "".join([day, slash1, month, slash2, year])
matches.append(dates)
if len(matches) > 0:
pyperclip.copy("\n".join(matches))
print("Copied to clipboard:")
print("\n".join(matches))
else:
print("No dates found.")
datedetection(text)
In my approach to this project, I considered validating the days, months, and year ranges as part of the regular expression. I then defined functions to check for the leap year, and validate the number of days according to the months.
I found that way simpler and easier to understand and follow. As below:
dateRegex = re.compile(r'([0-3][0-9])/([0-1][0-9])/([1-2][0-9]{3})')
def is_leap_year(year):
year = int(year)
if year % 4 == 0:
if year % 100 == 0:
return year % 400 == 0
else:
return True
else:
return False
def is_valid_date(day, month, year):
if month == '02':
if is_leap_year(year):
return int(day) <= 29
else:
return int(day) <= 28
elif month in ['04', '06', '09', '11']:
return int(day) <= 30
else:
return int(day) <= 31
You can find the rest of my code below.
https://gist.github.com/alialbusaidi/f56e4c9342f622434f8bff0549f94884
The problem was the operations before the year operations. The day and month operations were overwriting the year values. Not entirely sure how or why at this point, but moving the year code above the day and month code has started to fix the issue.
I am trying to program a calendar that checks how many days from now/ ago (past and present) from raw_input. I need a loop that counts the days through the current year and adds it to a variable called: Total_days and this loop has to go through each year until it hits the current date that the code ran on. The end result is that the output gives you the date you entered in a complete sentence: eg. "10/08/1700 was ___ days ago" Basically my teacher explained that the past days has to add up until it hits that certain date using a loop(loops are required. This is an assignment, i cant use any other functions like delta, but loops and datetime stuff is good!) and then for the future it has to say how many days from now until that futuristic date happens using loops. I am very stumped and i need your guys' help.
Heres what i got so far:
import datetime
input_date = raw_input("Enter in full format (mm/dd/yyyy):")
year = input_date[6:10]
yeara = int(year)
montha = int(input_date[1:2])
daya = int(input_date[4:5])
from datetime import datetime
from datetime import date
now = datetime.now()
year = now.year
month = now.month
day = now.day
def isleapYear(year):
if year % 4 == 0:
check = True
if year % 100 == 0:
check = False
if year % 400 == 0:
check = True
total_days = 0
n = 12
moNum = [0,31,28,31,30,31,30,31,31,30,31,30,31]
while n > montha:
if yeara > year:
if year == isleapYear(year):
total_days += 366
elif year != isleapYear(year):
total_days += 365
if montha == month:
break
total_days += int(moNum[n])
if n == 02:
if isleapYear(year) == True:
total_days += 1
n -= 1
ny = 365
h = total_days
if yeara > year:
if year == isleapYear(year):
total_days += 366
elif year != isleapYear(year):
total_days += 365
if yeara>year:
time = "future"
if yeara<year:
time = "past"
if yeara==year:
if montha>month:
time = "future"
if montha<month:
time = past
if montha == month:
if daya>day:
time = "future"
if daya<day:
time = "past"
if daya==day:
time = "present"
print str(h.days) + " days in the " + str(time)
Thanks for helping out! i appreciate your help :)
Must you use a loop? Else, you can build from the following:
refdatestr = "2010/08/23"
refdate = datetime.strptime(refdatestr, "%Y/%m/%d")
now = datetime.now()
difference_days = (now-refdate).days
difference_days is a datetime.timedelta object. If refdate (or refdatestr) was in the future, this would be negative.
Here is an updated code, with everything fixed:
import datetime
input_date = raw_input("Enter in full format (mm/dd/yyyy):")
year = input_date[6:10]
yeara = int(year)
montha = int(input_date[1:2])
daya = int(input_date[4:5])
from datetime import datetime
from datetime import date
now = datetime.now()
year = now.year
month = now.month
day = now.day
def isleapYear(year):
if year % 4 == 0:
check = True
if year % 100 == 0:
check = False
if year % 400 == 0:
check = True
end_date = input_date
start_date = now
delta = date(year,month,day)
delta2 = date(yeara,montha,daya)
h = delta-delta2
if yeara>year:
time = "future"
if yeara<year:
time = "past"
if yeara==year:
if montha>month:
time = "future"
if montha<month:
time = past
if montha == month:
if daya>day:
time = "future"
if daya<day:
time = "past"
if daya==day:
time = "present"
print str(h.days) + " in the " + str(time)
The most important thing that you forgot is that there are functions in datetime that will automatically find the number of days till the input...
Hope this helps!!!
def dateCalculationNorm(year):
a = year%19
b = year%4
c = year%7
d = (19*a + 24)%30
e = (2*b + 4*c + 6*d + 5)%7
dateNumber = 22 + d + e
return dateNumber
def dateCalculationSpecial(year):
a = year%19
b = year%4
c = year%7
d = (19*a + 24)%30
e = (2*b + 4*c + 6*d + 5)%7
dateNumber = 15 + d + e
return dateNumber
def dateOutput(year, date):
print("The date of Easter in the year {0} is {1}.".format(year, date))
def main():
print("Easter Date Calculator")
print()
year = eval(input("Enter the year: "))
if year >= 1900 and year <= 2099:
dateCalculationNorm(year)
if dateNumber > 31:
date = "April " + str(dateNumber - 31)
dateOutput(year, date)
else:
date = "March " + str(dateNumber)
dateOutput(year, date)
elif year == 1954 or year == 1981 or year == 2049 or year == 2076:
dateCalculationSpecial(year)
if dateNumber > 31:
date = "April " + str(dateNumber - 31)
dateOutput(year, date)
else:
date = "March " + str(dateNumber)
dateOutput(year, date)
else:
print("Sorry, but that year is not in the range of this program.")
if __name__ == '__main__':
main()
I am having trouble getting main() to accept dateNumber in the line following
(if year >= 1900 and year <=2099) Python is saying that dateNumber is not defined. I tried making dateNumber global at the beginning of the program and that worked (albeit with a warning from Python), but I know that's the sloppy way to get this program working.
Any help is very much appreciated.
You need to instantiate dateNumber.
if year >= 1900 and year <= 2099:
dateNumber = dateCalculationNorm(year) # Instantiate here.
if dateNumber > 31:
date = "April " + str(dateNumber - 31)
dateOutput(year, date)
else:
date = "March " + str(dateNumber)
dateOutput(year, date)
As it stands, there's nothing like that inside your main() function. There's no need to set it to a global either.