Lists
Binary Search
What is Binary Search?
- Binary search is a search algorithm that finds the position of a target value within a sorted array. Binary search compares the target value to the middle element of the array.
- An algorithm for iterating to find a value inside a data set
- Binary search compares the target value to the middle element of the array. An algorithm for iterating to find a value inside a data set
def BinarySearch(array, x, low, high):
# Repeat until the pointers low and high meet each other
while low <= high:
mid = low + (high - low)//2 # find the middle (taking the higest index number plus the lowest and divided by two)
if array[mid] == x: # if desired number is the middle is found return desired number (middle number)
return mid
elif array[mid] < x:
low = mid + 1
else:
high = mid - 1
return -1
array = [3, 4, 5, 6, 7, 8, 9]
x = 4
result = BinarySearch(array, x, 0, len(array)-1)
if result != -1:
print("Element is present at index " + str(result))
else:
print("Not found")
Data Abstraction
-Method used in coding to represent data in a useful form, by taking away aspects of data that aren't being used in the situation -Variables and lists are primary tools in data abstraction -Provides a separation between the abstract properties of a data type and the concrete details of its representation
quesCount = 0
score = 0
# Use a dictionary for the questions
quesList = ["What team is Lebron James on?", "Who won the 2022 NBA Championship?","Who is the best player on the Mavericks?","Who is the best 3 point shooter in the NBA?"]
# Use a dictionary for the correct solutions
soluList = ["Lakers", "Golden State Warriors", "Luka Doncic", "Stephen Curry"]
quesAmount= len(quesList)
while quesCount < quesAmount:
print(quesList[quesCount] + "\n")
guess = input()
if(guess == soluList[quesCount]):
score += 1
print("Correct! Score: ")
else:
print("Incorrect! The correct answer was " + soluList[quesCount] + "\n")
print(quesCount)
print(quesAmount)
quesCount += 1
Procedures
- A procedure is a named group of programming instructions that may have parameters and return values.
- Procedures are referred to by different names, such as method or function, depending on the programing language.
- Parameters are input values of a procedure. Arguments specify the values of the parameters when procedure is called.
- A procedure call interrupts the sequential execution of statements causing the program to execute the statements within the procedure before continuing. One the last statement in the procedure (or a return statement) has executed, flow or control is returned to the point immediately following where the procedure was called.
def convertFahrenheit(temperature):
celsius = temperature - 32
celsius = celsius * 5 / 9
return celsius
outsideTemp = input("What is the temperature Outside?")
print(convertFahrenheit(int(outsideTemp)))
brands = ["baseball", "soccer", "basketball"] #string
numbers = [1, 2, 3, 4, 5] #integer
truefalse = [True, False, True] #boolean
num1 = 100
num2 = 44
sum = num1 + num2
if sum == 200:
{
print(200)
}
else:
{
print(sum)
}
What is a simulation?
- A simulation is a tested scenario used for viewing results/outputs to prepare for them in real world situations
- These can be used for games like dice rolling, spinners, etc
- These can be used for practical things such as building structures, testing car crashes, and other things before engaging in them in the real world
- These simulations can have the option of obeying real world physics (Gravity, collision) or they can go against these norms since this is a fictitious scenario, and couldn't happen in real life
pos = 20
# The ball is initially moving upwards at a velocity of 30 units/second
vel = 30
# The acceleration due to gravity is 5.5 units/second^2 downwards
g = -5.5
# We will update the position of the ball every 0.2 seconds
dt = 0.2
# Keep track of the time
time = 0
# Main loop of the simulation
while True:
# Update the position of the ball
pos = pos + vel * dt
# Update the velocity of the ball
vel = vel + g * dt
# If the ball hits the ground, reverse its direction
if pos <= 0:
vel = -vel
# Increment the time by the timestep
time = time + dt
# Print the current position and velocity of the ball
print(f"Time: {time:.1f} s | Position: {pos:.1f} units | Velocity: {vel:.1f} units/s")
# End the simulation after 10 seconds
if time >= 10:
break
currentScore = 10
highScore = currentScore
currentScore = 7
print(highScore)
10
Iteration
Iteration refers to the repetition of a process, and there are two types: indefinite and definite. In a definite iteration, it is clear how many times the loop will run, while in an indefinite iteration, the number of times the loop will run is not specified. For loops and while loops are examples of iteration. An object is considered iterable if it can be used in an iteration, and the built-in function 'iter()' returns an iterator for an object. Some common examples of iterable objects include strings, lists, dictionaries, sets, and tuples. The break statement can be used to stop a loop prematurely.
words = ["alfa", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india", "juliett", "kilo",
"lima", "mike", "november", "oscar", "papa", "quebec", "romeo", "sierra", "tango", "uniform", "victor", "whiskey", "xray", "yankee", "zulu"]
inp = input().lower()
alpha = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
for i in words:
print(inp)
Procedures
A procedure, also known as a method or function, is a group of programming instructions that can accept input values (called parameters) and may return a value or perform a specific task. When a procedure is called, the program execution is temporarily interrupted and the statements within the procedure are executed before control is returned to the point where the procedure was called. It is important to note whether a procedure returns data or simply performs a block of statements. If it returns data, the value can be stored in a variable. For example, in Python, we can define a procedure named "convertFahrenheit" that converts temperature from Fahrenheit to Celsius. The pseudocode for this procedure might look like this:
def convertFahrenheit(temp_fahrenheit):
temp_celsius = (temp_fahrenheit - 32) * (5/9)
return temp_celsius
temp_outside_fahrenheit = 72
temp_outside_celsius = convertFahrenheit(temp_outside_fahrenheit)
print(temp_outside_celsius)