ICS3U Learning To Problem Solve With Python Part 2

ICS3U Learning Goals

In this ICS3U lesson you will be learning how to

  • Break more complicated programs into more manageable pieces
  • Write pseudo code using the input-processing-output method of problem solving.
  • Add documentation to a python program
  • Evaluate the solutions to more complex problems

Problem Solving in Computer Science

Recall from the previous problem solving lesson, in ICS3U we solve a lot of problems in computer science using an algorithm.  (A series of steps that lead you to the correct answer)  The INPUT – PROCESSING – OUTPUT model of problem solving generally works pretty well in this course for solving straightforward computational problems

  • Input – Lists the data needed to be stored or entered from the user
  • Processing – The logic / math, steps needed to solve the problem
  • Output – Lists what is required to be displayed on the screen when the program is running or finished
This problem solving document is often called the  PSEUDOCODE for your program.
 
As programs start to get more complicated, you might want to consider doing this process for small parts of the program, instead of the entire program as a whole.  It can be quite challenging to plan out everything before hand in a complicated problem.  If you can test and debug small portions of code, that will be much more manageable in the long run.

ICS3U Problem To Solve

We are going to program a variation of the game of NIM between a human player and the computer player

  • The game starts with a random number of coins between 20 and 50
  • The players can pick 1, 2, or 3 coins to remove
  • Players alternate taking away coins
  • The player that removes the last coin is the loser

Video Solution

Important Information to Remember

Part 1 - Random Coins to Start the Game

Design the code that will generate the random coins that start the game and test to ensure it works correctly.

Processing: 

  • Just use the randint function to generate the random number
  • Need to import the random function library

Code: 

				
					import random

#Generate # of random coins to start
numCoins = random.randint(20,50)
print("There are", numCoins, "coins in this game")
				
			

Part 2 - Game Loop and Player Choice

Design the code so that the player should be able to continuously choose ANY number of coins (deal with limitations later) and the game will reduce the coins in the pile after each choice.  It should stop when there are no more coins left.

Processing:

Create an infinite loop

  • pChoice -> input choice of coins from player
  • Subtract pChoice from numCoins
  • if numCoins > 0
    • display remaining coins
  • else
    • game over, print “loss”, stop the game loop

Code:

				
					#Infinite Game loop
while True:

	#Player Choose the number of coins
	pChoice = int(input("Enter the number of coins to pick: "))

	#Reduce the number of coins
	numCoins = numCoins - pChoice

	#Check if the game should continue or the player loses
	if numCoins > 0:
		print("There are", numCoins, "coins left in this game")
	else:
		print("You Took the last coin, you lose")
		break
				
			

Part 3 - Check for Valid Player Inputs

Design the code so that the player can only choose 1, 2, or 3 coins.  The game can’t stop if they choose incorrectly, it needs to keep asking until a valid input is chosen.

Processing: 

Inside the infinite game loop:

Add another Infinite Loop

  • Get the user input
  • if input >3 or < 1 or > remaining coins
    • print not valid
  • else
    • it was valid choice so break the input loop

Code:

				
					#Player Choose the number of coins & Check for valid input
	while True:
		pChoice = int(input("Enter the number of coins to pick: "))

		#Check for invalid, if valid break out of choice loop
		if pChoice > 3 or pChoice < 1 or numCoins - pChoice < 0:
			print("Not Valid->Choose again")
		else:
			break
				
			

Part 4 - Add the Computer Player

Design the code so that the computer will pick an appropriate amount of coins.  It should have some limited intelligence and try to win if it has an opportunity to win.

Processing: 

if numCoins > 3 

  • computer makes a random choice of 1 or 2 or 3 coins

if numCoins == 3

  • computer chooses 2 coins (force the player to take last coin and computer will win)

if numCoins == 2 or 1

  • computer picks 1 coin (when there is 2 coins left picking one will ensure it wins.  When there is 1 coin left, it has no choice but to take last coin and lose)

After choosing the correct amount of coins:

  • Reduce the total coins
  • Check for a winning / losing state

Code:

				
					#Computer choice based on # of coins remaining
	if numCoins > 3:
		cChoice = random.randint(1,3)
	elif numCoins == 3:
		cChoice = 2
	elif numCoins == 2 or numCoins == 1:
		cChoice = 1

	print("Computer takes",cChoice,"coins")

	#Reduce the number of coins
	numCoins = numCoins - cChoice

	#Check if the game should continue or the Computer loses
	if numCoins > 0:
		print("There are", numCoins, "coins left in this game")
	else:
		print("Computer Took the last coin, you win")
		break
				
			

Interactive Learning Activity

When it comes time to evaluate if this solution is correct, you have to do things a bit differently than with questions that have a lot of math.  There is no math to verify in this program, so you need to check MANY different inputs to see if the program is behaving correctly for all of the different scenarios. 

Here is the completed code for the game. Type it into the Python Editor and run the program

				
					import random

#Generate # of random coins to start
numCoins = random.randint(20,50)
print("There are", numCoins, "coins in this game")

#Infinite Game loop
while True:

	#Player Choose the number of coins & Check for valid input
	while True:
		pChoice = int(input("Enter the number of coins to pick: "))

		#Check for invalid, if valid break out of choice loop
		if pChoice > 3 or pChoice < 1 or numCoins - pChoice < 0:
			print("Not Valid->Choose again")
		else:
			break

	#Reduce the number of coins
	numCoins = numCoins - pChoice

	#Check if the game should continue or the player loses
	if numCoins > 0:
		print("There are", numCoins, "coins left in this game")
	else:
		print("You Took the last coin, you lose")
		break

	#Computer choice based on # of coins remaining
	if numCoins > 3:
		cChoice = random.randint(1,3)
	elif numCoins == 3:
		cChoice = 2
	elif numCoins == 2 or numCoins == 1:
		cChoice = 1

	print("Computer takes",cChoice,"coins")

	#Reduce the number of coins
	numCoins = numCoins - cChoice

	#Check if the game should continue or the Computer loses
	if numCoins > 0:
		print("There are", numCoins, "coins left in this game")
	else:
		print("Computer Took the last coin, you win")
		break
				
			

I suggest you check if all the following scenarios are working correctly.

  • Player can only pick between 1 and 3
  • Player can’t pick more than the # of coins remaining
  • Player loses when he picks the last coin
  • # of coins reduces correctly
  • Computer picks the appropriate amount of coins given the situation
  • Computer loses when it picks the last coin.

ICS3U Coding Questions

Try to code the following ICS3U questions using an IDE of your choice (Spyder, IDLE, Pycharm, etc).  You will save those files on your computer for future reference. 

Make sure you are completing the Input-Processing-Output Problem Solving Process before you start your code.  Clearly evaluate the solution when finished.

Each question has:

  • A video of your teacher live coding and explaining the solution
  • The final code used in the video.

Try your best to solve the problems yourself without looking at the solutions.

Make sure you test your programs with multiple different inputs to ensure it is functioning properly.

ICS3U Practice Question

Name Your File : “ICS3UtargetSum.py”

You have two dice. An n sided dice and an m sided dice. n and m are inputted by the user. Your goal is to count and display all the possible combinations of dice rolls that will add up to a target number. That target number is entered by the user.

Here are some samples

ICS3U problem solving target sum

				
					#Required input
m = int(input("m:"))
n = int(input("n:"))
target = int(input("target Sum:"))
print("")

#counter
count = 0

#Loop through each value of the first dice
dice1 = 1
while dice1 <= m:
    
    #Loop through each value of the second dice
    dice2 = 1
    while dice2 <= n:
        
        #Total of both dice rolls
        total = dice1 + dice2
        
        #Check for target and increase count
        if total == target:
            print(dice1,"+",dice2,"=",total)
            count = count + 1
        
        #Move to the next dice2 value
        dice2 = dice2 + 1
        
    #Move to the next dice1 value
    dice1 = dice1 + 1
    
if count == 1:
    print("There is 1 way to get the sum of", target)
else:
    print("There are",count,"ways to get the sum of",target)
				
			

ICS3U Practice Question

Name Your File : “ICS3UguessingGame.py”

You are going to create a guessing game where the computer picks a random number between 1 and 100 and lets you guess the answer

  • If the guess matches the target, display “You Got It”
  • If the guess is higher than the target, display “Too High”
  • If the guess is lower than the target, display “Too Low”

Your program should also tell the user the following depending on the how far away they were from the actual answer

  • Less than 5 away -> “Boiling”
  • Between 5 and 10 away -> “Hot”
  • Between 10 and 20 away -> “Warm”
  • Between 20 and 50 away -> “Cold”
  • Larger than 50 away -> “Freezing”

				
					import random

target = random.randint(0,100)

while True:
    
    #Get User Guess
    guess = int(input("Guess a number: "))
    distance = guess - target
    
    #Check hint1
    if distance > 0:
        hint1 = "Too High"
    elif distance < 0:
        hint1 = "Too Low"
        distance = distance *-1
    else:
        break
    
    #Check hint2
    if distance > 0 and distance <=5 :
        hint2 = "Boiling"
    elif distance > 5 and distance <=10 :
        hint2 = "Hot"
    elif distance > 10 and distance <=20 :
        hint2 = "Warm"
    elif distance > 20 and distance <= 50 :
        hint2 = "Cold"
    else:
       hint2 = "Freezing"
    
    #Display results
    print(hint1,",",hint2)
        
print("You got it")
				
			

ICS3U Practice Question

Name Your File : “ICS3UsumacSequence.py”

A sumac sequence is made by beginning with two integer terms (the first larger than the second), and then producing more terms according to the following rules (starting with the third term)

  • The subsequent terms (Starting with the third) are the difference between the two previous terms
  • If a term is produced that is greater than the term before it, the sequence terminates

Here are some examples

ICS3U Sumac Sequence Output

				
					a = int(input("First: "))
b = int(input("Second: "))

#Start of the sequence
print("\nThe sequence is: ",end ="")
print(a,b, end = " ")


while True:
    
    #Find the next number in the sequence and print it
    c = a - b
    print(c, end =" ")
    
    #Check if sequence should end, if not then reset the first and second number
    if c > b:
        break
    else:
        a = b
        b = c
				
			

ICS3U Practice Question

Name Your File : “ICS3UsnakesLadders.py”

You want to simulate a “snakes and ladders” game using the board shown below. Assume its only 1 player playing. You are using 2 six sided dice. To win, you must land on 100 exactly. If your roll would put you over 100, then you don’t move. Indicate to the player if they land on a snake or a ladder and move to the appropriate spot. The player always starts on space 1

Remember that snakes move you down and ladders move you up

ICS3U snakes and ladders board

				
					import random

space = 1

print("You are on space 1")
while True:
    
    #Roll the dice
    input("Press Enter to Roll")
    dice1 = random.randint(1,6)
    dice2 = random.randint(1,6)
    print("You rolled:",dice1, dice2)
    
    #Update location and check for snakes / ladders, win
    tempSpace = space + dice1 + dice2
    if tempSpace == 9:
        space = 34
        print("Found a ladder")
    elif tempSpace == 40:
        space = 64
        print("Found a ladder")
    elif tempSpace == 67:
        space = 86
        print("Found a ladder")
    elif tempSpace == 54:
        space = 19
        print("Found a snake")
    elif tempSpace == 90:
        space = 48
        print("Found a snake")
    elif tempSpace == 99:
        space = 77
        print("Found a snake" )
    elif tempSpace > 100:
        print("Too many, can't move")
    elif tempSpace == 100:
        break
    else:
        space = tempSpace
    
    print("You are now on space", space)

#Game Over
print("Space 100...You Win")
				
			

External Resources

Return to Grade 11 Computer Science Main Page