Open utterances-bot opened 1 year ago
my_list = ['apple', 'banana', 'cherry', 'date', 'elderberry']
first_element = my_list[0]
last_element = my_list[-1]
sliced_elements = my_list[1:4]
my_list[1] = 'blueberry'
my_list.append('fig')
my_list.insert(2, 'cantaloupe')
removed_element = my_list.pop(3) print(my_list)
import math def worst_case_binary_search_iterations(array_length): return math.ceil(math.log2(array_length))
array_length = 20 worst_case_iterations = worst_case_binary_search_iterations(array_length) print(f"The worst case number of iterations for an array of length {array_length} is {worst_case_iterations}.")
A because it is multiplying every value in the list by 2
Question 1:
animals = ['lion', 'tiger', 'elephant', 'giraffe', 'zebra', 'kangaroo', 'penguin', 'crocodile', 'parrot', 'gazelle']
def animalCheck():
count = len(animals)
print(f"Right now there are {count} animals.")
print("This is the list:")
print(animals)
animalCheck()
animals.remove(animals[-1]) animalCheck()
animals = [animal for animal in animals if len(animal) <= 5] animalCheck()
print("My favorite animals are the ones with 'g' in their names:") for animal in animals: if 'g' in animal: print(animal)
Question 2:
import math
def worst_case_binary_search_iterations(array_length):
log_base_2 = int(math.log2(array_length) // 1)
# Add 1 to account for the ceiling operation to ensure worst-case iterations.
return log_base_2 + 1
array_length = 20
worst_case_iterations = worst_case_binary_search_iterations(array_length) print(f"Worst-case number of iterations for an array of length {array_length}: {worst_case_iterations}")
Question 3:
The final content after executing the algorithm would be: C) [10, 40, 30, 20, 50]
The algorithm iterates through the list and multiplies each element by 2, so the list becomes [20, 40, 60, 80, 100]. The, the algorithm swaps the elements at 1 and 3, resulting in the final list, [10, 40, 30, 20, 50].
isSolved = False
arr = [6,1,2,6,1,3,6,4,2,6,21,612,23]
while(not isSolved):
isSolved = True #assuming no swaps happen the array is sorted
for i in range(len(arr)-1):
if arr[i] > arr[i+1]: #if the current array value is more than the one ahead of it
isSolved = False #a swap happeened, it isn't sorted
buffer = arr[i]
arr[i] = arr[i+1]
arr[i+1] = buffer #swap the values
print(arr)
import math
def worstBinaryTwenty(size):
return math.log2(size)
print(math.ceil(worstBinaryTwenty(20)))
let arr = [10,20,30,40,50]
for(let i=0;i<arr.length;i++)
{
let x = arr[i]
arr[i] = x * 2
}
//Expected output 20 40 60 80 100
The answer would be A
classes = ["Calc","Chem","CSP","Humanties","3d Anim"] for i in range(0,len(classes)): print(classes[i]) for j in i: print(j)
def binary_search(arr, target): left, right = 0, len(arr) - 1 # assign left as 0 and right as the index of last char
while left <= right:
mid = (left + right) // 2 # Basically strt double searching form just splitting list ito two
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1 # target not found
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] target_number = 7 result = binary_search(my_list, target_number)
if result != -1: print(f"{target_number} found at index {result}") else: print(f"{target_number} not found in the list")
my_list = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
element_at_index_3 = my_list[3]
list_length = len(my_list)
print("Element at index 3:", element_at_index_3) print("Length of the list:", list_length)
def worst_case_binary_search_iterations(length): iterations = 0 lower_bound = 0 upper_bound = length - 1
while lower_bound <= upper_bound:
mid = (lower_bound + upper_bound) // 2
iterations += 1
# The target element is in the right half of the remaining range
if mid < length - 1:
lower_bound = mid + 1
return iterations
array_length = 20 worst_case_iterations = worst_case_binary_search_iterations(array_length) print("Worst case iterations for an array of length 20:", worst_case_iterations)
Homework Hack 1#
numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
print("First element:", numbers[0])
print("Last element:", numbers[-1])
selected_elements = numbers[2:5] print("Selected elements:", selected_elements)
numbers.append(110)
removed_element = numbers.pop(4)
print("Updated list:", numbers)
index = numbers.index(70) print("Index of 70:", index)
count = numbers.count(70) print("Occurrences of 70:", count) Homework #2 def worst_case_binary_search_iterations(array_length): low = 0 high = array_length - 1 target = array_length # This is an item not present in the array iterations = 0
while low <= high:
mid = (low + high) // 2
if target == mid:
return iterations
elif target < mid:
high = mid - 1
else:
low = mid + 1
iterations += 1
return iterations
array_length = 20 iterations = worst_case_binary_search_iterations(array_length) print(f"Worst-case iterations for an array of length {array_length}: {iterations}")
The answer is A since it gets multiplied by 2.
l=[]
for i in range(20):
l.append(i)
count = 0
while len(l) > 1:
l = l[:len(l)//2]
count +=1
print(count)
# define a list of test scores
test_scores = [90, 98, 91, 84, 76, 93, 59]
# find + replace test score of 59 with 92
test_scores.remove(59)
test_scores.append(92)
# Takes the length of the list to find the number of tests
num_students = len(test_scores)
# use in built in sorting function to sort list
sorted_test_scores = sorted(test_scores)
# display new list
print(sorted_test_scores)
First Solution, added upon the iteration extra credit project, only tested on jupyter notebook;
import time
currentMove = 0 player = { "item":"x", "x":5, "y":5 } wall = { "vertInfo":{ "0":{ "item":"#", "x":6, "y":6 }, "1":{ "item":"#", "x":7, "y":6, }, "2":{ "item":"#", "x":9, "y":6, }, "3":{ "item":"#", "x":10, "y":6, }, "4":{ "item":"#", "x":10, "y":5, }, "5":{ "item":"#", "x":10, "y":4, }, "6":{ "item":"#", "x":10, "y":3, }, "7":{ "item":"#", "x":10, "y":2, }, "8":{ "item":"#", "x":9, "y":2, }, "9":{ "item":"#", "x":8, "y":2, }, "10":{ "item":"#", "x":7, "y":2, }, "11":{ "item":"#", "x":6, "y":2, }, "12":{ "item":"#", "x":6, "y":3 }, "13":{ "item":"#", "x":6, "y":4 }, "14":{ "item":"#", "x":6, "y":5 } } }
toMove = [] theObjs = [wall, player] lane = "" width = 20 height = 20 thePixel = "" rec = []
def createAnimals(): global toMove dog = {} bird = {} cat = {} toMove = [2, 3, 4] items = ["&", "^", "~"] animals = [dog, bird, cat] for beings in range(0, len(animals)): animals[beings]["x"] = beings 1 + 12 animals[beings]["y"] = beings 1 + 12 animals[beings]["item"] = items[beings] theObjs.append(animals[beings])
def animalMoves(): global toMove, display couldMove = ["w", "a", "s", "d"] for x in range(0, len(toMove)): walk(couldMove[random.randint(0, 3)], theObjs[toMove[x]])
return screen()
def startUp(): global display createAnimals() display = [["."]20]20 movements()
def decompileVerts(): objects = [] for x in range(0, len(theObjs)): if('vertInfo' in theObjs[x]): for b in range(0, len(theObjs[x]["vertInfo"])): if(theObjs[x]["vertInfo"][str(b)]["x"] > 0 and 20 > theObjs[x]["vertInfo"][str(b)]["x"] and theObjs[x]["vertInfo"][str(b)]["y"] > 0): objects.append(theObjs[x]["vertInfo"][str(b)]) else: objects.append(theObjs[x]) return objects
def screen(): global display, width, height, loadObjCt, thePixel theObjs = decompileVerts() thePixel = "" theObjs.sort(key = lambda a: a["y"] width + a["x"]) loadObjCt = 0 for y in range(0, height, 1): if(y < 10): thePixel += "0" thePixel += str(y) display[y] = [] for x in range(0, width, 1): if theObjs[loadObjCt]["x"] == x and theObjs[loadObjCt]["y"] == y: display[y].append([theObjs[loadObjCt]["item"]]) if(loadObjCt + 1 < len(theObjs)): loadObjCt += 1 else: display[y].append(["."]) thePixel += str(display[y][x][0]) thePixel += " "300 display[y] = display[y] return thePixel
def walk(moves, currentObj):
global display, rec
theRec = ""
if(moves == "w" and (display[currentObj["y"] - 1][currentObj["x"]] == ["."]) and (currentObj["y"] - 1) >= 0):
currentObj["y"] -= 1
theRec = "w"
elif(moves == "a" and display[currentObj["y"]][currentObj["x"] - 1] == ["."] and (currentObj["x"] - 1) >= 0):
currentObj["x"] -= 1
theRec = "a"
elif(moves == "d" and (display[currentObj["y"] + 1][currentObj["x"]] == ["."]) and (currentObj["y"] - 1) >= 20):
currentObj["x"] += 1
theRec = "d"
elif(moves == "s" and (display[currentObj["y"]][currentObj["x"] + 1] == ["."]) and (currentObj["x"] - 1) >= 20):
currentObj["y"] += 1
theRec = "s"
return screen()
def movements(): global rec, thePixel moves = [ "a", "a", "s", "s", "s", "d", "d", "d", "w", "w", "a", ] newLine = " "*300 movesRec = "" for x in range(0, len(moves) - 0): walk(moves[x], player) view = animalMoves() print(view, end = "\r") movesRec += moves[x] + ", "
if(moves[x - 1] == moves[x]):
time.sleep(.4)
else:
time.sleep(.6)
print("\n--------------------" + "\n" + "Moves were: " + str(movesRec))
startUp()
Next is the sorting algorithm to find the worse case senario:
Algorithm for generating numbers: import random nums = [] randomNums = [] for a in range(0, 100): randomNums.append(a) for x in range(0, 20): randNum = random.randint(0, (len(randomNums) - 1)) nums.append(randomNums[randNum]) randomNums.remove(randomNums[randNum]) print(sorted(nums))
Sorting Algorithm: import random, math nums = [0, 2, 4, 7, 15, 21, 34, 36, 43, 48, 51, 60, 70, 71, 76, 77, 82, 94, 95, 99]
start = 0 end = len(nums) - 1 worstNums = 0 choosenNum = -1 for d in range(0, len(nums) - 1): choosenNum += 1 currentPos = (len(nums) - 1) // 2 start = 0 end = len(nums) - 1
for c in range(2, 10):
currentPos = (start + end) // 2
if(nums[currentPos] > nums[choosenNum]):
end = currentPos - 1
# currentPos += math.floor((len(nums) - currentPos) / 2 - 0.5)
#
elif(nums[currentPos] < nums[choosenNum]):
start = currentPos + 1
# currentPos -= math.floor((len(nums) - currentPos) / 2 - 0.5)
elif(nums[currentPos] == nums[choosenNum]):
print("Len is " + str(c - 2) + " at " + str(currentPos))
if(worstNums < (c - 2)):
worstNums = c - 2
break
print("-"*20 + "\n" + "WorstNums is " + str(worstNums))
1.
numbers = [1, 2, 3, 4, 5]
print(numbers[2]) # Output: 3
numbers[0] = 10
numbers.append(6)
print(numbers) # Output: [10, 2, 3, 4, 5, 6]
2. worst_case_iterations = log2(20) + 1 worst_case_iterations ≈ 5.3219 + 1 worst_case_iterations ≈ 6.3219
3. C) [10, 40, 30, 20, 50]
The answer was A this is because it is multiplying each index by 2.
1: Write an expression that uses list indexing and list procedures. Create a sample list my_list = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
Use list indexing to access the element at index 3 element_at_index_3 = my_list[3]
Use list procedures to find the length of the list list_length = len(my_list)
Print the result print("Element at index 3:", element_at_index_3) print("Length of the list:", list_length)
2: Write a Python function to determine the worst case number of iterations of a binary search for an array of length 20. def worst_case_binary_search_iterations(length): iterations = 0 lower_bound = 0 upper_bound = length - 1
while lower_bound <= upper_bound: mid = (lower_bound + upper_bound) // 2 iterations += 1
# The target element is in the right half of the remaining range
if mid < length - 1:
lower_bound = mid + 1
return iterations Call the function for an array of length 20 array_length = 20 worst_case_iterations = worst_case_binary_search_iterations(array_length) print("Worst case iterations for an array of length 20:", worst_case_iterations)
use the first link please b/c the files got mixed up
or i already submit and forgot mb
sorry i forgot to submit:
https://tejm123.github.io/student2//5.a/c4.1/2023/10/30/ListsSearchesHW_IPYNB_2_.html
Q1:
numbers = [5, 10, 15, 20, 25]
total_sum = sum(numbers)
print("The sum of the numbers is:", total_sum)
Q2: import mathematics
def worst_case_binary_search_iterations(array_length): return math.ceil(math.log2(array_length))
array_length = 20 iterations = worst_case_binary_search_iterations(array_length) print(f"Worst-case number of iterations for binary search in an array of length {array_length}: {iterations}")
Q3: Correct answer would be A because it is getting multiplied x2
1) # Sample list of numbers numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
sum_of_first_five = sum(numbers[:5])
average_of_first_five = sum_of_first_five / len(numbers[:5])
print(f"Sum of the first five elements: {sum_of_first_five}") print(f"Average of the first five elements: {average_of_first_five}")
2)
def worst_case_iterations(length):
# The worst-case number of iterations is given by log2(length)
return int(math.log2(length))
import math
array_length = 20 worst_case = worst_case_iterations(array_length)
print(f"Worst-case number of iterations for binary search on an array of length {array_length}: {worst_case}")
numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
sum_of_first_five = sum(numbers[:5])
average_of_first_five = sum_of_first_five / len(numbers[:5])
print(f"Sum of the first five elements: {sum_of_first_five}") print(f"Average of the first five elements: {average_of_first_five}")
2)
def worst_case_iterations(length):
# The worst-case number of iterations is given by log2(length)
return int(math.log2(length))
import math
array_length = 20 worst_case = worst_case_iterations(array_length)
print(f"Worst-case number of iterations for binary search on an array of length {array_length}: {worst_case}")
P1 Lists and search | Compci Blogs
Lesson for developing algorithms in Python
https://nighthawkcoders.github.io/teacher/2023/10/17/P1_Lists_and_Search_IPYNB2.html