r/pythonhomeworkhelp • • Mar 24 '21

Random number into list

3 Upvotes

Hello... I am stuck on an assignment:

"Generate a two-column and 21-row file with random values using file operation and the random method

Example:

Name0 0.8100797727702638

Name1 0.8876938145132516

Name2 0.3928158570421808

Name3 0.7483429697454923

...etc until 20

  • Read in the file, output the two columns in ascending order of the random values

  • Identify the minimum value, maximum value, median, and the average of these values."

What I have so far:


r/pythonhomeworkhelp • • Dec 07 '23

Psychopy homework

2 Upvotes

Does anyone know psychopy??


r/pythonhomeworkhelp • • Nov 14 '23

ZZZ Code AI | Support this website

2 Upvotes

r/pythonhomeworkhelp • • Jun 22 '23

Python water bill calculator assignemnt

2 Upvotes

Hey guys I am working on my Computer science project and I am stuck. Here is my code, how do I fix the errors listed on the bottom
import tkinter as tk
from tkinter import messagebox
# Create the main window
window = tk.Tk()
window.title("Water Bill Calculator")
# Customer Information Box
customer_info_frame = tk.LabelFrame(window, text="Customer Information")
customer_info_frame.grid(row=0, column=0, padx=10, pady=10, sticky="w")
# Labels and Entry Fields for Customer Information
labels = ["Name:", "Address:", "City:", "Province:", "ZIP Code:"]
entries = []
for i, label_text in enumerate(labels):
label = tk.Label(customer_info_frame, text=label_text)
label.grid(row=i, column=0, sticky="e")
entry = tk.Entry(customer_info_frame, width=30)
entry.grid(row=i, column=1, padx=5)
entries.append(entry)
entries[2].insert(0, "Midland") # Prefill City field with "Midland"
entries[3].insert(0, "Ontario") # Prefill Province field with "Ontario"
entries[4].insert(0, "L4R") # Prefill ZIP Code field with "L4R"
# Water Usage Box
water_usage_frame = tk.LabelFrame(window, text="Water Usage")
water_usage_frame.grid(row=0, column=1, padx=10, pady=10, sticky="w")
# Labels and Entry Fields for Water Usage
water_usage_labels = ["Last Meter Read:", "Current Meter Read:", "Litres Used:"]
water_usage_entries = []
for i, label_text in enumerate(water_usage_labels):
label = tk.Label(water_usage_frame, text=label_text)
label.grid(row=i, column=0, sticky="e")
entry = tk.Entry(water_usage_frame, width=10)
entry.grid(row=i, column=1, padx=5)
water_usage_entries.append(entry)
# Sewer Usage Box
sewer_usage_frame = tk.LabelFrame(window, text="Sewer Usage")
sewer_usage_frame.grid(row=0, column=2, padx=10, pady=10, sticky="w")
# Labels and Entry Fields for Sewer Usage
sewer_usage_labels = ["Litres Used:", "Discount Amount:", "Billable Amount:"]
sewer_usage_entries = []
for i, label_text in enumerate(sewer_usage_labels):
label = tk.Label(sewer_usage_frame, text=label_text)
label.grid(row=i, column=0, sticky="e")
entry = tk.Entry(sewer_usage_frame, width=10, state="readonly")
entry.grid(row=i, column=1, padx=5)
sewer_usage_entries.append(entry)
# Bill Summary Box
bill_summary_frame = tk.LabelFrame(window, text="Water Charges")
bill_summary_frame.grid(row=1, column=1, padx=10, pady=10, sticky="w")
# Labels and Entry Fields for Bill Summary
bill_summary_labels = ["Water Usage:", "Water Rate:", "Service Charge:", "Total:"]
bill_summary_entries = []
for i, label_text in enumerate(bill_summary_labels):
label = tk.Label(bill_summary_frame, text=label_text)
label.grid(row=i, column=0, sticky="e")
entry = tk.Entry(bill_summary_frame, width=10, state="readonly")
entry.grid(row=i, column=1, padx=5)
bill_summary_entries.append(entry)
# Sewer Charges Box
sewer_charges_frame = tk.LabelFrame(window, text="Sewer Charges")
sewer_charges_frame.grid(row=1, column=2, padx=10, pady=10, sticky="w")
# Labels and Entry Fields for Sewer Charges
sewer_charges_labels = ["Sewer Usage:", "Sewer Rate:", "Service Charge:", "Total:"]
sewer_charges_entries = []
for i, label_text in enumerate(sewer_charges_labels):
label = tk.Label(sewer_charges_frame, text=label_text)
label.grid(row=i, column=0, sticky="e")
entry = tk.Entry(sewer_charges_frame, width=10, state="readonly")
entry.grid(row=i, column=1, padx=5)
sewer_charges_entries.append(entry)
# Grand Total
grand_total_label = tk.Label(window, text="Grand Total:")
grand_total_label.grid(row=2, column=1, padx=10, pady=10, sticky="e")
grand_total_entry = tk.Entry(window, width=10, state="readonly")
grand_total_entry.grid(row=2, column=2, padx=5)
# Service Type
service_var = tk.StringVar(value=None) # Set initial value to None
service_type_frame = tk.LabelFrame(window, text="Service Type")
service_type_frame.grid(row=1, column=0, padx=10, pady=10, sticky="w")
water_only_radio = tk.Radiobutton(service_type_frame, text="Water only", variable=service_var, value="water")
water_only_radio.grid(row=0, column=0, padx=5, pady=2)
water_sewage_radio = tk.Radiobutton(service_type_frame, text="Water and Sewage", variable=service_var, value="water_sewer")
water_sewage_radio.grid(row=1, column=0, padx=5, pady=2)
def clear_service_type():
service_var.set("")
# Exit Button
def exit_program():
window.destroy()
exit_button = tk.Button(window, text="Exit", command=exit_program)
exit_button.grid(row=3, column=2, padx=5, pady=10, sticky="e")
# Reset Form Button
def reset_form():
clear_service_type()
for entry in entries:
entry.delete(0, tk.END)
entries[2].insert(0, "Midland") # Prefill City field with "Midland"
entries[3].insert(0, "Ontario") # Prefill Province field with "Ontario"
entries[4].insert(0, "L4R") # Prefill ZIP Code field with "L4R"
for water_entry in water_usage_entries:
water_entry.delete(0, tk.END)
for sewer_entry in sewer_usage_entries:
sewer_entry.delete(0, tk.END)
for bill_entry in bill_summary_entries:
bill_entry.delete(0, tk.END)
for water_charges_entry in water_charges_entries:
water_charges_entry.delete(0, tk.END)
for sewer_charges_entry in sewer_charges_entries:
sewer_charges_entry.delete(0, tk.END)
grand_total_entry.configure(state="normal")
grand_total_entry.delete(0, tk.END)
grand_total_entry.configure(state="readonly")
reset_button = tk.Button(window, text="Reset Form", command=reset_form)
reset_button.grid(row=3, column=1, pady=5)
# Calculate Button
def calculate_bill():
# Check if all required fields are filled
for entry in entries:
if entry.get().strip() == "":
messagebox.showerror("Error", "Please fill in all customer information fields.")
entry.focus()
return
if water_usage_entries[0].get().strip() == "" or water_usage_entries[1].get().strip() == "":
messagebox.showerror("Error", "Please enter both last meter read and current meter read.")
water_usage_entries[0].focus()
return
# Check if current meter reading is greater than previous meter reading
last_meter_read = int(water_usage_entries[0].get())
current_meter_read = int(water_usage_entries[1].get())
if current_meter_read <= last_meter_read:
messagebox.showerror("Error", "Current meter reading must be greater than previous meter reading.")
water_usage_entries[0].delete(0, tk.END)
water_usage_entries[1].delete(0, tk.END)
water_usage_entries[0].focus()
return
# Calculate Litres Used
litres_used = current_meter_read - last_meter_read
if service_var.get() == "Water only":
# Calculate Water charges
water_usage_entries[2].configure(state="normal")
water_usage_entries[2].delete(0, tk.END)
water_usage_entries[2].insert(0, litres_used)
water_usage_entries[2].configure(state="readonly")
if litres_used <= 10000:
water_rate = 3.50
elif litres_used <= 20000:
water_rate = 3.25
elif litres_used <= 50000:
water_rate = 3.05
else:
water_rate = 2.90
if litres_used <= 50000:
water_service_charge = 7.50
else:
water_service_charge = 6.50
water_total = (litres_used / 1000) * water_rate + water_service_charge
# Calculate Sewer charges
sewer_usage_entries[0].configure(state="normal")
sewer_usage_entries[0].delete(0, tk.END)
sewer_usage_entries[0].insert(0, 0)
sewer_usage_entries[0].configure(state="readonly")
sewer_rate = 0
sewer_service_charge = 0
sewer_total = 0
else:
# Calculate Water charges
water_usage_entries[2].configure(state="normal")
water_usage_entries[2].delete(0, tk.END)
water_usage_entries[2].insert(0, litres_used)
water_usage_entries[2].configure(state="readonly")
if litres_used <= 10000:
water_rate = 3.50
elif litres_used <= 20000:
water_rate = 3.25
elif litres_used <= 50000:
water_rate = 3.05
else:
water_rate = 2.90
if litres_used <= 50000:
water_service_charge = 6.50
else:
water_service_charge = 5.50
water_total = (litres_used / 1000) * water_rate + water_service_charge
# Calculate Sewer charges
sewer_usage_entries[0].configure(state="normal")
sewer_usage_entries[0].delete(0, tk.END)
sewer_usage_entries[0].insert(0, litres_used)
sewer_usage_entries[0].configure(state="readonly")
discount_amount = litres_used * 0.025
billable_amount = litres_used - discount_amount
sewer_usage_entries[1].configure(state="normal")
sewer_usage_entries[1].delete(0, tk.END)
sewer_usage_entries[1].insert(0, discount_amount)
sewer_usage_entries[1].configure(state="readonly")
sewer_usage_entries[2].configure(state="normal")
sewer_usage_entries[2].delete(0, tk.END)
sewer_usage_entries[2].insert(0, billable_amount)
sewer_usage_entries[2].configure(state="readonly")
if billable_amount <= 50000:
sewer_rate = 1.25
sewer_service_charge = 12.50
else:
sewer_rate = 1.15
sewer_service_charge = 10.50
sewer_total = (billable_amount / 1000) * sewer_rate + sewer_service_charge
# Update Bill Summary
bill_summary_entries[0].configure(state="normal")
bill_summary_entries[0].delete(0, tk.END)
bill_summary_entries[0].insert(0, litres_used)
bill_summary_entries[0].configure(state="readonly")
bill_summary_entries[1].configure(state="normal")
bill_summary_entries[1].delete(0, tk.END)
bill_summary_entries[1].insert(0, water_rate)
bill_summary_entries[1].configure(state="readonly")
bill_summary_entries[2].configure(state="normal")
bill_summary_entries[2].delete(0, tk.END)
bill_summary_entries[2].insert(0, water_service_charge)
bill_summary_entries[2].configure(state="readonly")
water_total = round(water_total, 2)
bill_summary_entries[3].configure(state="normal")
bill_summary_entries[3].delete(0, tk.END)
bill_summary_entries[3].insert(0, water_total)
bill_summary_entries[3].configure(state="readonly")
# Update Sewer Charges
sewer_charges_entries[0].configure(state="normal")
sewer_charges_entries[0].delete(0, tk.END)
sewer_charges_entries[0].insert(0, billable_amount)
sewer_charges_entries[0].configure(state="readonly")
sewer_charges_entries[1].configure(state="normal")
sewer_charges_entries[1].delete(0, tk.END)
sewer_charges_entries[1].insert(0, sewer_rate)
sewer_charges_entries[1].configure(state="readonly")
sewer_charges_entries[2].configure(state="normal")
sewer_charges_entries[2].delete(0, tk.END)
sewer_charges_entries[2].insert(0, sewer_service_charge)
sewer_charges_entries[2].configure(state="readonly")
sewer_total = round(sewer_total, 2)
sewer_charges_entries[3].configure(state="normal")
sewer_charges_entries[3].delete(0, tk.END)
sewer_charges_entries[3].insert(0, sewer_total)
sewer_charges_entries[3].configure(state="readonly")
# Calculate Grand Total
grand_total = water_total + sewer_total
grand_total_entry.configure(state="normal")
grand_total_entry.delete(0, tk.END)
grand_total_entry.insert(0, grand_total)
grand_total_entry.configure(state="readonly")
# Calculate Button
calculate_button = tk.Button(window, text="Calculate Bill", command=calculate_bill)
calculate_button.grid(row=3, column=0, padx=5, pady=10)
# Start the main loop
window.mainloop()
There is errors like when the program starts the service type buttons are both selected for some reason and also the line in water usage called litres used for some reason allows the user to input information but when calculate bill button is pressed it does what it is supposed to do which is subtract the current meter reading from the previous meter reading, so that input field should be unavailable for the user to put anything in there. Also the reset button does not work as it should. When reset is pressed it only clears the customer information box and the meter readings not clearing out any of the rest of the lines and does not clear the service type buttons. Please help


r/pythonhomeworkhelp • • May 04 '22

Help plz does anyone know hot to do this

Thumbnail
gallery
2 Upvotes

r/pythonhomeworkhelp • • Jan 20 '22

Intro Python assistance please!

2 Upvotes

Hi everyone,

I am having difficulty correcting the syntax error in my code below. I am specifically having difficulties with the last two lines of the code it seems. Ideas on how to correct my code? Any help of any kind would be helpful, even an explanation, I am in my first comp sci class in uni this semester! Question wanted output: "Enter integer: 4

You entered: 4

4 squared is 16

And 4 cubed is 64 !!

Enter another integer: 5 4 + 5 is 9

4 * 5 is 20"

My code:

user_num = int(input('Enter integer:\n'))

print('You entered', user_num)

print(user_num, 'squared is', user_num*user_num)

print('And', user_num, 'cubed is', user_num*user_num*user_num, '!!')

user_num2 = int(input('Enter another integer: /n')

print(str(user_num), '+', str(user_num2), "is", user_num + user_num2)

print(str(user_num), '*' ,str(user_num2), "is", user_num * user_num2)


r/pythonhomeworkhelp • • Jan 28 '26

My code is committing unalive.

1 Upvotes

Hi I came here for some help on my code. It's collider is WAY above the ground. Anyone know how to fix it?

from ursina import *

from random import randint

def update():

if held_keys\["a"\]:

	cube.position += cube.left \* time.dt \* 2

if held_keys\["d"\]:

	cube.position += cube.right \* time.dt \* 2



cube.v_speed += 25 \* time.dt



cube.y +=cube.v_speed \* time.dt



if cube.y < 0.5:

	cube.y = 0.5 \* 0.5

	cube.v_speed = 0



	if held_keys\["space"\]:

		cube.v_speed = 10

cube=Entity(model="cube", color=color.white, scale=2, collider="box")

ground=Entity(model="cube", scale=8, color=color.white, collider="box", position=(0, -7, 0))

cube.v_speed = 3

app=Ursina()

app.run()


r/pythonhomeworkhelp • • Jul 10 '25

I'm stuck banging my head against a wall with this "active contour" assignment

1 Upvotes

The goal of the assignment is as follows:
You are only allowed to use numpy and matplotlib libraries. You can only use OpenCV to apply the smoothing and sharpening.

  1. Implement an active contour that starts in a given location and it grows until it touches the edge of the shape.

  2. You can use the simplest version (moving each point in the contour independently).

  3. Extra points for those who use the combined energy model.

  4. Set the starting point inside each shape as marked in the example and make a short video showing the growing process for each shape (~2 seconds per shape). The result should be the contour that covers the perimeter of the shape.

(hahahaha easy he says)
To make your life easy: Define the starting point for your active contour using one set of x, y coordinates of the image. Based on those coordinates create four points (x-1, y), (x+1, y), (x, y-1), (x,y+1) and make them move away from x, y on each iteration until you find the gradient. Remember to measure the distance between points on each iteration to add a new point when the distance between two points is larger than a threshold.

The following is my current code. Basically my issue is that the contour fills the shape like light, so when it reaches a corner, it simply goes past the empty area and doesn't contour into it. Rather than like light, I need it to be like water, flowing into all parts of the shape. Looking at the solution video (the video I attached to the post) provided by the professor, I already know my method is entirely incorrect but I was hoping there would be a way to do it with my current code.

import numpy as np
import matplotlib.pyplot as plt
import cv2
from matplotlib.animation import FuncAnimation, FFMpegWriter

image = cv2.imread("image-1.png", cv2.IMREAD_GRAYSCALE)
image = cv2.GaussianBlur(image, (5, 5), 0)

imf = image.astype(float)
gy, gx = np.gradient(imf)
gradient_x, gradient_y = gx, gy
gradient = np.hypot(gx, gy)

def active_contour(center, threshold=20, step=1, distance_threshold=5, max_iter=300):
    offsets = [( 1,  1),(-1,  1),(-1, -1),( 1, -1)]
    points = [np.array([center[0] + dx, center[1] + dy], dtype=float) for dx, dy in offsets]
    static = [False]*4
    h, w = image.shape
    frames = []

    balloon = 0.5
    radial = 0.5
    alpha_int = 0.2

    for x in range(max_iter):
        frame = cv2.cvtColor((image/image.max()*255).astype(np.uint8), cv2.COLOR_GRAY2BGR)
        points_int = np.array(points, dtype=np.int32)
        cv2.polylines(frame, [points_int], isClosed=True, color=(255,0,0), thickness=2)
        frames.append(frame)

        new_points, new_static = [], []
        length = len(points)
        for i, p in enumerate(points):
            if static[i]:
                new_points.append(p)
                new_static.append(True)
                continue

            dir_vector = p - center
            n = np.linalg.norm(dir_vector) or 1
            dir_unit = dir_vector / n
            
            p2 = p + step * dir_unit
            p2[0] = np.clip(p2[0], 0, w-1)
            p2[1] = np.clip(p2[1], 0, h-1)
            if gradient[int(p2[1]), int(p2[0])] > threshold:
                new_points.append(p2)
                new_static.append(True)
            else:
                new_points.append(p2)
                new_static.append(False)
        
        for j in range(len(new_points)):
            if not new_static[j]:
                prev = new_points[j-1]
                _next = new_points[(j+1) % len(new_points)]
                new_points[j] += alpha_int * (((prev + _next)/2) - new_points[j])

        merged_points, merged_static = [], []
        length = len(new_points)
        for i in range(length):
            p1, s1 = new_points[i], new_static[i]
            p2, s2 = new_points[(i+1) % length], new_static[(i+1)% length]
            merged_points.append(p1) 
            merged_static.append(s1)
            if np.linalg.norm(p2-p1) > distance_threshold:
                merged_points.append((p1+p2)/2)
                merged_static.append(False)
        points, static = merged_points, merged_static
        if all(static):
            remaining = max_iter - x - 1
            if remaining > 0:
                frames.extend([frame] * remaining)
            break
    return frames

centers = [(150,200), (320,230), (620, 170)]
fps = 20
writer = FFMpegWriter(fps=fps)

for idx, c in enumerate(centers):
    frames = active_contour(np.array(c))
    h, w, _ = frames[0].shape
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter(f'active_contour_shape_{idx}.mp4', fourcc, fps, (w, h))
    for f in frames:
        out.write(f)
    out.release()

I have tried asking AI—not helpful to say the least—and using online resources but nothing I could find helped me with this.

I am not really looking for someone to necessarily fix my code for me, even if someone could provide me with a similar solution to this assignment like a link to a GitHub page or another website, just anything. I am literally losing my mind. Please help me 😭🙏


r/pythonhomeworkhelp • • Jun 09 '25

Creating a CSV readout from a Raspberry Pi sensor, have issues with timestamp

Post image
1 Upvotes

Hello,
I'm working on a school project where we're supposed to create temperature data and since we're already doing a similar project in another subject we thought we'd use the equipment there to help generate the data we need.

My partner has set up some basic code, but his version only created one line of data (temperature, relative humidity and a timestamp in POSIX format), which I've somewhat managed to fix by putting the calls into a "while" loop. However, the code doesn't seem to do two things:

  1. I want the process to only happen once in a while - I can't figure that part out, the "sleeptime" variable seems to do nothing.

  2. I want every call on the timestamp to reflect the current time, however, all my research into this using Python's documentation, some tutorials and Stackoverflow have lead me nowhere - I've somewhat managed to include a call for a fixed timestamp in a previous version of the code but I want the timestamp to be at the same time as the last readout.

Can anybody help me? Thanks in advance.


r/pythonhomeworkhelp • • Feb 08 '25

[beginner] Probably a dumb question but I'm stuck!!

Post image
1 Upvotes

Qn : FIND ONE TEST CASE THAT SATISFIES THE REQUIREMENTS OF INPUT (n>= 2), BUT THE CODE GIVES INCORRECT RESULT.

Preamble given: A prime number is a positive integer greater than 1, divisible only by 1 and itself. To check if a number p is prime, we only need to test divisibility up to the square root of p. The input n will always be a positive integer greater than or equal to 2.


r/pythonhomeworkhelp • • Nov 03 '24

mad libs help needed

1 Upvotes

I am super new to python so my code is an absolute mess. I'm trying to create a program that has 2 stories in it that a user can choose from. Then collects the words to input into the stories. Then it loops back and let's them do another if they'd like and it counts the number of stories they've created.

My link to the trinket I've made so far: https://trinket.io/python3/ba5c267d4262

My issues currently:

this endless loop - I think it's caused by what I've got in def main():

redirecting the user to inputting a correct answer if they put something other than y/n for the do you want to play the game portion

redirect the user to inputting a correct answer if they put something other than A or B for which story they want to do

having a properly function tracker for the story count


r/pythonhomeworkhelp • • Oct 07 '24

NEED HELP ASAPPPP

Thumbnail
gallery
1 Upvotes

i need help creating a code on this plsssssssssssssss


r/pythonhomeworkhelp • • Sep 27 '24

Counting Frequencies in Ciphertext

1 Upvotes
import matplotlib.pyplot as plt
import string

ciphertext = """ndgfq-radoq mffmow m ndgfq-radoq mffmow uzhaxhqe fdkuzs qhqdk baeeunxq wqk gzfux mz
                uzfqxxusunxq fdmzexmfuaz ar ftq oubtqdfqjf uzfa bxmuzfqjf ue anfmuzqp. az mhqdmsq tmxr
                ar mxx baeeunxq wqke ygef nq fduqp fa motuqhq egooqee. ftmf ue ur ftqdq mdq j purrqdqzf
                wqke az mhqdmsq mz mffmowqd iagxp pueoahqd ftq mofgmx wqk mrfqd tmxr fduqe me m rudef
                efqb ftq dqxmfuhq rdqcgqzok ar ftq xqffqde omz nq pqfqdyuzqp mzp oaybmdqp fa m efmzpmdp
                rdqcgqzok puefdungfuaz rad qzsxuet egot me ue etaiz uz ur ftq yqeemsq iqdq xazs qzagst, ftue
                fqotzucgq mxazq yustf nq egrruouqzf ngf nqomgeq ftue ue m dqxmfuhqxk etadf yqeemsq iq omzzaf
                qjbqof mz qjmof ymfot uz mzk omeq ftq dqxmfuhq rdqcgqzouqe ar ftq xqffqde uz ftq oubtqdfqjf (uz
                bqdoqzfmsqe) mdq me raxxaie ftqdq mdq m zgynqd ar imke fa bdaoqqp mf ftue bauzf. iq oagxp
                ymwq eayq fqzfmfuhq meeuszyqzfe mzp efmdf fa ruxx uz ftq bxmuzfqjf fa eqq ur uf xaawe xuwq
                m dqmeazmnxq ewqxqfaz ar m yqeemsq. m yadq ekefqymfuo mbbdamot ue fa xaaw rad aftqd
                dqsgxmdufuqe. rad qjmybxq oqdfmuz iadpe ymk nq wzaiz fa nq uz ftq fqjf. ad iq oagxp xaaw rad
                dqbqmfuzs eqcgqzoqe ar oubtqd xqffqde mzp fdk fa pqpgoq ftqud bxmuzfqjf qcguhmxqzfe."""
frequency_dict = {letter: 0 for letter in string.ascii_lowercase}
print(frequency_dict)

clean_ciphertext = ''.join([char.lower() for char in ciphertext if char.isalpha()])
#print(join_ciphertext)
for letter in clean_ciphertext:
    if letter in frequency_dict:
        frequency_dict[letter] += 1
sorted_frequencies = dict(sorted(frequency_dict.items()))

plt.figure(figsize=(10, 6))
plt.bar(sorted_frequencies.keys(), sorted_frequencies.values(), color='blue')
plt.title("Letter Frequency Analysis of Ciphertext")
plt.xlabel("Letters")
plt.ylabel("Frequency")
plt.show()

print("Frequency table:")
for letter, frequency in sorted_frequencies.items():
    print(f"{letter}: {frequency}")

I'm working on an assignment to document the frequencies of every letter in a given ciphertext. I know it's sloppy and I was hoping for any suggestions to clean it up. Also, in a few lines I have warnings for 'Incorrect Type' and I don't know how to fix them. The program still runs even with these errors. The incorrect type errors are in the for letter loop in frequency_dict[letter] being letter and plt.bar 'sorted_frequencies.values()'

EDIT: In frequency_dict[letter] += 1 the letter has the error. "Expected 'LiteralString' (matched generic type '_KT'), got 'str' instead.


r/pythonhomeworkhelp • • Aug 20 '24

Error "Golf() takes no arguments" on line 22

1 Upvotes

This is exactly how the professor laid out the answer sheet for this assignment, however, I get the error in the title when the code goes to line 22 "hole1 = Golf(1, score, 3)"

I've looked through all of our readings and compared them to the example and to me it looks the same, but I seem to be missing something. Any help is much appreciated!

class Golf:

'Golf scoring class'

results = " "

def __innit__(self, hole, score, par):

self.hole = hole

self.par = par

def evaluate_and_display_score(self, hole, score):

if (score > self.par):

Golf.results = "Over Par"

elif (score < self.par):

Golf.results = "Under Par"

else:

Golf.results = "At Par"

print("You scored", Golf.results, "on hole #" , hole , "with a par of" , self.par)

score = 0

hole1 = Golf(1, score, 3)

hole2 = Golf(2, score, 4)

hole3 = Golf(3, score, 5)

enter_hole = int(input("Enter the hole number: "))

score = int(input("Enter your score: "))

if enter_hole == 1:

hole1.evaluate_and_display_score(enter_hole , score)

if enter_hole == 2:

hole2.evaluate_and_display_score(enter_hole , score)

if enter_hole == 3:

hole3.evaluate_and_display_score(enter_hole , score)


r/pythonhomeworkhelp • • May 22 '24

I've been stuck here for 3 days now

1 Upvotes
def main():
    plate = input("Plate: ").upper()
    if is_valid(plate):
        print("Valid")
    else:
        print("Invalid")


def is_valid(s):
    let= ["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"]
    num= ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
    ban= ["`","~","!","@","#","$","%","^","&","*","(",")","_","-","+","=","{","[","}","]","|","'",":",";","<",",",">",".","?","/","}"]
    if len(s) <= 6 and len(s) >= 2:
        res = [ele for ele in let if (ele in s)]
        if res == True:
            x = [ele for ele in num if (ele in s)]
            return x
#has to start with 2 letters
#cant have wierd characters, just numbers and letters
#numbers must be at the end, not middle
#first number cant be a 0
#between 6 and 2 characters

main()

I am getting nothing but "invalid" when I run this code. no matter what I try as code after checking if there's letters in my input.

if I cut out everything after "if res == True" I can get "valid" but if I put anything other than "return res" there I cant get any "valid" outputs and I cant figure out why.

it also only returns "invalid" if I ask it to return the opposite of what "res" is. "if res == True: return False". so I cant ask it to hand over an "invalid" if anything on the "ban" list is there because it will always output "invalid" anyway.

I assume its a syntax issue. but I cant work out where my typo is. part of the problem is that my GitHub repository doesn't see anything wrong here.

and while I'm asking for help I cant find the functions/commands for the placement requirements or "if 0 is the first number" problem either. any ideas on those?


r/pythonhomeworkhelp • • May 20 '24

Got CS Summer Classes? Get Help from Experienced CS tutors!

Post image
1 Upvotes

r/pythonhomeworkhelp • • May 08 '24

Why isn't the calendar coming up or my image working?

1 Upvotes
import tkinter as tk
from tkinter import ttk
import datetime
from tkinter import PhotoImage


def save_date():
    selected_date = cal.get_date()
    saved_dates.append(selected_date)
    saved_dates_label.config(text=", ".join(saved_dates))

def open_calendar_window():
    calendar_window = tk.Toplevel(root)
    calendar_window.title("Calendar")
    cal = Calendar(calendar_window, selectmode="day", date_pattern="yyyy-mm-dd")
    cal.pack(fill="both", expand=True)

root = tk.Tk()
root.title("Calendar with Image")

# Load the image
image_path = "bee.jpeg"
beeImage = Image.open(image_path)
image = image.resize((200, 200), Image.ANTIALIAS)  # Used to size image
tk_image = ImageTk.PhotoImage(image)

# Display the image
image_label = tk.Label(root, image=tk_image)
image_label.grid(row=0, column=1, sticky="ne")

# Open calendar window button
open_calendar_btn = tk.Button(root, text="Open Calendar", command=open_calendar_window)
open_calendar_btn.grid(row=1, column=0, columnspan=2, pady=10)

# Second window for saving dates
saved_dates = []
saved_dates_window = tk.Toplevel(root)
saved_dates_window.title("Saved Dates")
saved_dates_label = tk.Label(saved_dates_window, text="")
saved_dates_label.pack()

# Create a calendar widget
cal = Calendar(root, selectmode="day", date_pattern="yyyy-mm-dd")
cal.grid(row=0, column=0, padx=10, pady=10)

# Button to save selected date
save_btn = tk.Button(root, text="Save Date", command=save_date)
save_btn.grid(row=1, column=0, padx=10, pady=10)

root.mainloop()

r/pythonhomeworkhelp • • Apr 10 '24

How do I calculate the Big O runtime for this given function

1 Upvotes

def mystery_v2(lst: list[str]) -> str:
answer = ’ ’
i = 0
done = False
while not done:
next_list = []
done = True
for s in lst:
if i < len(s):
answer += s[i]
done = False
next_list.append(s)
i += 1
lst = next_list
return answer

Scenario: A list with n strings (n > 0), all of length 5, except for one string of length m (m > 5).
For this scenario, what is the Big-Oh runtime of v2 in terms of n and m?


r/pythonhomeworkhelp • • Mar 29 '24

how do you fix this runtime problem

1 Upvotes

hey yall, i got a problem with runtime error for my python homework. it outputs the right answer but the submission website gives me a runtime error every time. This is the simplest form i can go, given that i just started pythoning like 4 weeks ago. can somebody help me optimize this bullcrap i am losing my mind.

number = int(input())
completion_list = list(map(int, input().split(',')))
ddl_list = list(map(int, input().split(',')))
seq_list = list(map(int, input().split(',')))

og_seq = seq_list
min_delay = float('inf')

while True:
    new_seq = [og_seq[:i] + og_seq[i + 1:i + 2] + og_seq[i:i + 1] + og_seq[i + 2:] for i in range(len(og_seq) - 1)]
    new_seq.append(og_seq)
    new_seq.append(og_seq[-1:] + og_seq[1:-1] + og_seq[:1])

    min_delay_time = min_delay

    for sequence in new_seq:
        total_completion_time = 0
        total_delay_time = 0
        for job in sequence:
            if 1 <= job <= number:
                total_completion_time += completion_list[job - 1]
                deadline = ddl_list[job - 1]
                delay = max(0, total_completion_time - deadline)
                total_delay_time += delay

        if total_delay_time <= min_delay_time:
            min_delay_time = total_delay_time
            s_star = sequence

    if min_delay_time == min_delay:
        break
    else:
        og_seq = s_star
        min_delay = min_delay_time

best_seq = ','.join(map(str, s_star))
print(best_seq, min_delay_time, sep=';')

sample input:
4
5, 8, 6, 3
5, 12, 13, 10
3, 2, 4, 1
sample output:
1, 4, 3, 2; 11

idk if i need to give context for this hw question since my code is giving me the right output i just cant optimize this chunka text any more than this with my meager 4 weeks worth of python knowledge


r/pythonhomeworkhelp • • Mar 16 '24

Endless While Loop

1 Upvotes

I am building a program using Quadtree and when adding user inputted values into a 2D array I seem to have created an infinite while loop, however, I haven't been able to find where my error lies. Thanks for any help provided.

def quadTree():
  size = int(input(print("Enter a size: "))) #size will be 8
  box = [[] for i in range(size)] 

  while(len(box) < 9):
    entry = input(print("Enter 0 or 1 for colors: ")) #EX: 00000000, 11111111, or 10101010
    for i in range(size):
      for j in range(size):
        box[i].append(entry)
  print(box)



quadTree()

r/pythonhomeworkhelp • • Feb 24 '24

bowling game trouble

1 Upvotes

my cs class is making a bowling game with pyside6 and the logic for scoring is really getting me…

it’s a classic ten frame bowling game, i created all the frames with a loop so i wasn’t sure how to access individual frames. i am having an issue with the strike and spare logic because i don’t know how to access the next throw and add that to the last turns score…

any advice welcome ! (i have the files for anyone who might need to see)


r/pythonhomeworkhelp • • Feb 14 '24

8 puzzle problem assignment

1 Upvotes

I have an assingment about solving the 8 puzzle problem and the prof was not clear at all with expectations and i really need assistance ive been trying to figure it out myself but i need extra help and the prof isnt useful. Can someone hop on a zoom call or discord to help me out?