Posts

Showing posts from April, 2024

Using a Python Dictionary to Cache Results of a Recursive Function

Image
 I used recursive functions to calculate factorials. I created my own dictionary to cache the results of successive calculations.  #with caching, using my own dictionary cache={} def factorial(n):     if n<=1:       #this is the base case         return 1     else:         cache[n-1]=factorial(n-1)         cache[n]=cache[n-1]*n     #we don't get to this line until previous line has got to n=1         return cache[n] # ask user to input a number the factorial of which the user wishes to find num= int(input("What number? ")) print(num,'! = ',factorial(num))     # the recursive factorial function is called here print("Now I will print the dictionary's contents.") #print out the dictionary for key, value in cache.items():     print(f'key:{key}, value:{value}') Click on this image to increase its size and see the results ...

Math Puzzle Solved with Python

Image
This is a question in a elementary school math text.  The problem is stated in the first 5 comments. Whatever you input for the 2 days, the answer is always 21. # Mrs. Simpson waters her geraniums once every 3 days, and she waters her other house plants once a week. # How often does Mrs. Simpson water all the plants on the same day? # Geraniums are watered once every 3 days i.e. if watered on Monday, then watered again on Thursday. # Other plants are watered only once a week. # We have to determine how many days it takes for the watering days to be the same day. # Best way to do this is to first wait for the day to match, then count the number of days until the next #matching day. Otherwise, we get different answers for different geranium watering days.  # Ask for the first day that geraniums are watered. spelling_indicator1 = 0 while spelling_indicator1 == 0:      germ_first = input('What is the first day that the geraniums are watered (enter at least first 2 l...