Example 4: Better deal?

Your rich uncle is giving his son $1,000,000 in cash.  Your father claims he loves you a lot, but he is only giving you pennies over a sequence of 30 days.  He will start giving you 1 penny on the first day and double the amount  every one of the next 29 days (i.e., 1 penny today, 2 pennies tomorrow, 4 pennies the next day, 8 pennies the next day, etc.).  Are you or your cousin getting the better deal?

# 02Loops example_04 BetterDeal1.py
# who gets a better deal? Fixed amount or doubling pennies?

from __future__ import print_function # use Python 3.0 printing 

pennies = 1                #start with 1 penny on day 1
sumOfPennies = 0           #set the SumOfPennies to 0
days = 30
for day in range(1,days+1):    #loop for 30 days
    sumOfPennies = sumOfPennies + pennies    #accumulate the sum of pennies
    pennies = pennies * 2  #pennies double daily

sumOfPennies = sumOfPennies / 100.0 #convert pennies to dollars

print ("The total amount you receive from your father is $" , sumOfPennies)    

if sumOfPennies > 1000000:
    print ("You are getting the better deal!")
else:
    print("Your cousin is getting the better deal!")

The output is:

The total amount you receive from your father is $ 10737418.23
You are getting the better deal!

The result of the program may be surprising to some students. It captures an important concept underlying many algorithms: if we take a number larger than one and double it repeatedly, the number grows exponentially. This means the number gets large very fast. This can be good (e.g., if it corresponds to money you get) or it can be bad (e.g., if it corresponds to the time needed to run an algorithm).

The better deal problem is discussed in the following video. The video also presents a variation of the better deal problem (see the program below 02Loops example_04 BetterDeal2.py) which modifies the program BetterDeal1 to print the day on which the sum of the pennies exceeds $1,000,000 for the first time.  Video Length: 5:08

Program 02Loops example_04 BetterDeal2.py

# 02Loops example_04 BetterDeal2.py
# who gets a better deal? Fixed amount or doubling pennies?

from __future__ import print_function # use Python 3.0 printing 

pennies = 1                #start with 1 penny on day 1
sumOfPennies = 0           #set the SumOfPennies to 0
days = 30

i = 1
while i <= days:
    sumOfPennies = sumOfPennies + pennies    #accumulate the sum of pennies
    pennies = pennies * 2  #pennies double daily
    penniesInDollars = sumOfPennies / 100.0 #convert pennies to dollars
    if penniesInDollars >= 1000000:
        print ("On day number", i, "you first beat your cousin. You get $", penniesInDollars)
        break
    i = i + 1