nighthawkcoders / teacher

Jupyter Notebooks and Posts dedicated to learning Python
MIT License
0 stars 63 forks source link

P1 Lists and search | Compci Blogs #40

Open utterances-bot opened 1 year ago

utterances-bot commented 1 year ago

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

monke7769 commented 1 year ago

https://monke7769.github.io/copy1/310311

abby-albert commented 1 year ago

1:

Creating a list

my_list = ['apple', 'banana', 'cherry', 'date', 'elderberry']

Accessing the first element of the list

first_element = my_list[0]

Accessing the last element of the list

last_element = my_list[-1]

Slicing the list to get elements from index 1 to 3 (exclusive)

sliced_elements = my_list[1:4]

Modifying the second element of the list

my_list[1] = 'blueberry'

Appending a new element to the list

my_list.append('fig')

Inserting a new element at a specific index

my_list.insert(2, 'cantaloupe')

Removing an element from the list

removed_element = my_list.pop(3) print(my_list)

2:

import math def worst_case_binary_search_iterations(array_length): return math.ceil(math.log2(array_length))

Determine worst case number of iterations for an array of length 20

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}.")

3:

A because it is multiplying every value in the list by 2

AnvayYadav commented 1 year ago

Question 1:

First, I made a new list full of animals

animals = ['lion', 'tiger', 'elephant', 'giraffe', 'zebra', 'kangaroo', 'penguin', 'crocodile', 'parrot', 'gazelle']

def animalCheck():

Got the number of animals in the list

count = len(animals)
print(f"Right now there are {count} animals.")
print("This is the list:")
print(animals)

animalCheck()

Removed the last animal from the list

animals.remove(animals[-1]) animalCheck()

Used list comprehension to filter out animals with names longer than 5 characters

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

Define a function to calculate the worst-case number of iterations for a binary search.

def worst_case_binary_search_iterations(array_length):

Calculate the base-2 logarithm of the array length and round down (floor).

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

Define the length of the array for which you want to determine the worst-case iterations.

array_length = 20

Call the function to calculate and print the worst-case number of iterations.

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

nitinsandiego commented 1 year ago

https://nitinsandiego.github.io/student//2023/10/19/3.10-3.11-Lists-and-Search_IPYNB_2_.html

SriS126 commented 1 year ago

https://sris126.github.io/student//2023/10/23/ListsandSearchHW_IPYNB_2_.html

spooketti commented 1 year ago

Problem 1

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)

Problem 2

import math
def worstBinaryTwenty(size):
    return math.log2(size)
print(math.ceil(worstBinaryTwenty(20)))

Problem 3

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

alaraipek commented 1 year ago

https://alaraipek.github.io/student//2023/10/19/lists-search_IPYNB_2_.html

shuban-789 commented 1 year ago

List HW: Print every element in list and print every character in element

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")

AidanLau10 commented 1 year ago

https://aidanlau10.github.io/student//2023/10/18/list-binary_IPYNB_2_.html

Nupurbb commented 1 year ago

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)

sharonkodali commented 1 year ago

https://sharonkodali.github.io/sharonk//2023/10/23/lists-binary-hw_IPYNB_2_.html

tarunja1ks commented 1 year ago

http://127.0.0.1:4200/student//2023/10/19/teamteachlistsbinarysearch_IPYNB_2_.html

tarunja1ks commented 1 year ago

https://tarunja1ks.github.io/student//2023/10/19/teamteachlistsbinarysearch_IPYNB_2_.html

RayyanDarugar commented 1 year ago

https://rayyandarugar.github.io/student//2023/10/23/Lists_and_OperationsHW_IPYNB_2_.html

SrinivasNampalli commented 1 year ago

Homework Hack 1#

Create a list of numbers

numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Access and print the first element (index 0) of the list

print("First element:", numbers[0])

Access and print the last element (index -1) of the list

print("Last element:", numbers[-1])

Slice the list to select elements from index 2 to 5 (exclusive)

selected_elements = numbers[2:5] print("Selected elements:", selected_elements)

Append a new number (110) to the end of the list

numbers.append(110)

Remove the element at index 4 (number 50)

removed_element = numbers.pop(4)

Print the modified list

print("Updated list:", numbers)

Find the index of a specific number (70)

index = numbers.index(70) print("Index of 70:", index)

Count the occurrences of a number (70) in the list

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}")

3

The answer is A since it gets multiplied by 2.

Nathaniel633 commented 1 year ago

https://github.com/Nathaniel633/student/blob/main/_notebooks/2023-10-25-lists-and-search.ipynb

Flying-Book commented 1 year ago
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)
ShakeSphereStuff commented 1 year ago

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))

ChrisP121 commented 1 year ago

1.

Create a list of numbers

numbers = [1, 2, 3, 4, 5]

Access and print the third element (index 2) from the list

print(numbers[2]) # Output: 3

Modify the first element (index 0) of the list

numbers[0] = 10

Append a new element to the end of the list

numbers.append(6)

Print the updated list

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]

Djxnxnx commented 1 year ago

https://djxnxnx.github.io/student//5.a/c4.1/2023/10/27/listsandsearch_IPYNB_2_.html

alishahussain commented 1 year ago

http://127.0.0.1:4200/student2//2023/10/23/list-binary_IPYNB_2_.html

alishahussain commented 1 year ago

https://alishahussain.github.io/student2//2023/10/23/list-binary_IPYNB_2_.html

tarasehdave commented 1 year ago

https://tarasehdave.github.io//c4.1/2023/10/17/ListsAndSearchTT_IPYNB_2_.html

shuban-789 commented 1 year ago

The answer was A this is because it is multiplying each index by 2.

Tanuj253 commented 1 year ago

https://tanuj253.github.io/student//5.a/c4.1/2023/10/24/lists_IPYNB_2_.html#3

tanvim-18 commented 1 year ago

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)

Tanuj253 commented 1 year ago

https://tanuj253.github.io/student//5.a/c4.1/2023/10/27/procedures_IPYNB_2_.html

Tanuj253 commented 1 year ago

https://tanuj253.github.io/student//5.a/c4.1/2023/10/29/lists_and_searches_IPYNB_2_.html

Tanuj253 commented 1 year ago

use the first link please b/c the files got mixed up

Tanuj253 commented 1 year ago

nvm use this one https://tanuj253.github.io/student//5.a/c4.1/2023/10/29/lists_and_searches_IPYNB_2_.html

Tanuj253 commented 1 year ago

or i already submit and forgot mb

TejM123 commented 1 year ago

sorry i forgot to submit:

https://tejm123.github.io/student2//5.a/c4.1/2023/10/30/ListsSearchesHW_IPYNB_2_.html

parkib commented 1 year ago

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

SOoctosnake commented 1 year ago

https://sooctosnake.github.io/student_october//2023/10/19/binary_search.html

vidhaganji commented 1 year ago

1) # Sample list of numbers numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Using list indexing and list procedures to calculate the sum of the first five elements

sum_of_first_five = sum(numbers[:5])

Calculate the average of the first five elements

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):

Binary search divides the array in half at each iteration

# 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}")

vibha-yganji commented 1 year ago

Sample list of numbers

numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Using list indexing and list procedures to calculate the sum of the first five elements

sum_of_first_five = sum(numbers[:5])

Calculate the average of the first five elements

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):

Binary search divides the array in half at each iteration

# 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}")