(1) Reflection

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

I learned many things from this lesson on sections 14-15. I learned about how libraries make coding more efficient because prewritten code can be used to simplify a program. I also learned about how procedures can be created so you don't have to use a series of commands to do something every time. For example, creating a procedure for moving a robot backwards and using it when necessary is much more efficient that using something like "rotate right, rotate right, move forward" every time you want to make the robot move backwards. I learned about how documentation gives an explanation of what a certain procedure does. Lastly, I learned about the random library and all of its functions that allows us to randomly generate values in different ways.

Notes

  • Libraries contain prewritten code that can be used by programmers
  • Programmers use libraries to make their code more efficient and easier to follow
  • Documentation allows for programmers to understand what each procedure or function does
  • An API is a way for computer programs to communicate with each other and access information
  • The random library is an example of a library that allows you to use different functions that allow you to generate random values
  • Examples of functions present in the random library:
    • random.randint(a,b): chooses a random integer between a and b (inclusive)
    • random.choice(list): chooses a random element from a list
    • random.shuffle(list): randomly rearranges the elements in a list
    • random.randrange(start, stop, step): similar to random.randint with the minimum and maximum values, but random.randrange needs a "step" parameter which takes in the increment by which the possible values increases by (default increment value of 1)

(2) 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.

☆ My answer: The answer is choice B because this function will randomly generate an integer from a to b (including the values a and b).

  1. 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

☆ My answer: The correct answer is choice A. This is because x is the starting or minimum value, y is the stopping or maximum value, and z is the step or value that the possible integers increment by.

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

A. random.item

B. random.random

C. random.shuffle

D. random.randint

☆ My answer: The answer to this question is A because all of the other functions exist. The function random.random generates a random float between 0 and 1. The function random.shuffle randomly rearranges the elements of the list it takes in. Lastly, random.randint generates a random integer.

(3) Short Answer Questions

  1. What is the advantage of using libraries?

☆ My answer: Using libraries is advantageous because they contain prewritten code that can be used by programmers to make their code more efficient and easier to follow.

  1. 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!")
Sachit is going to buy the meal today!

Documentation: The input() function prompts the user with a statement that the user needs to respond to. In this case, the user is prompted to enter everybody's names. The split() function will separate the names with commas. The len() function is used to find the length of the list of names. The random.randint() is used to generate a number from (representing index of the list) 0 to the length of the list minus 1. The person who will pay is selected using the randomly generated index of the list. The final print statement will print the person selected and states that they will buy the meal.

(4) Coding Challenges!

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

  1. Create a program to pick five random names from a list of at least 15 names
</div> </div> </div>
import random

names = ["Alex", "Emma", "David", "Grace", "Henry", "Noah", "Benjamin", "Luna", "Christopher", "Jayden", "Lucas", "Elijah", "Sophia", "Abigail", "Charlotte", "Mason"]
selected = []
checkDuplicates = [] # to make sure there aren't any duplicate names generated

for i in range(5):
    generated = random.choice(names)
    while generated in checkDuplicates:
        a = random.choice(names)
    checkDuplicates.append(generated)
    selected.append(generated)

print("5 Random Names:")
for name in selected:
    print(name)
5 Random Names:
Elijah
Sophia
Charlotte
Jayden
Abigail
  1. 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

# players start with 0 points before rolling
player1 = 0
player2 = 0

#rolls for player1:
roll1 = random.randint(1,6)
roll2 = random.randint(1,6)
player1sum = roll1 + roll2
print("Player 1 Sum: " + str(player1sum))

#rolls for player2:
roll1 = random.randint(1,6)
roll2 = random.randint(1,6)
player2sum = roll1 + roll2
print("Player 2 Sum: " + str(player2sum))

#Displaying which player is the winner:
if player1sum > player2sum:
    print("Player 1 is the winner!")
elif player1sum < player2sum:
    print("Player 2 is the winner!")
else:
    print("Both players have tied!")
Player 1 Sum: 7
Player 2 Sum: 8
Player 2 is the winner!

Extra Credit

Create a program to randomly generate one of those 5x5 square CollegeBoard robot courses frequently seen in these lessons. Here are the criteria:

  • No need to create a graphical user interface (output the course in graphical form); that would be too demanding. You can use store your randomizations in variables to be printed, after which you can sketch one instance of your output using any means (handdrawn, google drawings, etc.) to attach to your submission as an image.

  • Your illustration can differ graphically from CollegeBoard's illustrations as long as the robot, its direction, the wall squares, and the goal square are fairly self-evident (ie you can make the goal a present or food instead of a gray square)

You must randomize the following:

  1. Initial direction of the robot (up, down, left, right)
  2. Initial Position of the robot
  3. Goal position
  4. Positions of at least 12 wall/obstacle squares

The latter three must be mutually exclusive (on different squares). This prevents you from generating a course where the robot is on the goal, on a wall square, or the goal is in a wall square

import random

directions = ["up", "down", "left", "right"]
initialDirection = random.choice(directions) # randomly chooses direction
print("Initial Direction: " + initialDirection) 

initialPosition = random.randint(1,25) # integer generated represents square number
print("Initial Position: " + str(initialPosition))

goalPosition = random.randint(1,25)
while goalPosition == initialPosition: # while loops ensures initial position can't be same as goal position
    goalPosition = random.randint(1,25)
print("Goal Position: " + str(goalPosition))

obstacles = [] # list that will hold all obstacle square numbers
checkDuplicates = []

for i in range(12): # generates 12 obstacles
    a = random.randint(1,25)
    while a in checkDuplicates: # makes sure a is not already present in list to ensure unique obstacle squares
        a = random.randint(1,25)
    while a == initialPosition or a == goalPosition: # makes sure a is not equal to initial or goal squares
        a = random.randint(1,25)
    checkDuplicates.append(a)
    obstacles.append(a)

print("Location of Obstacles: " + str(obstacles))
Initial Direction: up
Initial Position: 5
Goal Position: 9
Location of Obstacles: [15, 8, 12, 24, 20, 21, 19, 18, 3, 1, 2, 4]
</div>