Not logged in. Login

Exercise 11

Assignment 1, but easier.

Assignment 1 contained the qualifier: "There are some Python modules that can do this kind of calculation for you. You are expected to do the calculation yourself for this assignment, without help from imported modules."

How easy was the assignment without this restriction? Let's repeat it in a1.py.

Use the datetime.datetime.strptime function, to create a datetime object. Hint: "%Y/%m/%d".

Instances of datetime have a .timetuple() method. It returns a "struct_time" object, and a struct_time has a tm_yday attribute representing the day of year.

Use these facts to solve assignment 1 in a few lines of code. A leap year example:

Enter a date in the form YYYY/MM/DD: 2024/05/03
2024/05/03 is day 124 of the year 2024.

A non-leap year:

Enter a date in the form YYYY/MM/DD: 2023/05/03
2023/05/03 is day 123 of the year 2023.

If strptime is given an invalid date it will raise a ValueError. Use that to handle invalid inputs.

Enter a date in the form YYYY/MM/DD: tomorrow
Invalid date.

Greatest Common Divisor, recursively

In recursion1.py, create a recursive function gcd(m,n) that calculates the GCD (greatest common divisor) of the two arguments (which you can assume are integers).

Euclid's Algorithm for calculating the GCD relies on these facts:

gcd(a, 0) = a

gcd(a, b) = gcd(b, a%b), for b ≠ 0.

Here are some examples:

>>> print(gcd(12, 18))
6
>>> print(gcd(18, 31))
1
>>> print(gcd(87654, 0))
87654
>>> print(gcd(0, 87654))
87654
>>> print(gcd(324, 162))
162

Here, the base case will be when b==0 (return a). For the recursive case, return gcd(b, a%b).

Only Evens, recursively

A few weeks ago, you implemented a function even_only that took a list as an argument and returned a list of only the even numbers from the argument.

Add a recursive solution to this problem to recursion1.py. It should behave the same as the previous implementation but use recursion.

>>> print(even_only([]))
[]
>>> print(even_only([2, 4, 5, 9, 10, 12]))
[2, 4, 10, 12]
>>> print(even_only([1, 4, 9, 16, 25, 36, 49, 64, 81, 100]))
[4, 16, 36, 64, 100]

Submitting

Submit all of your work through CourSys.

Updated Thu July 18 2024, 10:31 by ggbaker.