The Crying Baby

Scenario

A baby loves candy!!

She has lots of candy to eat. There are some "red" ones, some "green" ones and some "blue" ones.

Her favourite ones are the "red" ones.

She knows how to count and if there are less than 5 "red" candies on the table, she will start to cry!

Develop a computer program to simulate this scenario.

A computer game designer has created an algorithm to solve the puzzle. Here it is:

  1. populate an array with strings ("red", "green", "blue") to simulate a candy bag.
  2. set count to 0
  3. start a loop
  4. if the current candy in the bag is the same as "red", increment the count
  5. repeat this for every candy in the bag
  6. end loop
  7. if the count is less than 5, display a message which describes crying
  8. otherwise display a message which describes celebrating

A coder has been messing with some ideas to code the solution but the lines are in the incorrect sequence. Reorder the code so that it matches the algorithm.

Python alert!: you will need to imagine the indentation!

  • candyBag = ["red", "green", "blue", "red", "blue", "green", "green", "red", "blue", "green"]
  • if candyBag[i] == "red":
  • print("Waaaaaaaaah!")
  • print("Wheee heeeeeee!")
  • else:
  • for i in range(len(candyBag)):
  • count = 0
  • count = count + 1
  • if count < 5:

Task 1 - development

Compare your sequence with a classmate. Do you agree with each other? After you have decided on the correct sequence, type your code into your IDE and run it. Fix any syntax errors that appear.

Task 2 - testing

Just because your code runs and does not have any syntax errors, that does not mean it works correctly.

You should carefully choose test data and check that your code works perfectly with different sets of data.

Task 3 - adaptation

Delete the candyBag array and replace it with this code:

import random

#store the color options in an array

colors = ["red", "green", "blue"]

#create an empty candy bag

candyBag = []

#fill the candy bag with 100 random candies

for i in range(100):

#generate a random number which is an index of the colors array (0, 1 or 2)

randnum = random.randint(0,2)

#get a random color from the colors array!

color = colors[randnum]

#append the color into the candy bag

candyBag.append(color)

print(candyBag)

Run your new program and see what happens. Can you see how the above code works?

Task 4 - adaptation II

Do you have any ideas for making this program more fun, interesting, surprising?

Testing

Make sure you are thoughtful when testing your solution.

If your code has a validation check, test your code with acceptable/valid data and unacceptable/invalid data.