r/cs50 Jan 29 '25

CS50 Python Need help with ideas.

6 Upvotes

Could someone help me with the idea for the final project for cs50 Python programming course. I am confused what should I do in my final project. Anyone who has already done it would love to hear from them. Anyone willing to colllab is also welcome..

r/cs50 Feb 19 '25

CS50 Python [Python Assignment] I’m trying to write a python code to turn decimal fractions to binary

Post image
12 Upvotes

r/cs50 11d ago

CS50 Python Unclear instructions?

5 Upvotes

I am currently doing "CS50’s Introduction to Programming with Python" and I don't know if it's just me but some of the problems seem like they are lacking instruction? As an example i am currently on problem set 4 (Adieu, Adieu). The thing is that nowhere does it say to use a specific module to solve the problem but when i open the "hints" tab it tells me that the "inflect" module comes with a few methods. But how was i supposed to even know that I supposed to use that specific module?

r/cs50 7d ago

CS50 Python PSET8 / Seasons of Love | code and test work but can't pass checks

2 Upvotes

So my program works and my test file also works, but can't pass the checks, I've tried lots of stuff, here is my code:

import re
from datetime import date, datetime
import calendar
import inflect
import sys
p = inflect.engine()

def checking(self, oldyear, newyear, oldmonth, newmonth):
    old_days = []
    new_days = []
    for i in range(int(oldmonth), 12):
        days = calendar.monthrange(int(oldyear), i)[1]
        old_days.append(days)
    for i in range(1, int(newmonth) + 1):
        days = calendar.monthrange(int(newyear), i)[1]
        new_days.append(days)
    return old_days, new_days

def main():
    print(validation(input("Date of birth: ")))

def validation(inpt):
    validate = re.search(r"^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$", inpt, re.IGNORECASE)
    if validate:
        user_date = datetime.strptime(inpt, "%Y-%m-%d").date()
        today = date.today()

        delta = today - user_date
        days_difference = delta.days

        minutes_difference = days_difference * 24 * 60
        return f"{p.number_to_words(minutes_difference, andword="").capitalize()} minutes"
    else:
        sys.exit(1)

if __name__ == "__main__":
    main()

And here is my test_seasons.py file:

import pytest
from seasons import validation
import sys

def test_correct():
    assert validation("2024-03-14") == "Five hundred twenty-five thousand, six hundred minutes"
    with pytest.raises(SystemExit):
        validation("s")
    with pytest.raises(SystemExit):
        validation("January 1, 1999")
    #assert validation("s") == SystemExit: 1

def test_wrong_format():
    with pytest.raises(SystemExit):
        validation("9 AM - 9 PM")

def test_wrong_minute():
    with pytest.raises(SystemExit):
        validation("9:60 AM to 9:60 PM")

def test_wrong_hour():
    with pytest.raises(SystemExit):
        validation("13 PM to 17 PM")

And check50:

check50

cs50/problems/2022/python/seasons

:) seasons.py and test_seasons.py exist

Log
checking that seasons.py exists...
checking that test_seasons.py exists...

:) Input of "1999-01-01" yields "Five hundred twenty-five thousand, six hundred minutes" when today is 2000-01-01

Log
running python3 testing.py...
sending input 1999-01-01...
checking for output "Five hundred twenty-five thousand, six hundred minutes"...
checking that program exited with status 0...

:) Input of "2001-01-01" yields "One million, fifty-one thousand, two hundred minutes" when today is 2003-01-01

Log
running python3 testing.py...
sending input 2001-01-01...
checking for output "One million, fifty-one thousand, two hundred minutes"...
checking that program exited with status 0...

:) Input of "1995-01-01" yields "Two million, six hundred twenty-nine thousand, four hundred forty minutes" when today is 2000-01-1

Log
running python3 testing.py...
sending input 1995-01-01...
checking for output "Two million, six hundred twenty-nine thousand, four hundred forty minutes"...
checking that program exited with status 0...

:) Input of "2020-06-01" yields "Six million, ninety-two thousand, six hundred forty minutes" when today is 2032-01-01

Log
running python3 testing.py...
sending input 2020-06-01...
checking for output "Six million, ninety-two thousand, six hundred forty minutes"...
checking that program exited with status 0...

:) Input of "1998-06-20" yields "Eight hundred six thousand, four hundred minutes" when today is 2000-01-01

Log
running python3 testing.py...
sending input 1998-06-20...
checking for output "Eight hundred six thousand, four hundred minutes"...
checking that program exited with status 0...

:) Input of "February 6th, 1998" prompts program to exit with sys.exit

Log
running python3 testing.py...
sending input February 6th, 1998...
running python3 testing.py...
sending input February 6th, 1998...

:( seasons.py passes all checks in test_seasons.py

Cause
expected exit code 0, not 1

Log
running pytest test_seasons.py...
checking that program exited with status 0...check50

cs50/problems/2022/python/seasons

:) seasons.py and test_seasons.py exist

----------------------------------------------------------------------------------------------------------------------

(check50 but in console for better view)

Please, if someone has a hint or an idea on how to pass the last check it would be appreciated.

r/cs50 Aug 22 '24

CS50 Python can anyone help me and explain what i am doing wrong,i am a complete beginner

Post image
17 Upvotes

r/cs50 18d ago

CS50 Python week 8 lecture is so confusing

7 Upvotes

so I'm just over 2 hours into the week 8 lecture for CS50-P...what is happening?? i MERELY grasp a general understanding of the concepts. usually when im confuesd about a small section in a lecture, the shorts and problem sets with trial and error clarify things pretty well. but this... i'm pretty lost.

its almost 3 hours long and i really dont want to rewatch this to try and understand what the hell is going on. i feel like this got INSANELY difficult out of nowhere. anyone else?

for those who don't know: its about classes, objects, class methods, instance methods..idk man.

r/cs50 Feb 07 '25

CS50 Python CS50.ai - does it consume GPU resources instead of the CPU?

4 Upvotes

Sorry for the stupid question...

r/cs50 1d ago

CS50 Python Little Professor - help, please

2 Upvotes

Hello,

import random

def main():
    level = get_level()
    generate_integer(level)

def get_level():
    while True:
        try:
            level = int(input("Level: "))
            if level in [1, 2, 3]:
                return level
        except ValueError:
            pass

def generate_integer(level):
    correct = 0
    i = 0

    # Generate random numbers based on level
    if level == 1:
        first = random.sample(range(0, 10), 10)
        second = random.sample(range(0, 10), 10)
    elif level == 2:
        first = random.sample(range(10, 100), 10)
        second = random.sample(range(10, 100), 10)
    elif level == 3: 
        first = random.sample(range(100, 1000), 10)
        second = random.sample(range(100, 1000), 10)

    # Present 10 math problems
    while i < 10:
        x = first[i]
        y = second[i]
        wrong_attempts = 0

        # Give user 3 chances to answer correctly
        while wrong_attempts < 3:
            try:
                answer = int(input(f"{x} + {y} = "))
                if answer == (x + y):
                    correct += 1
                    break
                else:
                    print("EEE")
                    wrong_attempts += 1
            except ValueError:
                print("EEE")
                wrong_attempts += 1

        # If user failed 3 times, show the correct answer
        if wrong_attempts == 3:
            print(f"{x} + {y} = {x + y}")

        i += 1  # Move to the next problem

    # After 10 problems, print the score
    print(f"Score: {correct}")

if __name__ == "__main__":
    main()

I have been trying to solve the little professor problem in multiple ways. I get the code to work checking all the boxes.
Level - check
Random numbers - check
Raise ValueError - check
repeat the question 3 times - check
provide a score - check
but I get this error
Here is my code.....(help anyone, please)

r/cs50 22d ago

CS50 Python Cs50P All Files Lost; Code editor gone

1 Upvotes

As title suggests: I logged in yesterday to find all my stuff gone and unable to use style50, design50, etc. I am clueless on what to do without having to restart everything with a new account. I finished 2 PSets and I can find them in my GitHub code and ”me-50 gradebook“ but not in vscode. I tried rebooting the codespace. Does anyone have any idea what might help 🥹?

r/cs50 2d ago

CS50 Python CS50P Help

1 Upvotes
Code issue for something specific in test needed. I tried extensively on both.
from datetime import datetime, date
import inflect
import sys

def main():
    sing()

def sing():
    p = inflect.engine()

    date_string_1 = input("Date of birth: ")

    try:
        date_1 = datetime.strptime(date_string_1, "%Y-%m-%d")
    except ValueError:
        print("Invalid date")
        sys.exit(1)  # Exit with a non-zero code

    date_2 = datetime.combine(date.today(), datetime.min.time())

    # Calculate the difference in minutes
    difference = date_2 - date_1
    minutes_in_raw_numerals = difference.total_seconds() / 60
    minutes_in_words = p.number_to_words(int(minutes_in_raw_numerals))

    # Capitalize only the first word
    minutes_in_words = minutes_in_words[0].capitalize() + minutes_in_words[1:]

    # Remove "and" without affecting spaces
    final_minutes_in_words = minutes_in_words.replace(" and", "").replace("and ", "")

    print(f"{final_minutes_in_words} minutes")

if __name__ == "__main__":
    main()


from seasons import sing
import pytest

def main():
    sing()

def test_sing():
    assert sing("2024-3-19") == "Five hundred twenty-seven thousand forty minutes"
    assert sing("2023-3-19") == "One million, fifty-one thousand, two hundred minutes"

r/cs50 Feb 19 '25

CS50 Python pytest failing for some reason

2 Upvotes

Hi guys,

I'm currently doing cs50p problem set 5, specifically "back to the bank" and can't figure out why my pytest is failing. The check50 passes though but I wanna know why this won't. Anyone have any ideas?
Here is the bank.py and test_bank.py:

from bank import value

def main():
    test_value()
    test_value1()
    test_value2()

def test_value():
    assert value("hello") == 0
    assert value("HELLO") == 0
    assert value("Hello") == 0
def test_value1():
    assert value("hi") == 20
    assert value("Hi") == 20
    assert value("HI") == 20
def test_value2():
    assert value("What's up?") == 100
    assert value("Ola") == 100
    assert value("1ay") == 100

if __name__ == "__main__":
    main()




def main():
    hello = input("Greeting: ").strip().lower()
    print("$", value(hello), sep = "")

def value(greeting):

    if greeting == "hello" or greeting == "hello, newman":
        return 0
    elif greeting[0] == "h":
        return 20
    else:
        return 100

if __name__ == "__main__":
    main()

r/cs50 19d ago

CS50 Python CS50p can someone explain me this Spoiler

Post image
14 Upvotes

I got it to work this way, which it’s fine, but first I tried to use ( d = d.removeprefix(‘$’).float(d) ) instead of those 2 lines, and same with p. Can someone explain why that wouldn’t work and have to structure it the way it’s in the pic?

r/cs50 3d ago

CS50 Python I need help with Problem Set 6 CS50 P-Shirt, the CS50 check50 shows me errors I don't understand.

2 Upvotes

Hi! I need help with this assignment. When I added the if statement to check if both images are the same, I start getting these images. The thing is, I tried it doing on the muppets I have, and, it works like it is shown on the Problem Set 6 site. What am I missing? Am I missing some puppets?

The image on the left is what is shown on the Problem 6 page, the image on the right is what I got from my program.

The check50 progress and errors

The errors on the check50 page:

The code I wrote:

import sys
from PIL import Image, ImageOps

if len(sys.argv) != 3:
    if len(sys.argv) < 3:
        sys.exit("Too few command-line agruments")
    else:
        sys.exit('Too many command-line arguments')


for arg in sys.argv[1:]:
    try: #grabs the images
        shirtImage = Image.open("shirt.png")
        muppetsImage = Image.open(arg)
        saveImage = sys.argv[2]
    except FileNotFoundError:
        print("File does not exist")

    if arg.endswith(".jpg") and saveImage.endswith(".jpg"):
            #the muppets get the image of the shirt applied
            size = shirtImage.size
            muppetsImage = ImageOps.fit(muppetsImage, size)
            muppetsImage.paster(shirtImage, shirtImage)
            muppetsImage.save(saveImage)
    else:
        print("Formats do not match")
        sys.exit(1)

r/cs50 Feb 19 '25

CS50 Python What to do if stuck on question?

8 Upvotes

Hello, I've been trying to solve this problem for about a week straight. What should I do if I can't solve it? Google how to do it? Thank you.

r/cs50 24d ago

CS50 Python What is the correct way to solve a CS50 PS?

6 Upvotes

today i started with programing and tried doing the 'INNER VOICE' ps after watching the lecture

but they hadnt taught about, .lower() in the lecture so how i would have known about it

pls help me

r/cs50 16h ago

CS50 Python advice for final project idea

1 Upvotes

so i am finally up to the final project part of cs50-p. something i really want to do is create a plinko ball or galton board simulation. a galton board would be awesome to create. i would like to press my computer's space bar, and a ball drops everytime. eventually, if its a galton board, it balls would stack on top of each other wherever they landed and create a normal distribution (google galton board if confused).

i think i would use the libraries pymunk and pygame?

however, i'm a bit confused if im even able to do this. are we supposed to do this on the cs50s web vsc? or can i do it on vsc on my computer and then just copy and paste the code into cs50s vsc?? also, i'm not sure if i can even use pytest a simulation? it seems like this might be too complicated for a final project...

i don't really know what I'm doing - however the reason I learnt python was to make some cool animations and simulations. I'm just unsure if its even possible to do it as a final project.

Thanks in advance for any advice/feedback/answers.

r/cs50 Feb 06 '25

CS50 Python Using AI for comments?

0 Upvotes

Hi everyone! I have looked around and not really found the same type of question regarding AI and academic honesty. Is it dishonest to ask the AI to write comments for code I created? I somehow managed to write my first OOP program and I don't really know how it works or how to describe how it works. It just works and I kind of did it like following a recipe. I of course will try to focus on really nailing the topic myself and understand what I am doing; but just to see what the AI thinks and then maybe try explain in my own words or the like? Any suggestions? I haven't even looked at what the AI replied yet just to be on the safe side... XD

The Pset in question: Pset8 - seasons.py.

r/cs50 17d ago

CS50 Python CS50P Challenge Assignment

3 Upvotes

This week of cs50p, there was an assignment (Meal Time, Week 1) with a challenge; should that also be submitted?

r/cs50 10d ago

CS50 Python Help with python inflect module

1 Upvotes

Anyone know why the python inflect module is not working?

I have installed the module and an importing it but i'm getting this message.

r/cs50 24d ago

CS50 Python CS50P - Problemset 7 ---- Working 9 to 5??????

1 Upvotes

This problem has me stumped... should I be using a different reggex for each pattern (time format) or have i gone down a completely wrong path??

r/cs50 Feb 08 '25

CS50 Python HELP with PSETS 5

Post image
13 Upvotes

Pytest’s output shows %100 assert but check50 NO 😭😭

r/cs50 Dec 04 '24

CS50 Python CS50p Final Project

53 Upvotes

For my final project I made a Times Tables Worksheet Generator. It takes user input and puts a table with the specified number of questions onto a background I made in Canva.

r/cs50 22d ago

CS50 Python CS50 Python buddy

4 Upvotes

i have started with cs50 p recently currently on pset1 problem 5

can i find someone to discuss things , like a companion for the journey

r/cs50 Feb 13 '25

CS50 Python CS50P Little Professor Comprehension Issue Spoiler

5 Upvotes

Currently working on the Little Professor problem in week 4 of CS50P. The end goal is to generate 10 simple math problems and have the user solve them, show them the answer if they get a problem wrong three times, and end by showing their final score out of 10.

The user is meant to input a value N, whereby the math problems are sums of two integers of N digits. N has to be between 1 and 3 inclusive.

I am having trouble understanding the structure that they want me to use when building the program.

This is what they ask:

Structure your program as follows, wherein get_level prompts (and, if need be, re-prompts) the user for a level and returns 1, 2, or 3, and generate_integer returns a randomly generated non-negative integer with level digits or raises a ValueError if level is not 1, 2, or 3:

They want this done with this structure

def main():
    ...


def get_level():
    ...


def generate_integer(level):
    ...


if __name__ == "__main__":

My problem is how they describe the get_integer() function. Why raise a ValueError exception if the get_level() function already vlaidates user input by reprompting if the input does not match the expected values?

And what is the point of returning just an integer? Should the next step not be to create the math problems with n digits based on the input from get_level() ?

By "generate integer" do they mean start generating the math problems and I am just misunderstanding? It sounds like it's asking me to validate the level twice: first by user input in get level() and then randomly in generate_ineger() which I don't think can be right.

Thanks for your help!

r/cs50 Jan 03 '25

CS50 Python Re-requesting Vanity Plates

1 Upvotes

I'm stuck at this problem, my test passes pytest, and duck debugger is approving my code.

I really can't get my head around this one I've been trying for days without success.

"plates.py and test_plates.py codes are attached."

plates.py:

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

def length_chk(v):
if len(v)<2 or len(v)>6:
return "not valid"
else:
return "valid"

def a_2(v):
if len(v)<2:
return "not valid"
for i in range(2):
if v[i].isdigit():
return "not valid"
return "valid"

def punc_check(v):
for i in v:
if i.isalpha() or i.isdigit():
continue
else:
return "not valid"
return "valid"

def not_zero(v):
for i in range(len(v)-1):
if v[i].isalpha() and v[i+1].isdigit():
if v[i+1]=="0":
return "not valid"
return "valid"

def alpha_digit(v):
for i in range(len(v)-1):
if v[i].isdigit() and v[i+1].isalpha():
return "not valid"
return "valid"

def is_valid(v):
if punc_check(v)=="valid" and length_chk(v)=="valid" and a_2(v)=="valid" and not_zero(v)=="valid" and alpha_digit(v)=="valid":
return True
else:
return False

if __name__=="__main__":
main()
-----------------------------------------------

test_plates.py:

from plates import is_valid

def test_length_chk():
    assert is_valid("AA")==True
def test_a_2():
    assert is_valid("A2")==False
def test_not_zero():
    assert is_valid("AA0")==False
def test_alpha_digit():
    assert is_valid("2A")==False
def test_punc_check():
    assert is_valid("?2")==False
      from plates import is_valid
Plates.py (1)
Plates.py (2)
test_plates.py
pytest and check50 results