Unit 3.14-3.15 Hacks
Reflection
After todays lesson on sections 14 through 15, I have a better understanding of libraries and documentations and how they make coding a more efficient process. I learned that libraries are efficient because they are pre-written and can be referenced throughout the code. Documentations are efficient as they explain how the code works. I also learned more about API's and that they facilitate communication amongst multiple computers. Finally, I learned about random values and how they can be used in determining possible results in an expression.
- Reflection Practicing random.shuffle
import random
number_list = [19, 11, 21, 28, 35, 42, 49, 56, 63, 70]
print("Original list:", number_list)
random.shuffle(number_list)
print("List after first shuffle:", number_list)
random.shuffle(number_list)
print("List after second shuffle:", number_list)
- Reflection Practicing random.choice
import random
number_list = [111, 222, 333, 444, 555]
print(random.choice(number_list))
- Reflection Practice Documentation
def numAverage(value):
sumNums = 0
for t in value:
sumNums = sumNums + t
average = sumNums / len(value)
return average
print("The number average is", numAverage([1, 2, 3, 4, 5, 6, 61, 84, 81, 83]))
Multiple choice
- 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 the random function mean a random integer from the parameters set will be chosen. a,b are the parameters, a random integer from a to b will be given, including a and b.
- 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 because the randrange function has the parameters so that the the start, x is the minimum value. Y is the stop (maximum), and z is the step/increment the values can be.
- Which of the following is NOT part of the random library? A. random.item
B. random.random
C. random.shuffle
D. random.randint
ANSWER: A because the item() function is used in dictionaries to find an item in the dictionary. Since it does not have any parameters, is not a part of the random library. Example of a function without the import random funcion.
random = {
"day": "Nike",
"clothing": "shirt",
"year": 2012
}
x = random.items()
random["year"] = 2018
print(x)
Short Answer Questions
- What is the advantage of using libraries?
Libraries are already pre-written and can be referenced in your code. Instead of taking the time to rewrite the same code multiple times, libraries are reusable functions that can be used without redefining them. Overall, libraries are efficient, easier for coding complex functions, and reducing coding errors.
- Write a thorough documentation of the following code.
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!")
Documentation:
Using the library random, I set the variable names_string equal to the the names the user provides/inputs.
The split function will separate the names with a comma.
num_items will give each name given a number and using the random function randint, it randomly select a number that corresponds to a name.
The procedure returns the name and the sentence.
import random
namesList = ["Ellie", "Katie", "Haeryn", "Dylan", "Ava", "Olivia", "Sreeja", "Yuna", "Hannah", "Taylor", "Madison", "Lizzy", "Evan", "Hailey", "Ella"]
sample_namesList = random.sample(namesList, k=5)
print(f" These are your 5 random names: {sample_namesList}!")
EXPLANATION: First I created a list that had all the names I wanted to use, I chose to use the names of my friends. Then I set a variable equal to a function that would pick 5 different random names. I used the random library function choices and set k equal to 5 which would choose 5 options from the list. After printing the list the random.sample function allows me to get 5 names.
- 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
p1dice1 = random.randrange(1,6)
p1dice2 = random.randrange(1,6)
print("Player 1 rolled a", p1dice1, "and", p1dice2, "for a sum of:", p1dice1+p1dice2)
p2dice1 = random.randrange(1,6)
p2dice2 = random.randrange(1,6)
print("Player 2 rolled a", p2dice1, "and", p2dice2, "for a sum of:", p2dice1+p2dice2)
p1sum = p1dice1 + p1dice2
p2sum = p2dice1 + p2dice2
if p1sum > p2sum:
print("Player 1 wins!")
elif p1sum == p2sum:
print("Roll again! You both rolled the same sum.")
else:
print("Congratulations! Player 2 wins!")
Explanation: Using the random library, I set variables equal to a random number 1-6, which represents rolling the dice. I named the variables based on who rolled and what number they rolled it. Then I added the numbers together, whichever player had the higher sum wins.
import random
width = 5
height = 5
obstacles = 15
maze = [[0 for i in range(width)] for j in range(height)]
for i in range(obstacles):
x = random.randint(0, width - 1)
y = random.randint(0, height - 1)
maze[x][y] = 'x'
def startEnd():
a = random.randint(0, width - 1)
b = random.randint(0, height - 1)
maze[a][b] = 'S'
c = random.randint(0, width - 1)
d = random.randint(0, height - 1)
maze[c][d] = 'E'
startEnd()
for row in maze:
print(' '.join(str(cell) for cell in row))
import random
direction = ["up", "down", "left", "right"]
itemDirection = random.choices(direction)
print(f"Initial direction of the robot: {itemDirection}")
startNumber = random.randrange(1,25)
print(f"Where the robot started: {startNumber}")
goalPosition = []
for i in range(1):
r=random.randrange(1,25)
if r != startNumber:
goalPosition.append(r)
print(f"The goal position is: {goalPosition}")
obstacles = []
for i in range(12):
r=random.randint(1,25)
if r != startNumber:
obstacles.append(r)
if r != goalPosition:
obstacles.append(r)
if r not in obstacles:
obstacles.append(r)
print(f"The goal position is: {obstacles}")