3.14

Libraries and Documentation

Essential Knowledge

  • Software libraries contain procedures used in creating novel programs.
  • Existing code segments can be derived from internal or external sources:Libraries, Previously written code.- Libraries simplify complex programs.
  • APIs (application program interfaces) specify how procedures in libraries should behave and be utilized.
  • Documentation for APIs/Libraries are necessary to gain proper understanding into how to use them.

Key Vocabulary

  • Documentation- Explaining in words what a piece of code does in a simple way for others to understand
  • Libraries- a collection of precompiled, reusable files, functions, scripts, procedures, and other resources
  • Application Programming Interface- a set of definitions and protocols for building and integrating application software

Big Ideas

  • Reusing Code: To make maximize efficiency in novel code, it is best to use previously made procedures.
  • Documentation: Explaining in words what a piece of code does in a simple way for others to understand
    • Documentation for the example below: The procedure gradeAverage takes a list of integer values representing the percentages in a certain class, and returns the average of those integers.
  • Libraries and APIs: A useful example of a Library that is provided by College Board, is the APCSP Exam Reference Sheet. The sheet contains various procedures and how they should/are used.
    • Appilcation Program Interface (API) gives specific directions for how procedures that reside in these APIs can be used.
def gradeAverage(num):
    sumNums = 0
    for t in num:
        sumNums = sumNums + t

    average = sumNums / len(num)
    return average

print("The average grade is", gradeAverage([65, 70, 72, 75, 80, 73, 61, 84, 81, 83]))
The average grade is 74.4

Practice

  1. Which of the following would be MOST useful as part of a program that determines Grade Point Average?
  • A procedure isEqual, which takes two positive integers as input and returnes if their values are equal.
  • A procedure calcQuotient, which takes two positive integers as input and returns their quotient.
  • A procedure getHighGrade, which takes a list of grades as input and returns the highest value.
  • A procedure calcStatus, which takes a positve integer credits and returns a string grade classifier (senior, junior, etc.).

  • Answer: 2, in order to calculate a GPA, it is necessary to take sum of the letter grades' corresponding numbers, and divide them by the number of grades]

  1. Which of the following would be LEAST useful in a program that helps choose the best restaurant within 5 miles of your location?
  • A procedure orderReviews, which lists 10 restaurants from least to greatest based on their associated star-rating.
  • A procedure numPeople, which outputs the name of 10 restaurants with the highest visits per month.
  • A procedure foodItem, which lists all menu items marked vegetarian on a high rated restaurants menu.
  • A procedure ranRest, which randomizes a list of highest rating restaurants and outputs 1 restaurant.

  • Answer: 3, it does not help to choose the restaurant itself

3.15

Random Values

Learning Objectives:- Write expressions to generate possible values- Evaluate expressions to determine the possible results

Key Vocabulary:

  • randomization- Rolling a dice, Lottery Tickets, Game of Marbles

Practice:

  1. RANDOM(a, b) - which generates and returns a random integer from a to b, inclusive. Each result is equally likely to occur.

    • Adding two ranges to get a third range

      • Example Problem:
      • answer1 = random(0,2)
      • answer2 = random(1,5)
      • answer3 = answer1 + answer2
    • What is the possible range of results for answer?

    • Answer: [1, 2, 3, 4, 5, 6, 7]
  2. Working with Random Number Generators
    • A die contains six sides with corresponding dots 1 through 6 on individual sides. Which of the following code segments can be used to simulate the results of rolling the die 3 times and assigns the sum of the values obtained by the rolls to the variable.
      • A) sum = 3 * random(1,6)
      • B) sum = random(1,18)
      • C) sum = random(1,6) + random(1,6) + random(1,6)
    • Answer: C, because it is random each time

Using the random library

Using random.choice

import random

tvshows_list = ['Squid Game', 'Cobra Kai', 'Gilmore Girls', 'Sherlock Holmes', 'Barbie in the Dream House']

# pick a random choice from a list of strings.
random_tvshow = random.choice(tvshows_list)
print(f"You should watch {random_tvshow}!")
You should watch Cobra Kai!

Using random.shuffle

import random

num_list = [7,8,10,22]

print("List before using shuffle: ", num_list)
random.shuffle(num_list)

print("List after using shuffle method: ", num_list)
List before using shuffle:  [7, 8, 10, 22]
List after using shuffle method:  [7, 22, 8, 10]

Syntax

import random  ## The random library must be imported to use it's functions

## Either randint or randrange can be used the only difference is that you can use a step function in randrange and the max value won't be inclued

x = 0
a = 0
b = 100

while x < 10:
    print ('-----')
    x = x + 1
    
    i = random.randint(a, b)
    r = random.randrange(a, b, 10)  
    print(i, r)
-----
37 70
-----
47 70
-----
82 30
-----
48 30
-----
94 50
-----
55 90
-----
81 10
-----
54 0
-----
17 90
-----
33 40

randint:

  • write this is randint(start, stop) where start is the minimum value, stop is the maximum value. And this allows you to generate a random integer from a set range and this can help you create code for things like a coin-flip, dice roll, and anything else which needs an inclusive range.
numRolls = 10
x = 0
while x < numRolls:
    x = x + 1 
    i = random.randint(1, 6)
    print(i)
4
4
3
6
4
4
4
3
5
4

randrange:

  • like an arithmetic series
  • can be written like randrange(start, stop, step) where start is the minimum value, stop is the maximum value (like the randint function), and step is the incriment the values can be and its default value is 1. If start = 0 and step = 5 all the values that can by outputed are 0 and multiples of 5. And if start = 2 and step = 3 the output would be 2 and a multiple of 3 plus 2.

Practice

  1. A person is playing a game of darts.
  • This incomplete code segment simulates the person throwing a dart:

    • IF () { shotMade ← true DISPLAY("Score!") } ELSE { DISPLAY("Miss!") }
    • Which of these can replace MISSING CONDITION so that the has a 75% chance of making the shot? (There are TWO answers!)

      • RANDOM(1, 100) <= 75
      • RANDOM(1, 100) < 75
      • RANDOM(1, 4) < 3
      • RANDOM(1, 4) <= 3
    • Answer: 1 and 4 are both correct, 1 includes the values from 1-75 which means that it has a 75% chance to be chosen and 4 includes the values of 1, 2, and 3 which makes 3/4 which is the same as a 75% chance.

      • ratios 75/100 = 3/4 = 75%

Hacks/Homework

Reflection

Thorough notes or summary that reflects understanding of today's lesson.

Multiple Choice

  1. What does the random(a,b) function generate?

    • A. A random integer from a to be exclusive
    • B. A random integer from a to b inclusive.
    • C. A random word from variable a to variable b exclusive.
    • D. A random word from variable a to variable b inclusive.

    • Answer: B, because it includes all of those numbers in between and the endpoints

  2. What is x, y, and z in random.randrange(x, y, z)?

    • A. x = start, y = stop, z = step
    • B. x = start, y = step, z = stop
    • C. x = stop, y = start, z = step
    • D. x = step, y = start, z = stop

    • Answer: A, the order is start, stop, step

  3. Which of the following is NOT part of the random library?

    • A. random.item
    • B. random.random
    • C. random.shuffle
    • D. random.randint

    • Answer: B, there is no random.random

Short Answer Questions

  1. What is the advantage of using libraries?
  • The advantage of using libraries is that they show how code should be used and is used.
  1. Write a thorough documentation of the following code.
  • Basically, the user inputs the possible names of the people. The code then calculates the number of people entered, randomizes it in order of how it was entered and then choose a person.
import random 

names_string = input("Give me everybody's names, seperated by a comma.")
names = names_string.split(",")

num_items = len(names)

random_choice = random.randint(0, num_items - 1)

person_who_will_pay = names[random_choice]

print(f"{person_who_will_pay} is going to buy the meal today!")
 Amitha is going to buy the meal today!

Coding Challenges!

REQUIRED:Create programs in python to complete the two task</p>

  • Create a program to pick five random names from a list of at least 15 names
import random 

possible_people = input("Enter the names into a lottery, separated by a comma. This is a chance to win $10 Million!")
people = possible_people.split(",")

num_people = len(people)

random_choice - random.randint(0, num_people - 1)

lottery_winner = people[random_choice]

print(f"{lottery_winner} won the lottery of $10 Million")
 athyna won the lottery of $10 Million
  • Create a program to simulate a dice game where each player rolls two fair dice (6 sides); the player with the greater sum wins
import random 
possible_rolls = [1,2,3,4,5,6]

player_1 = input("Enter 1st player's name")
r1 = random.choice(possible_rolls)
r2 = random.choice(possible_rolls)
print(player_1, "rolled", r1, "and", r2)

player_2 = input("Enter 2nd players name")
r3 = random.choice(possible_rolls)
r4 = random.choice(possible_rolls)
print(player_2, "rolled", r3, "and", r4)

if (r1 + r2 > r3 + r4):
    print(player_1, "wins")
elif (r1 +r2 < r3 + r4):
    print(player_2, "wins")
joselyn rolled 1 and 1
lina rolled 5 and 3
lina wins