I was trying to make a simple program that finds the day difference between 2 dates that are inputted.
This is the code:
#program to find the day difference between one date and another
import calendar
date1Y = int(input("input year of date 1")) #putting the input from user to an list in order
date1M = int(input("input month of date 1")) #I don't know how to do this efficiently
date1D = int(input("input day of date 1"))
date2Y = int(input("input year of date 2"))
date2M = int(input("input month of date 2"))
date2D = int(input("input day of date 2"))
list_date1 = [date1Y, date1M, date1D] #lists of the first and second date in order Y/M/D
list_date2 = [date2Y, date2M, date2D]
days = 0
if list_date1(0) < list_date2(0) or (list_date1(0) == list_date2(0) and list_date1(1) < list_date2(1)):
while (list_date1(0) != list_date2(0) and list_date1(1) != list_date2(1)):
while (list_date1(1) <= 12):
a = calendar.monthrange(list_date1(0), list_date1(1))
days_month = a[1]
days += a[1]
list_date1(1) += 1
else :
list_date1(0) += 1
list_date1(1) = 0
elif list_date2(0) < list_date1(0) or (list_date1(0) == list_date2(0) and list_date2(1) < list_date1(1)):
while (list_date1(0) != list_date2(0) and list_date1(1) != list_date2(1)):
while (list_date2(1) <= 12):
a = calendar.monthrange(list_date2(0), list_date2(1))
days_month = a[1]
days += a[1]
list_date2(1) += 1
else :
list_date2(0) += 1
list_date2(1) = 0
if (date1D > date2D): #adding the day differences of the 2 dates
days = days + (date1D-date2D)
else :
days = days + (date2D-date1D)
print("the number of days difference =", str(days))
Since both list_date1 and list_date2 are lists, accessing an element from it would use square brackets instead of regular ones. Try changing all of your list_date#(#) to list_date#[#]
For example, with a list x = [1, 2, 3]
printing x[1] would print 2, because list indexes start at 0.
Related
The goal of the program is to:
validate inputs formats, and the date range should not be more than 2 months
No input/invalid input -> return the first or second half of the current month based on the day of the month
For the first half is from day 1 to day 15 for the second half is from day 16 till the end of the month
The hardcode, which will be the first code snippet, works as expected with the correct output, however the date validation in the second code snippet does not jump to the method indicated in the except block, which is causing me problems and not displaying correct output.
import os, sys
import datetime as dt
if __name__ == '__main__':
validate_range('2003/12/23', '2003/12/22')
validate_range('2003/10/23', '2003/11/22')
validate_range('2003/12/23', '2003/10/22')
validate_range('2003/7/23', '2003/10/22')
Code snippet with correct output (does not check if dates are correct format):
def validate_range(first_date, second_date):
start_date = dt.datetime.strptime(first_date, '%Y/%m/%d') # Get first date
end_date = dt.datetime.strptime(second_date, '%Y/%m/%d') # Get second date
num_months = (end_date.year - start_date.year) * 12 + (
end_date.month - start_date.month) # Get year/month within 2 months
if num_months >= 0 and num_months <= 2:
print("In Range")
else:
current_day = dt.datetime.today().day
if current_day >= 1 and current_day <= 15:
print("First half")
if current_day >= 16 and current_day <= 32:
print("Second half")
Correct Output:
In Range
In Range
First half
First half
Code snippet that does not display correct output (with date validation):
def read_args(first_date, second_date):
try:
start_date = dt.datetime.strptime(first_date, '%Y/%m/%d') # Get first date
end_date = dt.datetime.strptime(second_date, '%Y/%m/%d') # Get second date
v_range(start_date, end_date)
except:
w_range()
def v_range(first_date, second_date):
num_months = (second_date.year - first_date.year) * 12 + (
second_date.month - first_date.month) # Get year/month within 2 months
if num_months >= 0 and num_months <= 2:
print("In Range")
def w_range():
current_day = dt.datetime.today().day
if current_day >= 1 and current_day <= 15:
print("First half")
if current_day >= 16 and current_day <= 32:
print("Second half")
Output:
In Range
In Range
Keeping with your use of try / except, might need some improvement, but this example demonstrates it is possible:
import os, sys
import datetime as dt
def read_args(first_date, second_date):
try:
start_date = dt.datetime.strptime(first_date, '%Y/%m/%d') # Get first date
end_date = dt.datetime.strptime(second_date, '%Y/%m/%d') # Get second date
result = v_range(start_date, end_date)
except:
pass
# w_range()
def v_range(first_date, second_date):
num_months = (second_date.year - first_date.year) * 12 + (
second_date.month - first_date.month) # Get year/month within 2 months
if num_months >= 0 and num_months <= 2:
print("In Range")
else:
w_range()
def w_range():
current_day = dt.datetime.today().day
if current_day >= 1 and current_day <= 15:
print("First half")
if current_day >= 16 and current_day <= 32:
print("Second half")
if __name__ == '__main__':
read_args('2003/12/23', '2003/12/22')
read_args('2003/10/23', '2003/11/22')
read_args('2003/12/23', '2003/10/22')
read_args('2003/7/23', '2003/10/22')
n = int(input("Enter n: "))
sum = 0
i = 1
while i <= n:
sum = sum +1
i = i+1
print("The sum is" , sum)
I tried the above code but didn't got my answer.
The question is to generate a series that is: 1,4,7,10,13,16,19,22 using while loop.
To generate series you need to do two things:
Put the print inside the loop to output accumulator variable's value every iteration
Add 3 to sum every iteration and not 1 since it's the difference between series members
n = int(input("Enter n: ")) # n=8 should work
sum = 1
i = 1
while i <= n:
print(str(sum)+",")
sum = sum +3
i = i+1
I see two errors:
You should add i to sum,not 1 (this assumes you are interested in the sum as implied by the code)
You should be incrementing i by 3 not by 1
If I understand you correctly, you want this:
i = 1
while i <= 22:
print(i)
i += 3
n = int(input("Enter n: "))
count = 0
i = 1
sum = 0
while count <= n-1:
print(i)
sum += i
i += 3
count += 1
print("Sum is", sum)
You are going to want to increase the count by three every time with i += 3.
def createList():
user_input = input()
i = 1
list_of_vals = []
while i < int(user_input): # The max value:
list_of_vals.append(i)
i += 3
return list_of_vals
print (createList())
I think you want something like this:
n = int(input("Enter n: "))
series_sum = 0
i = 1
series = []
add = 3
while i <= n:
series.append(i)
series_sum = series_sum + i
i = i + add
print("series: ", series)
print("The sum is" , series_sum)
This would get you a series (and sum of elements) with the last element less than n, starting from i = 1 and increment add = 3
How could you count the number of leap years and calculate their average using the following python script?
start = int(input("Enter start year: "))
end = int(input("Enter end year: "))
if start <= end:
leap_years = [str(x + start) for x in range(end-start) if x % 4 == 0 and x % 100 != 0]
leap_years[-1] += "."
print(f"Here is a list of leap years between {start} and {end}:\n{(', '.join(leap_years))}")
from statistics import mean
leap_years = [start + x for x in range(end-start) if x % 4 == 0 and x % 100 != 0]
avg_leap_year = mean(leap_years)
print(len(leap_years))
print(avg_leap_year)
Please let me know if this script could be improved to be less redundant.
Thank you!
Here is a simple solution:
from statistics import mean
leap_years = [start + x for x in range(end-start) if x % 4 == 0 and x % 100 != 0]
avg_leap_year = mean(leap_years)
Having an issue with a certain part of the code (I am new to coding and have tried looking through StackOverflow for help):
def totalRainfall (rainfall):
totalRain = 0
month = 0
while month < len(rainfall):
totalRain = rainfall[month] + totalRain
month += 1
return totalRain
TypeError: Can't convert 'int' object to str implicitly
I've tried multiple ways of changing the code to make it a string explicitly as it still giving me various issues.
I'm also having a hard time enhancing the code to sort the array in ascending order and displays the values it contains.
The full code is here:
def main ():
rainfall = rainInput ()
totalRain = totalRainfall (rainfall)
average_Rainfall = averageRainfall (totalRain)
highestMonth, highestMonthly = highestMonthNumber (rainfall)
lowestMonth, lowestMonthly = lowestMonthNumber (rainfall)
print #this is for spacing output
print ('The total rainfall for the year was: ' +str(totalRain) + ' inche(s)')
print #this is for spacing output
print ('The average rainfall for the year was: ' +str(average_Rainfall) +\
' inche(s)')
print #this is for spacing in output
print ('The highest amount of rain was', highestMonthly, 'in' , highestMonth)
print #this is for spacing in output
print ('The lowest amount of rain was', lowestMonthly, 'in' , lowestMonth)
def rainInput ():
rainfall = ['January','Febuary','March','April','May','June','July','August'\
,'September','October','November','December']
month = 0
while month < len(rainfall):
rainfall[month] = input ('Please enter the amount for month ' + str\
(month + 1) + ': ')
month += 1
return rainfall
def totalRainfall (rainfall):
totalRain = 0
month = 0
while month < len(rainfall):
totalRain = rainfall[month] + totalRain
month += 1
return totalRain
def averageRainfall (totalRain):
average_Rainfall = totalRain / 12
return average_Rainfall
def highestMonthNumber (rainfall):
month = ['January','Febuary','March','April','May','June','July','August'\
,'September','October','November','December']
highestMonthly = 0
for m, n in enumerate(rainfall):
if n > highestMonthly:
highestMonthly = n
highestMonth = m
return month[highestMonth], highestMonthly
def lowestMonthNumber (rainfall):
month = ['January','Febuary','March','April','May','June','July','August'\
,'September','October','November','December']
lowestMonthly = 0
for m, n in enumerate(rainfall):
if n < lowestMonthly:
lowestMonthly = n
lowestMonth = m
return month[lowestMonth], lowestMonthly
main()
You have stored strings in your array rainfall, you need to convert them to ints before adding.
def totalRainfall (rainfall):
totalRain = 0
month = 0
while month < len(rainfall):
totalRain = int(rainfall[month]) + totalRain
month += 1
return totalRain
If you want the total rainfall as the sum of the numbers per month, simply use sum() on the list of ints. But as your error suggests, you have a list of strings, which you explicitly have to convert.
Something along the lines of
def totalRainfall (rainfall):
return sum([int(x) for x in rainfall])
The problem with your list being strings will continue to be problematic for you, so as a quick fix, I suggest you change this line
rainfall[month] = input ('Please enter the amount for month ' + str\
(month + 1) + ': ')
to
rainfall[month] = int(input('Please enter the amount for month ' + str\
(month + 1) + ': '))
That way your list contains only numbers and all your other comparisons will work.
You should also add this initialization in your lowestMonthNumber function to avoid UnboundLocalError: local variable 'lowestMonth' referenced before assignment:
lowestMonth = 0
Notice, that by initializing lowestMonthly to 0, you will most likely never get a correct result, since it is highly unlikely that any month has less rainfall.
I am solving a problem in Codeforce and this was my previous submission
#!/usr/local/bin/python
limit = 10**18
string = raw_input()
year1, year2 = string.split()
year1 = int(year1)
year2 = int(year2)
x = 1
count = 0
a = []
while True:
k = 2**x - 1
if k > limit:
break
else:
for i in xrange(len(bin(k)[2:])):
if year1 <= k - (1 << i) <= year2 and len(bin(k - (1 << i))[2:].split('0')) == 2:
count += 1
x += 1
print count
It worked for all the given values but it gave one less count value for the range 1 to 1000000000000000000. It was hard to debug and hence I put a hacked up code before the last print like this
if year2 - year1 + 1 == limit:
count += 1
and it worked for that value but again gave one less value value for another range, 1 to 935829385028502935.
No wonder that the logic-less hack didn't work but I want to know that why it gave one less count value previously ?
You need to increase limit by another order of magnitude:
limit = 10**19
Otherwise you'd miss 864691128455135231, obtained from 1152921504606846975 - (1 << 58).
(Observe that 1152921504606846975 > 10**18.)
I tried to simplify code (it works now, Accepted):
limit = 10**19 # this change is important because otherwise you will loose 1 solution
# k > limit and exists such i that k - (1 << i) < limit
string = raw_input()
year1, year2 = string.split()
year1 = int(year1)
year2 = int(year2)
x = 1
count = 0
a = []
while True:
k = 2**x - 1
if k > limit:
break
for i in xrange(x - 1): # k has exactly x bits. So we have only x-1 chances to set zero bit
if year1 <= k - (1 << i) <= year2:
count += 1
x += 1
print count
Submission: http://codeforces.com/contest/611/submission/15230069