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 • • Nov 16 '23

Bag of Dice project with classes

1 Upvotes

My main Problem is how Exactly my professor wants me to do the second class. From my knowledge you cant create a list within a class, I know you can make a child class but it hasn't really worked well with making dice. I just started coding a couple of months ago so this might seem simple. so any tips would be apricated.

His instructions were:

In this project, you will be creating a bag of dice that will be used in your final project.

First things first, you need to import random into your file.

Use the Die class from Programming Concepts 10. There's no need to code this again.

Normally we would import this, but for simplicity, just copy/paste the Die class here.

Your DiceBag class should contain the following members and methods.

A list of Die objects.

A singleRoll method that selects a die by its number of sides via input. If the die exists, roll it and return the result. If not, return -1.

A multiRoll method that takes a number of sides to select and number of times to roll and returns the sum of the rolls. If the selected die doesn't exist, return -1.

Once you've got both your classes present and accounted for, write some test code. Create a list of Die objects.

You should have a 4, 6, 10, 20, 50, and 100 sided die. Creat a DiceBag object containing this list of dice.

Call the singleRoll and multiRoll functions a few times and print the results to verify that it works.

The concepts 10 code is:

import random

class Die:

def __init__(self, sides):

self.sides = sides

self.value = 1

def roll(self):

self.value = random.randrange(1,self.sides+1)

return self.value

newDie = Die(20)

print(newDie.roll())


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 • • Aug 14 '23

The Ultimate 9 Commands And Concepts in Python.

Thumbnail
elevatepython.com
1 Upvotes

r/pythonhomeworkhelp • • Jul 26 '23

Verifying the presence of a value in a list - Python.

Thumbnail
elevatepython.com
1 Upvotes

r/pythonhomeworkhelp • • Dec 10 '23

Trouble converting while and for loops to functions

1 Upvotes

I am making an app that takes what info you were given about an element, and returns all the essential information. I am trying to integrate the idea into tkinter, but I cant get my loops to convert to functions, and I dont get how to change the text in the gui to display the results.

I have tried converting the loops a few times, but they dont convert.

below if my code, its still in progress

from tkinter import *

from periodicTable import elements

#RELIC

givenInfo = input("please enter an the information you were given about the element, and I will enter the info for it:") #prompt for what they were provided

#RELIC

#if else route to designate each entry of givenInfo as str, int, or float

if givenInfo.isdigit():

givenInfo = int(givenInfo)

elif givenInfo.replace('.', '', 1).isdigit():

givenInfo = float(givenInfo)

else:

givenInfo = givenInfo.capitalize()

#The proper designations for the data, for the start, it is all empty

name = ""

symbol = ""

atomNum = 0

atomMass = 0

#Loop to run through elements dictionry and make list of the values there

result = [] #List needed

for element, element_dict in elements.items(): #for (new variable made in for loop), () in (dictionary elements, but .items() designates just the values)

if (givenInfo in element_dict):

result = list(element_dict)

break

#RELIC

print(givenInfo)

#print(result)

#RELIC

#Loop to assign each value to its proper designation

i=0

while i < len(result):

if type(result[i]) is int:

atomNum = result[i]

print("The atomic number is:", atomNum)

i+=1

elif type(result[i]) is float:

atomMass = result[i]

print("The atomic mass is:", atomMass)

i+=1

elif type(result[i]) is str and len(result[i]) > 2:

name = result[i]

print("The element name:", name)

i+=1

elif type(result[i]) is str and len(result[i]) <= 2:

symbol = result[i]

print("The symbol for the element:", symbol)

i+=1

else:

print(type(result[i]))

i+=1

#______________________________________________________________Margin from main program engine______________________________________________________________#

root = Tk()

#myText=givenInfo;

firstframe = Frame(root)

firstframe.pack()

secondframe= Frame(root)

secondframe.pack( side = BOTTOM )

#Text label prompt for what user was provided in the problem label in row 0

Label(firstframe, text='What were you provded for the element?').grid(row=0)

#Result1 label in row 1

Label(firstframe, text=f"{'The symbol for the element is: '+ symbol}").grid(row=1) #this line prints the result as needed

#Result2 label in row 2

Label(firstframe, text='result2 this might be the atomic number').grid(row=2)

#Result3 label in row 3

Label(firstframe, text='result3 this might be the atomic mass').grid(row=3)

#Result4 label in row 4

Label(firstframe, text='The atomic number is:').grid(row=4)

#entry field

entry = Entry(firstframe)

#place it next to "what were you given"

entry.grid(row=0, column=1)

#answer label adjacent to label Result , so row 2 column 1

Label(firstframe,text="",textvariable=givenInfo).grid(row=2,column=1)

#creating a search button. Clicking the button should initiate the search through the dictionary.

#command attribute is for on click event.

searchButton = Button(secondframe, text ='Search')

searchButton.pack()

#creating a new button, should clear the results when clicked.

clearButton = Button(secondframe, text ='Clear')

clearButton.pack()

#creating a new window to search another element with

newWindowButton = Button(secondframe, text="New Window", command=root.mainloop)

newWindowButton.pack()

#creating a Celsius to Exit button. root.destroy will exit the window

exitbutton = Button(secondframe, text ='Exit', fg ='red', command=root.destroy)

exitbutton.pack()

root.mainloop()

the loops i am trying to convert right now are:

#Loop to assign each value to its proper designation

i=0

while i < len(result):

if type(result[i]) is int:

atomNum = result[i]

print("The atomic number is:", atomNum)

i+=1

elif type(result[i]) is float:

atomMass = result[i]

print("The atomic mass is:", atomMass)

i+=1

elif type(result[i]) is str and len(result[i]) > 2:

name = result[i]

print("The element name:", name)

i+=1

elif type(result[i]) is str and len(result[i]) <= 2:

symbol = result[i]

print("The symbol for the element:", symbol)

i+=1

else:

print(type(result[i]))

i+=1

and:

#Loop to run through elements dictionry and make list of the values there

result = [] #List needed

for element, element_dict in elements.items(): #for (new variable made in for loop), () in (dictionary elements, but .items() designates just the values)

if (givenInfo in element_dict):

result = list(element_dict)

break

i would really appreciate the help.


r/pythonhomeworkhelp • • Jul 28 '23

The Best Python IDE for Windows

Thumbnail
elevatepython.com
1 Upvotes

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 • • Jul 19 '23

ElevatePython - Visit Today >> Learn Python, From Zero to Hero!

Post image
1 Upvotes

r/pythonhomeworkhelp • • Jul 19 '23

How to Use the “Pop” Command – Python

Thumbnail
elevatepython.com
1 Upvotes

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 • • 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 • • Aug 17 '23

A guide for beginners on how to open and read files in Python.

Thumbnail
elevatepython.com
1 Upvotes

r/pythonhomeworkhelp • • Nov 16 '23

Bag of Dice project with classes

1 Upvotes

My main Problem is how Exactly my professor wants me to do the second class. From my knowledge you cant create a list within a class, I know you can make a child class but it hasn't really worked well with making dice. I just started coding a couple of months ago so this might seem simple. so any tips would be apricated.

His instructions were:

In this project, you will be creating a bag of dice that will be used in your final project.

First things first, you need to import random into your file.

Use the Die class from Programming Concepts 10. There's no need to code this again.

Normally we would import this, but for simplicity, just copy/paste the Die class here.

Your DiceBag class should contain the following members and methods.

A list of Die objects.

A singleRoll method that selects a die by its number of sides via input. If the die exists, roll it and return the result. If not, return -1.

A multiRoll method that takes a number of sides to select and number of times to roll and returns the sum of the rolls. If the selected die doesn't exist, return -1.

Once you've got both your classes present and accounted for, write some test code. Create a list of Die objects.

You should have a 4, 6, 10, 20, 50, and 100 sided die. Creat a DiceBag object containing this list of dice.

Call the singleRoll and multiRoll functions a few times and print the results to verify that it works.

The concepts 10 code is:

import random

class Die:

def __init__(self, sides):

self.sides = sides

self.value = 1

def roll(self):

self.value = random.randrange(1,self.sides+1)

return self.value

newDie = Die(20)

print(newDie.roll())


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 • • Apr 04 '23

Beginner python help on code

1 Upvotes

Hi i was wondering how i have the input "enter your drink" in the same menu with the display drink

class drinks:
    def __init__(self,name,cost):
        self.name = name
        self.cost = cost
#display drink        
    
    def __str__(self):
        return f"{self.name} : {self.cost} cents"


#select drink
        drink = input("Enter drink you would like to purchase: ") 
        def select_drink(self):
            if drink in self.name:            
                return True
            else:
                print("This is not one of our drinks")
                return False 


    


d1 = drinks("Coffee", 120)
d2 = drinks("Tea", 80)
d3 = drinks("Coke", 150)
d4 = drinks("Juice",100)

print(d1)
print(d2)
print(d3)
print(d4)

r/pythonhomeworkhelp • • Jul 04 '23

If you are new to programming, your first program can become a daunting task! But not for you guys.

1 Upvotes

If you are new to programming, your first program can become a daunting task! But not for you guys.

I have created a blog post that will help you program your very first Python file! #programming #python #help

Coding Your First Program with Python! – Windows » Elevate Python


r/pythonhomeworkhelp • • Aug 01 '23

How to write a While Loop - Python

Thumbnail
elevatepython.com
1 Upvotes

r/pythonhomeworkhelp • • Jan 08 '23

How to extract tabular data with no clear table format

1 Upvotes

https://doc.morningstar.com/LatestDoc.aspx?clientid=wilmington&key=ec1abe1991294779&documenttype=124&sourceid=200&secid=FOUSA06URP

Hi,

please check the attached PDF,

I want to extract tabular data "Composition","Top 10 Holdings","Morningstar Equity Sectors" and also Market cap which has no header.
it it possible to extract the data in excel file and repeat this process for multiple similar files?

Thank you for your valuable time and help in advance.


r/pythonhomeworkhelp • • Jul 26 '23

Verifying the presence of a value in a list - Python.

Thumbnail elevatepython.com
1 Upvotes

r/pythonhomeworkhelp • • Aug 01 '23

Ultimate Guide To While Loops

Thumbnail elevatepython.com
1 Upvotes

r/pythonhomeworkhelp • • Jul 24 '23

The Ultimate Guide To Functions - Python

Thumbnail
elevatepython.com
1 Upvotes

r/pythonhomeworkhelp • • Jul 28 '23

The Ultimate Guide to Python Libraries

Thumbnail
elevatepython.com
1 Upvotes

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?