Home > Mobile >  Return the associated day of the year with a for loop that takes the month, day as input
Return the associated day of the year with a for loop that takes the month, day as input

Time:10-26

The problem says: Write a function called day_of_the_year that takes a month and day as input and returns the associated day of the year. Let the month by a number from 1 (representing January) to 12 (representing December). For example:

day_of_the_year(1, 1) = 1
day_of_the_year(2, 1) = 32
day_of_the_year(3, 1) = 60

Continued problem: Use a loop to add up the full number of days for all months before the one you're interested in, then add in the remaining days. For example, to find the day of the year for March 5, add up the first two entries in days_per_month to get the total number of days in January and February, then add in 5 more days.

So far, I have made a list:

days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

This is my code so far:

def day_of_the_year(month,day):
    days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    for number in day_of_the_year:
        total = days_per_month[0]   days_per_month[1]   5
        return total

Is there something that I am missing?

CodePudding user response:

Yes, you are exiting your loop on the first pass every time. What you should do is define the total variable outside of the for loop and then increment it on each iteration. You also only need to iterate to the month that is specified so use the range function to loop. Then once the loop has finished you can add the days to total and return it

def day_of_the_year(month,day):
    days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    total = 0
    for number in range(month - 1):
        total  = days_per_month[number]
    total  = day
    return total

CodePudding user response:

The easiest way to solve this problem is to use sum() to find the number of days in the months that have already passed, then add the extra days. Like this:

def day_of_the_year(month, day):
    days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    return sum(days_per_month[:month-1])   day


print(day_of_the_year(1, 1))  # => 1
print(day_of_the_year(2, 1))  # => 32)
print(day_of_the_year(3, 1))  # => 60)

It is more readable and fairly understandable.

  • Related