nighthawkcoders / teacher

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

P1 Developing Algorithms | Compci Blogs #36

Open utterances-bot opened 1 year ago

utterances-bot commented 1 year ago

P1 Developing Algorithms | Compci Blogs

Lesson for developing algorithms in Python

https://nighthawkcoders.github.io/teacher/2023/10/09/P1_developingalgorithms_IPYNB2.html

nitinsandiego commented 1 year ago

https://nitinsandiego.github.io/student//2023/10/17/3.9-And-3.15_IPYNB_2_.html

shuban-789 commented 1 year ago
import random

def getmedian(list):
  if len(list)%2 == 0: 
  # If the length of the list is even, get average of the two middle numbers
    return (list[len(list)//2-1]+list[len(list)//2])/2
  if len(list)%2 == 1:
  # If the length of the list is odd, just get the middle element
    return (list[(len(list)-1)/2])

def getclassmed():
  chemscores = [99,52,107,87,92,103,82,88,91,77,95,81,100,75,79,85,89,93,100,72]
  n = len(chemscores) # Sort with (good) bubble sort, then get median
  for i in range(n):
      for j in range(0,n-i-1):
          if chemscores[j] > chemscores[j+1]:
            chemscores[j], chemscores[j+1] = chemscores[j+1], chemscores[j]
  return getmedian(chemscores)

def randomgame(): # Generate random number and keep prompting till the answer is correct
  number = random.randint(1,100)
  correct = 0
  while correct != 1:
    n = int(input("Put your guess: "))
    if n == number:
      print("Correct!")
      correct = 1
    elif n > number:
      print("Too high!")
    elif n < number:
      print("Too low!")
  return

if __name__ == "__main__":
  print(getclassmed())
  randomgame()

All the homework is included in this one program. They are separated into respective functions.

devaSas1 commented 1 year ago

Hw 1: import statistics

List of test grades

test_grades = [85, 92, 78, 90, 88, 76, 94, 89, 81, 87]

Calculate the median

median_grade = statistics.median(test_grades)

Print the median test grade

print("The median test grade is: {median_grade}") (edited) 9:26 HW 2: import random def guess_the_number():

Generate a random number between 1 and 100

secret_number = random.randint(1, 100)
# Set the initial number of tries
tries = 0
print("Welcome to the Guess the Number game!")
print("I'm thinking of a number between 1 and 100.")
while True:
    # Ask the player to guess the number
    guess = int(input("Enter your guess: "))
    # Increment the number of tries
    tries += 1
    # Check if the guess is correct
    if guess == secret_number:
        print(f"Congratulations! You guessed the number {secret_number} in {tries} tries.")
        break
    elif guess < secret_number:
        print("Too low. Try again.")
    else:
        print("Too high. Try again.")

if name == "main": guess_the_number()

https://github.com/devaSas1/student/blob/main/_notebooks/2023-10-17-DevelopingAlgorithms.ipynb

spooketti commented 1 year ago

median test grade

txt = str(input("enter grades with spaces between grades"))

x = txt.split()

for i in range(len(x)):
    x[i] = int(x[i])
median = 0
if((len(x))%2==0):
    median = (x[int(len(x)/2)]+x[int(len(x)/2)-1])/2
else:
    median = x[int(len(x)/2)]
print(median)

simple game

import random

choice = random.randint(1,6)

answer = int(input("Rolling a 6 sided die, choose a side to bet on"))
if answer == choice:
    print("you won")
else:
    print("sucks to be you")

jonathan liu

monke7769 commented 1 year ago

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

AidanLau10 commented 1 year ago

https://aidanlau10.github.io/student//2023/10/15/developing-algorithms_IPYNB_2_.html

abby-albert commented 1 year ago

1:

scores = [87, 92, 78, 65, 80, 90, 88, 72] scores.sort() n = len(scores) if n % 2 == 0: median = (scores[n // 2 - 1] + scores[n // 2]) / 2 else: median = scores[n // 2] print("The median of the class test scores is:", median)

2:

import random lower_limit = 1 upper_limit = 100 random_number = random.randint(lower_limit, upper_limit) guessed_number = None print("Welcome to the Number Guessing Game!") print(f"I have chosen a number between {lower_limit} and {upper_limit}. Let's see if you can guess it.") while guessed_number != random_number: try: guessed_number = int(input("Enter your guess: "))

    if guessed_number < random_number:
        print("Too low! Try again.")
    elif guessed_number > random_number:
        print("Too high! Try again.")
    else:
        print(f"Congratulations! {random_number} is the correct number. You win!")
        break
except ValueError:
    print("Please enter a valid number.")

print("Game Over. Thanks for playing!")

AnvayYadav commented 1 year ago

Student Teaching, Algorithms

Find the median test grade of a class

testscores = [85, 92, 78, 90, 88, 76, 95, 89, 83, 91]

testscores.sort()

num_scores = len(testscores)

if num_scores % 2 == 1: median = testscores[num_scores // 2] else: middle1 = testscores[num_scores // 2 - 1] middle2 = testscores[num_scores // 2] median = (middle1 + middle2) / 2

print(f"The median test score is: {median}")

Create a simple game with numbers

import random

secret_number = random.randint(1, 100)

attempts = 0

while True: try: guess = int(input("Guess the secret number (between 1 and 100): ")) attempts += 1

    if guess == secret_number:
        print(f"Congratulations! You guessed the secret number {secret_number} in {attempts} attempts.")
        break
    elif guess < secret_number:
        print("Try a higher number.")
    else:
        print("Try a lower number")

except ValueError:
    print("Enter a valid number.")
peytonl11098 commented 1 year ago

1:

scores = [78, 82, 68, 75,927, 89, 63, 72] scores.sort() n = len(scores) if n % 2 == 0: median = (scores[n // 2 - 1] + scores[n // 2]) / 2 else: median = scores[n // 2] print("The median of the class test scores is:", median)

2:

import random lower_limit = 1 upper_limit = 100 random_number = random.randint(lower_limit, upper_limit) guessed_number = None print("Welcome to the Median Game!") print(f"I have chosen a number between {lower_limit} and {upper_limit}. Let's see if you can guess it.") while guessed_number != random_number: try: guessed_number = int(input("Enter your guess: ")) if guessed_number < random_number: print("Too low! Try again.") elif guessed_number > random_number: print("Too high! Try again.") else: print(f"Congratulations! {random_number} is the correct number. You win!") break except ValueError: print("Please enter a valid number.")

print("Game Over.")

Nupurbb commented 1 year ago

1:

scores = [87, 92, 78, 65, 80, 90, 88, 72] scores.sort() n = len(scores) if n % 2 == 0: median = (scores[n // 2 - 1] + scores[n // 2]) / 2 else: median = scores[n // 2] print("The median of the class test scores is:", median)

2:

import random lower_limit = 1 upper_limit = 100 random_number = random.randint(lower_limit, upper_limit) guessed_number = None print("Welcome to the Number Guessing Game!") print(f"I have chosen a number between {lower_limit} and {upper_limit}. Let's see if you can guess it.") while guessed_number != random_number: try: guessed_number = int(input("Enter your guess: "))

if guessed_number < random_number:
    print("Too low! Try again.")
elif guessed_number > random_number:
    print("Too high! Try again.")
else:
    print(f"Congratulations! {random_number} is the correct number. You win!")
    break

except ValueError: print("Please enter a valid number.")

SrinivasNampalli commented 1 year ago

1# def find_median(grades): sorted_grades = sorted(grades) n = len(sorted_grades) if n % 2 == 1:

Odd number of grades

    median = sorted_grades[n // 2]
else:

    middle1 = sorted_grades[n // 2 - 1]
    middle2 = sorted_grades[n // 2]
    median = (middle1 + middle2) / 2
return median

test_grades = [85, 92, 78, 90, 88, 95] median_grade = find_median(test_grades) print(f"The median test grade is: {median_grade}")

2# import random

def roll_dice(): return random.randint(1, 6)

def play_game(): while True: input("Press Enter to roll the dice...") dice1 = roll_dice() dice2 = roll_dice() total = dice1 + dice2 print(f"You rolled a {dice1} and a {dice2}. Total: {total}")

    if total == 7:
        print("You win!")
    else:
        print("You lose. Try again.")

    play_again = input("Play again? (yes/no): ").lower()
    if play_again != "yes":
        print("Thanks for playing!")
        break

if name == "main": print("Welcome to the Dice Rolling Game!") play_game()

SriS126 commented 1 year ago
  1. Find the Median Test Grade of a class

def find_median(grades): sorted_grades = sorted(grades) n = len(sorted_grades)

if n % 2 == 0:
    middle1 = sorted_grades[n // 2 - 1]
    middle2 = sorted_grades[n // 2]
    median = (middle1 + middle2) / 2
else:
    median = sorted_grades[n // 2]

return median

test_grades = [74, 93, 36, 95, 87, 94, 92, 81] median_grade = find_median(test_grades) print(f"The median test grade is: {median_grade}")

  1. Create a simple game using random numbers

import random

def higher_or_lower_game(): current_number = random.randint(1, 100) score = 0

while True:
    print(f"Current number: {current_number}")
    guess = input("Higher (h) or Lower (l) or Quit (q): ").lower()

    if guess not in ['h', 'l', 'q']:
        print("Please enter 'h' for higher, 'l' for lower, or 'q' to quit.")
        continue

    next_number = random.randint(1, 100)

    if (next_number > current_number and guess == 'h') or (next_number < current_number and guess == 'l'):
        score += 1
        current_number = next_number
    else:
        print(f"Game over! Your final score is {score}")
        break

print("Welcome to the higher or lower game!") higher_or_lower_game()

alaraipek commented 1 year ago

https://alaraipek.github.io/student//2023/10/17/Developing-Algorithms_IPYNB_2_.html

alishahussain commented 1 year ago

https://alishahussain.github.io/student2//2023/10/23/devalgorithms_IPYNB_2_.html

sharonkodali commented 1 year ago

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

Sreejarai123 commented 1 year ago

Find the median test Scores: def find_median(scores): sorted_scores = sorted(scores) n = len(sorted_scores)

if n % 2 == 0:
    # If the number of scores is even, take the average of the middle two scores
    middle1 = sorted_scores[n // 2 - 1]
    middle2 = sorted_scores[n // 2]
    median = (middle1 + middle2) / 2
else:
    # If the number of scores is odd, the median is the middle score
    median = sorted_scores[n // 2]

return median

Example usage:

class_scores = [85, 90, 92, 78, 88, 95, 89] median_score = find_median(class_scores) print("Median score:", median_score)

A number guessing game:

def guess_the_number():

Generate a random number between 1 and 100

secret_number = random.randint(1, 100)
attempts = 0

while True:
    # Get the player's guess
    guess = int(input("Enter your guess: "))
    attempts += 1

    # Check if the guess is correct
    if guess == secret_number:
        print(f"Congratulations! You guessed the number in {attempts} attempts.")
        break
    elif guess < secret_number:
        print("Too low. Try again.")
    else:
        print("Too high. Try again.")

Run the game

guess_the_number()

aidenk1 commented 1 year ago
  1. test_scores = [85, 92, 78, 90, 88, 76, 84, 89, 94, 87] sorted_scores = sorted(test_scores) n = len(sorted_scores) if n % 2 == 0: median = (sorted_scores[n // 2 - 1] + sorted_scores[n // 2]) / 2 else: median = sorted_scores[n // 2] print("Median test grade:", median)

  2. import random diceNumber = random.randint(1,6) choice = int(input("What number do you think the dice will land on?: " if choice = diceNumber: print("Congratulations, you were correct" else: print("You were incorrect, try again"

RayyanDarugar commented 1 year ago

https://rayyandarugar.github.io/student//c7.0/2023/10/19/DevAlgorithms_IPYNB_2_.html

Nathaniel633 commented 1 year ago

function findMedian(data) { // Sort the data in ascending order data.sort((a, b) => a - b);

const n = data.length;

// If the number of data points is odd, return the middle value
if (n % 2 !== 0) {
    return data[Math.floor(n / 2)];
} else {
    // If the number of data points is even, return the average of the two middle values
    const mid1 = data[n / 2 - 1];
    const mid2 = data[n / 2];
    return (mid1 + mid2) / 2;
}

}

// Example const classData = [85, 92, 78, 95, 88]; const median = findMedian(classData); console.log("Median:", median);

2

import random

x = input("Do you want to flip a coin? (y/n)")

x = str(x)

if x == "y": coin_flip = random.randint(0, 1) if coin_flip == 0: print("You landed tails!") else: print("You landed heads!")

If they don't want to flip a coin

elif x == "n": print("Maybe next time!") else: print("I\'m not sure what you mean")

tarasehdave commented 1 year ago

https://tarasehdave.github.io//c4.1/2023/10/09/DevelopingAlgorithmsTT_IPYNB_2_.html

ShakeSphereStuff commented 1 year ago

First Assignment

students = [] studentNamePos = [] assignments = [] assignmentNamePos = [] totalGrades = 0.0 def averageGrades(): global totalGrades, students, assignments for theStudent in students: print(theStudent["Name"] + ":") print("-"10) for theAssignment in assignments: print(f'\t Assignment Name: {theAssignment["Name"]}') print(f'\t Assignment Total: {theAssignment["Total"]}') print(f'\t Student Score: {theStudent[theAssignment["Name"]]}') if(theAssignment["Name"] != assignments[-1]["Name"]): print("-" 10) totalGrades += theStudent[theAssignment["Name"]] / theAssignment["Total"]

return totalGrades / (len(assignments) * len(students))

def addStudent(name): global students, assignments, studentNamePos newStudent = { "Name": str(name) } studentNamePos.append(name) for x in assignments: newStudent[str(x["Name"])] = 0 students.append(newStudent) return students

def makeAssignments(assignmentName, assignmentTotal): global assignments, assignmentNamePos newAssignment = {} newAssignment["Name"] = assignmentName newAssignment["Total"] = assignmentTotal assignmentNamePos.append(assignmentName) assignments.append(newAssignment)

def gradeAssignment(studentName, assignmentName, grade): global students, assignmentNamePos, assignments, studentNamePos

If the assignment total is greater than the grade

assignmentTotal = assignments[assignmentNamePos.index(assignmentName)]["Total"]
if(assignmentTotal >= grade):
    students[studentNamePos.index(studentName)][assignmentName] = grade / assignmentTotal 
    print(f'{studentName}\'s grade for {assignmentName} now at a {(grade / assignmentTotal)*100}%')
else:
    print("\t Invalid Input, we only accept point values from 0 to " + str(assignmentTotal))

def startUp(): global students print("Welcome to Grader, the program to do everything with students grades, choose what you want to do;") print("\tChoose A to average the class grades") print("\tChoose B to add a student") print("\tChoose C to make an Assignment") print("\tChoose D to grade an Assignment") print("\tChoose E to end this session") userInput = "" while 7 == 7: if(userInput == ""): print("Now, Choose another item from the list above") userInput = input("What option do you want to choose? ")

    if(userInput.upper() == "A"):
        print(f"{averageGrades()} for a class of {len(students)} student(s)")
        userInput = ""

    elif(userInput.upper() == "B"):
        userInput = input("\tWhat is the student's name? ")
        currentStudents = addStudent(userInput)
        print(currentStudents)
        userInput = ""

    elif(userInput.upper() == "C"):
        assignmentName = input("What is the assignment name? ")
        assignmentTotal = input("What is the assignment total? ")
        try:
            if(assignmentTotal != float("nan") and float(assignmentTotal) > 0):
                makeAssignments(assignmentName, float(assignmentTotal))
                userInput = ""
        except:
            print("Invalid Point Score, please try again")
            userInput = "C"

    elif(userInput.upper() == "D"):
        global assignmentNamePos, studentNamePos
        isValid = [False, False]
        studentAssignment = input("\tWhat is the assignment your grading? ")
        studentGrade = input("\tHow many points did they earn? ")
        studentName = input("\tWhat is the student your grading? ")
        for x in range(0, len(assignmentNamePos)):
            if(studentAssignment.upper() == assignmentNamePos[x].upper()):
                isValid[0] = True
        if(isValid[0] == False):
            print("Invalid Assignment Name, please try again")
            userInput = "D"
        for x in range(0, len(studentNamePos)):
            if(studentName.upper() == studentNamePos[x].upper()):
                isValid[1] = True
        if(isValid[1] == False):
            print("Invalid Assignment Name, please try again")
            userInput = "D"
        try:
            if(studentGrade != float("nan") and float(studentGrade) > 0 and int(isValid[0]) + int(isValid[1]) == 2):
                makeAssignments(assignmentName, float(studentGrade))
                userInput = ""
                gradeAssignment(studentName, studentAssignment, float(studentGrade))
        except:
            print("Invalid Values, please try again")
            userInput = "D"

    elif(userInput.upper() == "E"):
        print("\tHave a lovely day!")
        break

    else:
        print("Invaid Input, please try again")
        userInput = ""

startUp()

Second One

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

ShakeSphereStuff commented 1 year ago

Don’t know why there’s an indent for the last 5 lines, please reinsert the indents after, there’s a lot of them to account for

ShakeSphereStuff commented 1 year ago

Actually, here’s the proper ones

Number 2

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

Number 1

students = [] studentNamePos = [] assignments = [] assignmentNamePos = [] totalGrades = 0.0 def averageGrades(): global totalGrades, students, assignments for theStudent in students: print(theStudent["Name"] + ":") print("-"10) for theAssignment in assignments: print(f'\t Assignment Name: {theAssignment["Name"]}') print(f'\t Assignment Total: {theAssignment["Total"]}') print(f'\t Student Score: {theStudent[theAssignment["Name"]]}') if(theAssignment["Name"] != assignments[-1]["Name"]): print("-" 10) totalGrades += theStudent[theAssignment["Name"]] / theAssignment["Total"]

return totalGrades / (len(assignments) * len(students))

def addStudent(name): global students, assignments, studentNamePos newStudent = { "Name": str(name) } studentNamePos.append(name) for x in assignments: newStudent[str(x["Name"])] = 0 students.append(newStudent) return students

def makeAssignments(assignmentName, assignmentTotal): global assignments, assignmentNamePos newAssignment = {} newAssignment["Name"] = assignmentName newAssignment["Total"] = assignmentTotal assignmentNamePos.append(assignmentName) assignments.append(newAssignment)

def gradeAssignment(studentName, assignmentName, grade): global students, assignmentNamePos, assignments, studentNamePos

If the assignment total is greater than the grade

assignmentTotal = assignments[assignmentNamePos.index(assignmentName)]["Total"]
if(assignmentTotal >= grade):
    students[studentNamePos.index(studentName)][assignmentName] = grade / assignmentTotal 
    print(f'{studentName}\'s grade for {assignmentName} now at a {(grade / assignmentTotal)*100}%')
else:
    print("\t Invalid Input, we only accept point values from 0 to " + str(assignmentTotal))

def startUp(): global students print("Welcome to Grader, the program to do everything with students grades, choose what you want to do;") print("\tChoose A to average the class grades") print("\tChoose B to add a student") print("\tChoose C to make an Assignment") print("\tChoose D to grade an Assignment") print("\tChoose E to end this session") userInput = "" while 7 == 7: if(userInput == ""): print("Now, Choose another item from the list above") userInput = input("What option do you want to choose? ")

    if(userInput.upper() == "A"):
        print(f"{averageGrades()} for a class of {len(students)} student(s)")
        userInput = ""

    elif(userInput.upper() == "B"):
        userInput = input("\tWhat is the student's name? ")
        currentStudents = addStudent(userInput)
        print(currentStudents)
        userInput = ""

    elif(userInput.upper() == "C"):
        assignmentName = input("What is the assignment name? ")
        assignmentTotal = input("What is the assignment total? ")
        try:
            if(assignmentTotal != float("nan") and float(assignmentTotal) > 0):
                makeAssignments(assignmentName, float(assignmentTotal))
                userInput = ""
        except:
            print("Invalid Point Score, please try again")
            userInput = "C"

    elif(userInput.upper() == "D"):
        global assignmentNamePos, studentNamePos
        isValid = [False, False]
        studentAssignment = input("\tWhat is the assignment your grading? ")
        studentGrade = input("\tHow many points did they earn? ")
        studentName = input("\tWhat is the student your grading? ")
        for x in range(0, len(assignmentNamePos)):
            if(studentAssignment.upper() == assignmentNamePos[x].upper()):
                isValid[0] = True
        if(isValid[0] == False):
            print("Invalid Assignment Name, please try again")
            userInput = "D"
        for x in range(0, len(studentNamePos)):
            if(studentName.upper() == studentNamePos[x].upper()):
                isValid[1] = True
        if(isValid[1] == False):
            print("Invalid Assignment Name, please try again")
            userInput = "D"
        try:
            if(studentGrade != float("nan") and float(studentGrade) > 0 and int(isValid[0]) + int(isValid[1]) == 2):
                makeAssignments(assignmentName, float(studentGrade))
                userInput = ""
                gradeAssignment(studentName, studentAssignment, float(studentGrade))
        except:
            print("Invalid Values, please try again")
            userInput = "D"

    elif(userInput.upper() == "E"):
        print("\tHave a lovely day!")
        break

    else:
        print("Invaid Input, please try again")
        userInput = ""

startUp()

ShakeSphereStuff commented 1 year ago

Sorry, proper number 1: students = [] studentNamePos = [] assignments = [] assignmentNamePos = [] totalGrades = 0.0 def averageGrades(): global totalGrades, students, assignments for theStudent in students: print(theStudent["Name"] + ":") print("-"10) for theAssignment in assignments: print(f'\t Assignment Name: {theAssignment["Name"]}') print(f'\t Assignment Total: {theAssignment["Total"]}') print(f'\t Student Score: {theStudent[theAssignment["Name"]]}') if(theAssignment["Name"] != assignments[-1]["Name"]): print("-" 10) totalGrades += theStudent[theAssignment["Name"]] / theAssignment["Total"]

        return totalGrades / (len(assignments) * len(students))
    def addStudent(name):
        global students, assignments, studentNamePos
        newStudent = {
            "Name": str(name)
        }
        studentNamePos.append(name)
        for x in assignments:
            newStudent[str(x["Name"])] = 0
        students.append(newStudent)
        return students

    def makeAssignments(assignmentName, assignmentTotal):
        global assignments, assignmentNamePos
        newAssignment = {}
        newAssignment["Name"] = assignmentName
        newAssignment["Total"] = assignmentTotal
        assignmentNamePos.append(assignmentName)
        assignments.append(newAssignment)

    def gradeAssignment(studentName, assignmentName, grade):
        global students, assignmentNamePos, assignments, studentNamePos
        # If the assignment total is greater than the grade
        assignmentTotal = assignments[assignmentNamePos.index(assignmentName)]["Total"]
        if(assignmentTotal >= grade):
            students[studentNamePos.index(studentName)][assignmentName] = grade / assignmentTotal 
            print(f'{studentName}\'s grade for {assignmentName} now at a {(grade / assignmentTotal)*100}%')
        else:
            print("\t Invalid Input, we only accept point values from 0 to " + str(assignmentTotal))

    def startUp():
        global students
        print("Welcome to Grader, the program to do everything with students grades, choose what you want to do;")
        print("\tChoose A to average the class grades")
        print("\tChoose B to add a student")
        print("\tChoose C to make an Assignment")
        print("\tChoose D to grade an Assignment")
        print("\tChoose E to end this session")
        userInput = ""
        while 7 == 7:
            if(userInput == ""):
                print("Now, Choose another item from the list above")
                userInput = input("What option do you want to choose? ")

            if(userInput.upper() == "A"):
                print(f"{averageGrades()} for a class of {len(students)} student(s)")
                userInput = ""

            elif(userInput.upper() == "B"):
                userInput = input("\tWhat is the student's name? ")
                currentStudents = addStudent(userInput)
                print(currentStudents)
                userInput = ""

            elif(userInput.upper() == "C"):
                assignmentName = input("What is the assignment name? ")
                assignmentTotal = input("What is the assignment total? ")
                try:
                    if(assignmentTotal != float("nan") and float(assignmentTotal) > 0):
                        makeAssignments(assignmentName, float(assignmentTotal))
                        userInput = ""
                except:
                    print("Invalid Point Score, please try again")
                    userInput = "C"

            elif(userInput.upper() == "D"):
                global assignmentNamePos, studentNamePos
                isValid = [False, False]
                studentAssignment = input("\tWhat is the assignment your grading? ")
                studentGrade = input("\tHow many points did they earn? ")
                studentName = input("\tWhat is the student your grading? ")
                for x in range(0, len(assignmentNamePos)):
                    if(studentAssignment.upper() == assignmentNamePos[x].upper()):
                        isValid[0] = True
                if(isValid[0] == False):
                    print("Invalid Assignment Name, please try again")
                    userInput = "D"
                for x in range(0, len(studentNamePos)):
                    if(studentName.upper() == studentNamePos[x].upper()):
                        isValid[1] = True
                if(isValid[1] == False):
                    print("Invalid Assignment Name, please try again")
                    userInput = "D"
                try:
                    if(studentGrade != float("nan") and float(studentGrade) > 0 and int(isValid[0]) + int(isValid[1]) == 2):
                        makeAssignments(assignmentName, float(studentGrade))
                        userInput = ""
                        gradeAssignment(studentName, studentAssignment, float(studentGrade))
                except:
                    print("Invalid Values, please try again")
                    userInput = "D"

            elif(userInput.upper() == "E"):
                print("\tHave a lovely day!")
                break

            else:
                print("Invaid Input, please try again")
                userInput = ""
    startUp()
ShakeSphereStuff commented 1 year ago

Best I could do ^

tarunja1ks commented 1 year ago

https://tarunja1ks.github.io/student//2023/10/18/developingalgorithimshomework_IPYNB_2_.html

AustinZhang1 commented 1 year ago

def find_median(test_grades):

Sort the grades in ascending order

sorted_grades = sorted(test_grades)

n = len(sorted_grades)

# Check if the number of grades is odd or even
if n % 2 == 1:
    # If the number of grades is odd, return the middle value
    median = sorted_grades[n // 2]
else:
    # If the number of grades is even, return the average of the two middle values
    middle1 = sorted_grades[n // 2 - 1]
    middle2 = sorted_grades[n // 2]
    median = (middle1 + middle2) / 2

return median

List of test grades

test_grades = [85, 92, 78, 90, 88, 76, 84, 89, 95, 91]

Calculate the median

median_grade = find_median(test_grades)

print(f"The median test grade is: {median_grade}") import random

number = random.randint(1,10) guess = int(input("Guess a number from 1 to 10: ")) if guess == number: print("Congrats! You guessed the number!") else: print("Sorry, you didn't guess the number.")

DavidL0914 commented 1 year ago

1. Write Python Code or Psuedo Code that is able to take a string as input and detect if its a palindrome

def is_palindrome(input_string): return input_string == input_string[::-1]

input_string = input("Enter a string: ")

if is_palindrome(input_string) == True: print(f"{input_string} is a palindrome.") else: print(f"{input_string} is not a palindrome.")

2. Create a program that uses at least 1 of the algorithmic concepts covered in this notebook in a real-world application

def binary_search(arr, target): left = 0 right = len(arr) - 1 while left <= right: mid = (left + right) // 2 mid_value = arr[mid if mid_value == target: return mid elif mid_value < target: left = mid + 1 else: right = mid - 1 return -1

arr = [1, 3, 5, 7, 9, 11, 13] target = 1 result = binary_search(arr, target) if result != -1: print(f"Element {target} found at index {result}") else: print(f"Element {target} not found in the array")

Flying-Book commented 1 year ago
test_scores = [100, 96, 83, 82, 85, 85, 83, 22, 56, 63]
test_scores = sorted(test_scores)
length = len(test_scores)

if length % 2 == 0:
    median = (test_scores[length // 2] + test_scores[length // 2 - 1])/2
else:
    median = test_scores[length // 2]
print(int(median))
import random
ran_num = random.randint(1, 100)
def how_much_off(num):
    print(abs(num-ran_num))
how_much_off(30)
DavidL0914 commented 1 year ago
  1. def find_median(grades):

    Sort the grades

    sorted_grades = sorted(grades)

    Find the middle index

    middle_index = len(sorted_grades) // 2

    Check if the number of grades is even

    if len(sorted_grades) % 2 == 0:

    Average the two middle values for even-sized lists

    median = (sorted_grades[middle_index - 1] + sorted_grades[middle_index]) / 2

    else:

    Take the middle value for odd-sized lists

    median = sorted_grades[middle_index]

    return median

List of test grades

test_grades = [85, 92, 78, 90, 88, 76, 94, 89, 87, 91]

Calculate the median using the algorithm

median_grade = find_median(test_grades)

Print the median test grade

print("Median test grade:", median_grade)

  1. import random

Generate a random number between 1 and 100

secret_number = random.randint(1, 100)

attempts = 0

while True:

Get the player's guess

guess = int(input("Guess the secret number (between 1 and 100): "))
attempts += 1

if guess < secret_number:
    print("Try a higher number.")
elif guess > secret_number:
    print("Try a lower number.")
else:
    print(f"Congratulations! You guessed the secret number {secret_number} in {attempts} attempts.")
    break
abby-albert commented 1 year ago

1

def find_median(test_grades):

Sort the grades in ascending order

sorted_grades = sorted(test_grades)

n = len(sorted_grades)

Check if the number of grades is odd or even

if n % 2 == 1:

If the number of grades is odd, return the middle value

median = sorted_grades[n // 2]

else:

If the number of grades is even, return the average of the two middle values

middle1 = sorted_grades[n // 2 - 1]
middle2 = sorted_grades[n // 2]
median = (middle1 + middle2) / 2

return median List of test grades test_grades = [85, 92, 78, 90, 88, 76, 84, 89, 95, 91]

Calculate the median median_grade = find_median(test_grades)

print(f"The median test grade is: {median_grade}")

2

import random

Generate a random number between 1 and 100 secret_number = random.randint(1, 100)

attempts = 0

while True:

Get the player's guess

guess = int(input("Guess the secret number (between 1 and 100): ")) attempts += 1

if guess < secret_number: print("Try a higher number.") elif guess > secret_number: print("Try a lower number.") else: print(f"Congratulations! You guessed the secret number {secret_number} in {attempts} attempts.") break

parkib commented 1 year ago

Q1:

grades = [] while True: grade = input("Enter a test grade (or 'done' to finish): ") if grade.lower() == 'done': break else: grades.append(float(grade))

grades.sort()

n = len(grades) if n % 2 == 0: median = (grades[n // 2 - 1] + grades[n // 2]) / 2 else: median = grades[n // 2]

print(f"The median test grade is: {median}")

Q2: import random

List of words for the game

words = ["python", "banana", "tiger", "elephant", "computer", "guitar", "pizza"]

Select a random word from the list

word_to_guess = random.choice(words)

Create a list to store guessed letters

guessedletters = [""] * len(word_to_guess)

print("Welcome to the Word Guessing Game!")

while "_" in guessed_letters:

Display the current state of the word

print(" ".join(guessed_letters))

# Ask the player to guess a letter
guess = input("Guess a letter: ").lower()

if len(guess) != 1 or not guess.isalpha():
    print("Please enter a single letter.")
    continue

if guess in word_to_guess:
    # Update guessed_letters with the correct guesses
    for i in range(len(word_to_guess)):
        if word_to_guess[i] == guess:
            guessed_letters[i] = guess
else:
    print("Incorrect guess. Try again.")

print(f"Congratulations! You guessed the word: {word_to_guess}")

SOoctosnake commented 1 year ago

https://sooctosnake.github.io/student_october//2023/10/12/developing_algorthms.html

vidhaganji commented 1 year ago

1)

List of test grades

test_grades = [85, 92, 78, 90, 88, 76, 89, 94, 81, 87]

Sort the list in ascending order

test_grades.sort()

Calculate the median

n = len(test_grades) if n % 2 == 0:

If the number of grades is even, take the average of the two middle values

median = (test_grades[n // 2 - 1] + test_grades[n // 2]) / 2

else:

If the number of grades is odd, the median is the middle value

median = test_grades[n // 2]

print(f"The median test grade is: {median}")

2)

import random

Generate a random number between 1 and 100

secret_number = random.randint(1, 100)

attempts = 0

while True: guess = int(input("Guess the secret number (between 1 and 100): ")) attempts += 1

if guess < secret_number:
    print("Higher! Try again.")
elif guess > secret_number:
    print("Lower! Try again.")
else:
    print(f"Congratulations! You guessed the secret number {secret_number} in {attempts} attempts.")
    break
vibha-yganji commented 1 year ago

1)

List of test grades

test_grades = [85, 92, 78, 90, 88, 76, 89, 94, 81, 87]

Sort the list in ascending order

test_grades.sort()

Calculate the median

n = len(test_grades) if n % 2 == 0:

If the number of grades is even, take the average of the two middle values

median = (test_grades[n // 2 - 1] + test_grades[n // 2]) / 2

else:

If the number of grades is odd, the median is the middle value

median = test_grades[n // 2]

print(f"The median test grade is: {median}")

2)

import random

Generate a random number between 1 and 100

secret_number = random.randint(1, 100)

attempts = 0

while True: guess = int(input("Guess the secret number (between 1 and 100): ")) attempts += 1

if guess < secret_number:
    print("Higher! Try again.")
elif guess > secret_number:
    print("Lower! Try again.")
else:
    print(f"Congratulations! You guessed the secret number {secret_number} in {attempts} attempts.")
    break
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}")