Iteration Exercises

CSCI 1012

In-Lab Exercises

  • File names:
    • last_digit.py
    • pizza_party.py
    • odd_string.py
  • Turn in on the submit server for credit
  • Turn in one .zip with all the .py files
    • Unlimited attempts, until 5 PM on Friday 20 Feb
    • We’ll provide solutions – pay attention!

Exercise 1

last_digit.py
def last_digit(x):
  if x % 10 == 0 or 1:
    return True
  else:
    return False
  • Argument x will be a non-negative integer
  • Function should return True if x’s last digit is 0 or 1
    • Otherwise, function should return False
  • Something doesn’t work. Fix it!

Photograph of a Pizza Pie

Image copyright: Andy’s Pizza. Fair use.

Exercise 2

pizza_party.py
def pizza_party(people):
  slices_per_pie = 8
  pies = 1
  if (pies * slices_per_pie) % people == 0:
    return True
  return False
  • Currently: returns True if one pie can be equally shared by the number of people
  • Goal: return the minimum number of pies needed so the number of people can equally share the slices
    • pizza_party(2) returns 1
    • pizza_party(6) returns 3
    • pizza_party(5) returns 5

Exercise 3

odd_string.py
def odd_string(A):
  s = "" # create an empty string
  # use a for loop to iterate over odd numbers <= A
    # concatenate them with the string and reassign
    # you must account for the last digit "differently"
  return s
  • odd_string(5) should return "1 3 5"
  • odd_string(8) should return "1 3 5 7"