Reflection

This was an interesting lesson. It gave me new insights on useful skills for coding. Using libraries will allow coding to be much easier, and use work that has already been developed. Documentation makes it easy for someone to read my code, and many programs have a documentation which outlines usage for the users. The random library is used very frequently in Python programming. Randomization can be very useful in programs. A lot of programs which we see use randomization, such as games or websites.

Notes

  • Software libraries contain procedures used in creating novel programs
  • Libraries and prewritten code can make writing algorithms much easier
  • Libraries simplify complex programs
  • APIs(application program interfaces) specify how procedures in libraries should behave and be utilized
  • Reading documentation makes it much easier to understand how to use libraries/APIs
  • Useful random functions include:
    • random.randint(a, b): generates a random number. The values of a and b are required, as they are the start and stop values, placing an inclusive limit on the number to be generated. C is the step, which is optional, and is the interval at which the random numbers are generated at
    • random.randrange(a, b, c): generates a random number. The values of a and b are required, as they are the start and stop values, placing an inclusive limit on the number to be generated. C is the step, which describes what kind of multiple can be generated. The potential value starts at a, or is a a + a multiple of c, and is less than b.
    • random.shuffle: shuffles a list randomly to scramble contents

Vocab

  • Documentation: Text that explains the what, how, or why of your code.
  • Libraries: A collection of prewritten code or procedures that coders can use to maximize their efficiency
  • Application Programming Interface: A type of software through several computers are able to communicate information amongst eachother

Multiple Choice Problems

    1. B. A random integer from a to b inclusive
      • The random(a, b) function is inclusive, and generates a number. This means that the random integer will be from a to b and inclusive.
    1. A. x = start, y = stop, z = step
      • X and Y describe the range in random(x, y, z). These are both required. Z is optional, and is the step, and shows the intervals for random numbers.
    1. A. random.item
      • random.item does not exist. random.random generates a float between 0 and 1. random.shuffle randomly shuffles a list. random.randint generates a random integer.

Short Answer Questions

  1. Using libraries allows users to access and reuse pre-written code. This allows algorithms to be made more efficient. Additionally, there are many libraries which are created for multiple different purposes, which makes it easier for programmers to create more complex algorithms.
  2. First, the code segment imports the random library for use. Then, the program takes in names from user input, and puts them into a list(names). Then, the variable num_items finds the length of the list of names. The random_choice variable generates a random number which will be an index of the list. random_choice makes use of the random.randint function and generates a value from 0 to the maximum index(length of list minus 1). Then the program finds the person who is associated with the randomly generated value. Finally, the program prints that individual's name.
import random 

# takes user input, puts it into a list of names
names_string = input("Give me everybody's names, seperated by a comma.")
names = names_string.split(",")

num_items = len(names)

# uses random to choose a random number
random_choice = random.randint(0, num_items - 1)

# associates random number with a name
person_who_will_pay = names[random_choice]

# prints name
print(f"{person_who_will_pay} is going to buy the meal today!")
 Dwayne Johnson is going to buy the meal today!

Coding Challenge

Question 1

import random

names_list = ["McCorkle", "Patrick", "Josh", "Justin", "Kyler", "Jared", "Derek", "Jalen", "Daniel", "Taylor", "Dak", "Tom", "Andy", "Mike", "Davis"]
random_list = []

def addPeople(list, new_list):
    count = 1
    while count <= 5:
        number = random.randint(0, len(list) - 1)
        new_list.append(list[number])
        count += 1
    return new_list

print(addPeople(names_list, random_list))
['Josh', 'Jared', 'McCorkle', 'Jalen', 'Dak']

Documentation

This program generates 5 random names from a list. A list of names is predefined, as well as another empty list for the names to be put into. The function addPeople is defined for the sequence of code. It establishes a counter variable, which allows for 5 names to be appended to using a while loop, as the program runs while the counter variable is under a certain value. A random number is generated using the random.randint function, which generates a random integer from 0 to 1 less than the length of the list. This makes sure that when it calls the index to append into the new list, the index values fall in the range of the list of full names. Finally, the program returns the new list.

Question 2

import random
score1 = 0
score2 = 0

def DiceGame():
    score1 = random.randint(1, 6) + random.randint(1, 6)
    score2 = random.randint(1, 6) + random.randint(1, 6)
    if score1 > score2:
        print("Player 1 won with a score of " + str(score1) + " points!")
    if score1 < score2:
        print("Player 2 won with a score of " + str(score2) + " points!")
    if score1 == score2:
        print("Both players tied with " + str(score1) + " points!")

DiceGame()
DiceGame()
Player 1 won with a score of 8 points!
Both players tied with 9 points!

Documentation

The function must import the random library in order to replicate rolling a pair of dice. 2 variables are defined at first. Then, a function is created to represent the dice game. To give each player a score, the random.randint function is called twice, adding both random numbers to each other and storing that value. The random.randint function runs from 1 to 6, which represents a dice rolling a number from 1 to 6 equally. This is repeated for both players. Then, the scores are compared. If both scores are equal, a message is printed stating there is a tie. If one player has more points than the other, a statement saying that player with more points won is printed.

Extra

Trying to randomly generate a maze

import random

# defining constraints
width = 5
height = 5
obstacles = 12

# creates the maze
maze = [[0 for i in range(width)] for j in range(height)]

# for loop to generate obstacles
for i in range(obstacles):
    x = random.randint(0, width - 1)
    y = random.randint(0, height - 1)
    maze[x][y] = 'x' # represents obstacles

# function to create a start and end position
def startEnd():
    a = random.randint(0, width - 1)
    b = random.randint(0, height - 1)
    maze[a][b] = 'S' # represents the start position
    c = random.randint(0, width - 1)
    d = random.randint(0, height - 1)
    maze[c][d] = 'E' # represents the end position

startEnd()

# function to print the maze
for row in maze:
    print(' '.join(str(cell) for cell in row))
0 x x 0 E
0 x 0 x 0
0 0 0 x 0
0 0 0 x x
x S 0 0 0