/r/cs50

Photograph via snooOG

Demanding, but definitely doable. Social, but educational. A focused topic, but broadly applicable skills. CS50 is the quintessential Harvard (and Yale!) course.


O hai! This is CS50's subreddit.

CS50 is Harvard University's introduction to the intellectual enterprises of computer science and the art of programming. Anyone may take CS50, even if not a student at Harvard.


Please Read before Posting

Getting the Best from r/cs50


Status Page

cs50.statuspage.io



Filter by Problem Flair (undo)

cashcaesarcreditdnafilterfinancehousesidemariomoviespluralityprojectreadabilityrecoverrunoffscratchspellersubstitutiontidemangames trackweb trackandroid trackiOS track


Filter by Other Flair (undo)

CS50-LawCS50-BusinessCS50-TechnologyCS50-GamesCS50-MobileCS50-Web



This subreddit is night mode compatible

/r/cs50

116,064 Subscribers

1

Finance

Is it possible for me to get the certificate if i complete everything and have them all correct for every single problem set expect for Finance?

1 Comment
2024/12/21
22:04 UTC

3

Why does it say I only completed 7/11 weeks?

I checked my gradebook and it said i have missing assignments but I turned them in, why is that?

4 Comments
2024/12/21
19:56 UTC

1

CS50P - Week 5 - Refueling

Hi, I've been looking for the error in my code for hours...

- check50 cs50/problems/2022/python/tests/fuel

Results for cs50/problems/2022/python/tests/fuel generated by check50 v3.3.11
:) test_fuel.py exist
:( correct fuel.py passes all test_fuel checks
    expected exit code 0, not 2
:| test_fuel catches fuel.py returning incorrect ints in convert
    can't check until a frown turns upside down
:| test_fuel catches fuel.py not raising ValueError in convert
    can't check until a frown turns upside down
:| test_fuel catches fuel.py not raising ZeroDivisionError in convert
    can't check until a frown turns upside down
:| test_fuel catches fuel.py not labeling 1% as E in gauge
    can't check until a frown turns upside down
:| test_fuel catches fuel.py not printing % in gauge
    can't check until a frown turns upside down
:| test_fuel catches fuel.py not labeling 99% as F in gauge
    can't check until a frown turns upside down
To see more detailed results go to https://submit.cs50.io/check50/1acbe68c78bb4c06bb1e7975b01156159364ef33

But if I run my test_fuel.py:

test_fuel/ $ pytest test_fuel.py 
====================================================================================== test session starts ======================================================================================
platform linux -- Python 3.12.7, pytest-8.3.3, pluggy-1.5.0
rootdir: /workspaces/144679101/test_fuel
plugins: typeguard-4.4.0
collected 7 items                                                                                                                                                                               

test_fuel.py .......                                                                                                                                                                      [100%]

======================================================================================= 7 passed in 0.01s =======================================================================================

I don't really know where I have the error. My fuel.py functions as it should. I did not have any problems with the other three problems.
Help is appreciated!

2 Comments
2024/12/21
18:21 UTC

7

Does anyone know what cs50 courses are being updated this year other than cs50x?

Does anyone know what cs50 courses are being updated this year other than cs50x? Such as cs50 w, ai, and cyber?

2 Comments
2024/12/21
17:22 UTC

10

Will doing CS50p help me with deciding if i want to major in CS or do i have to do CS50x to get a more specific intro?

Hey guys, I have to pick my major in a couple of months and I’m still not sure what i want to do. I’ve always replies “CS” to people asking me what i want to major in, but now i realize that i don’t actually know much about the field.

I had an idea of doing one of the CS50 courses to show me a bit about the major but i hear that CS50x can be quite discouraging for a beginner.

I wanted to ask will doing CS50p also have the same effect as i wanted CS50x to or should i just stick with CS50x and try to ride it out?

7 Comments
2024/12/21
15:53 UTC

3

I need help on PSET 2, plates, CS50P

Firstly thank you all for those who have tried to help me on my previous post. I tried applying them but it just made me even more confused. Instead, maybe you can help me identify the errors in another revised version of my previous code.

PSET in qn:

https://preview.redd.it/a1temaonu78e1.png?width=694&format=png&auto=webp&s=aa66cf13f016041e63f69b16e961e052f2c4c166

The code:

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


def is_valid(s):
    s = list(s)
    flag = True
    flag1 = True


    if not (len(s) >= 2 and len(s) <= 6):
            return False
    if not (s[0].isalpha() and s[1].isalpha()):
            return False

    for i in range(2, len(s)): #[A, A, A, 2, 2 , A] [C, S, 5, 0] [A, A, A, 2, 2, 2]
        if s[i].isdigit():
            if s[i] == "0":
                return False
            else:
                for j in range(i, len(s)):
                    if not s[j].isdigit():
                         #as long as 1 element is a non-digit, flag = False
                         flag = False
                         break

        elif s[i].isalpha():
             pass

        elif not (s[i].isalpha() or s[i].isdigit()):
             flag1 = False

    if flag:
        return True
    if flag1:
        return True
    else:
        return False

main()

Im struggling to understand why my code still outputs valid when i input "AAA22A". According to CS50.ai, it has do with the logic of my inner loop and return conditions based on flag and flag1.

Below is what CS50.ai have to say regarding why "AAA22A" still outputs "Valid":

ddb

It looks like you're trying to validate a string based on certain conditions. Let's break down your code and see where it might be going wrong.

  1. Flag Initialization: Ensure that flag and flag1 are initialized to True before the loop starts.
  2. Inner Loop Logic: When you find a digit, you check subsequent characters. If any of them are not digits, you set flag to False. However, you don't seem to reset flag if you find a valid sequence later.
  3. Return Conditions: You have multiple return conditions based on flag and flag1. Make sure these flags are being set correctly based on your logic.

Can you try to print the values of flag and flag1 at different points in your code to see how they change? This might help you understand why the output is "valid" even when it shouldn't be.

PLS help a bro out

2 Comments
2024/12/21
14:59 UTC

4

Is CS50 intro to programming with python the best way to learn python?

Unlike every other python course this one is normal around 20 hours I believe and that's way too much when comparing it to others so what does it offer more? Is it worth it or not

9 Comments
2024/12/21
13:52 UTC

2

Organizing code50 commit.

Started doing problem in cs50.dev Loved it :D

But can I squash, remove a commit. I want to organize them myself. I also don't want to have 100+ commit in one day ruined my GitHub's commit history. Thanks!

0 Comments
2024/12/21
12:19 UTC

2

Pset 9 Finance: App behaving correctly but check 50 keeps giving expected to find "56.00" in page, but it wasn't found

Hey guys, I have spent two days rewriting my code for Finance and have even been unit testing using values in lookup that mimic a static stock price and then carrying out actions just as check 50 does. When I do this it behaves as requested (see pic), but check 50 keeps saying it doesn't.

https://preview.redd.it/vu1tfjxvx68e1.png?width=957&format=png&auto=webp&s=c33905d3316b2446ae29ed4d1d4c05648cf2f0b8

I've read all the other posts from people who had trouble with this valid sale check, but none of the mistakes they made are in my code. I restructured my sql database and changed data handling to try make sure everything was as optimal as I can make it at this stage of my ability. Yet it just keeps telling me

:( sell handles valid sale
Cause
expected to find "56.00" in page, but it wasn't found
Log
sending POST request to /login
sending POST request to /sell
checking that "56.00" is in page

Any help would be greatly appreciated. Hopefully posting this means I just figure out what is going wrong immediately after.

Here's my Sell function and html of Index the values are being handed to, and my Index function if that helps:

Sell Function:

@app.route("/sell", methods=["GET", "POST"])
@login_required
def sell():
    """Sell shares of stock"""
    if request.method == 'GET':
        # Get shares user bought
        shares_bought = db.execute("SELECT stock, SUM(shares) AS total_bought FROM purchases WHERE buyer_id = ? GROUP BY stock", session["user_id"])

        # Get shares user sold
        shares_sold = db.execute("SELECT stock, SUM(shares) AS total_sold FROM sales WHERE seller_id = ? GROUP BY stock", session["user_id"])

        # Convert shares to dictionary for quick lookup (O(1) lookup time by stock name, as opposed to O(n) for a list)
        bought_dict = {item["stock"]: item["total_bought"] for item in shares_bought}

        # Convert sales to dict as well for consistency and speed
        sold_dict = {item["stock"]: item["total_sold"] for item in shares_sold}

        # Iterate through shares bought and index into sold dict for match and do substraction
        for stock in bought_dict.keys():
            if stock in sold_dict:
                bought_dict[stock] -= sold_dict[stock]

        # Save our dictionary of items held in the session data to use elsewhere
        session ["bought_dict"] = bought_dict

        # Build list of stocks held
        stocks_held = [stock for stock, shares in bought_dict.items() if shares > 0]

        # Render menu after stocks found
        return render_template("sell.html", symbols=stocks_held)

    elif request.method == 'POST':

        bought_dict = session.get("bought_dict")
        if not bought_dict:
            return apology("Session expired or invalid request", 400)

        # Fetch users symbol from form
        symbol = request.form.get("symbol")
        if not symbol:
            return apology("Missing Symbol", 400)

        if symbol not in bought_dict:
            return apology("Symbol not in portfolio", 400)

        # Fetch shares to buy from form and convert to integer unless 0 or nothing entered
        shares = request.form.get("shares")
        if not shares:
            return apology("Missing No. of Shares", 400)

        shares_int = int(shares)
        print(shares_int)

        if shares_int > bought_dict.get(symbol, 0):
            return apology("Not enough shares", 400)

        if not shares_int >= 1:
            return apology("Positive no. of shares needed", 400)

        # Use lookup function to fetch stock information
        quote_data = lookup(symbol)
        if not quote_data:
            return apology("Invalid stock symbol", 400)

        # Execute sale
        sale_price = quote_data["price"] * shares_int
        print(sale_price)
        db.execute(
            "UPDATE users SET cash = cash + ? WHERE id = ?",
            sale_price, session["user_id"]
        )
        db.execute(
            "INSERT INTO sales (seller_id, stock, shares, price) VALUES (?, ?, ?, ?)",
            session["user_id"], quote_data["symbol"], shares_int, sale_price
        )

        # Return to homepage
        return redirect("/")

Index HTML:

{% extends "layout.html" %}

{% block title %}
Portfolio
{% endblock %}

{% block main %}
    {% if portfolio %}
    <table class="table table-striped">
        <thead>
            <tr>
                <th class="text-start">Symbol</th>
                <th class="text-end">Shares</th>
                <th class="text-end">Price</th>
                <th class="text-end">TOTAL</th>
            </tr>
        </thead>
        <tbody>
            {% for item in portfolio %}
            <tr>
                <td class="text-start">{{ item.stock }}</td>
                <td class="text-end">{{ item.shares }}</td>
                <td class="text-end">{{ item.price | usd }}</td>
                <td class="text-end">{{ item.total | usd }}</td>
            </tr>
            {% endfor %}
        </tbody>
        <tfoot>
            <tr>
                <td class="border-0 fw-bold text-end" colspan="3">Cash</td>
                <td class="border-0 text-end">{{ user_cash_total | usd }}</td>
            </tr>
            <tr>
                <th class="border-0 fw-bold text-end" colspan="3">Total</th>
                <td class="border-0 w-bold text-end">{{ user_balance_total |usd }}</td>
            </tr>
        </foot>
    </table>
    {% else %}
    <p>No holdings in your portfolio.</p>
    <tfoot>
        <tr>
            <td class="border-0 fw-bold text-end">Cash</td>
            <td class="border-0 text-end">{{ user_cash_total | usd }}</td>
        </tr>
    </foot>
    {% endif %}
{% endblock %}

Index Function results also being handed to index.html:

@app.route("/")
@login_required
def index():
    """Show portfolio of stocks"""

    # Get shares user bought
    shares_bought = db.execute("SELECT stock, SUM(shares) AS total_bought FROM purchases WHERE buyer_id = ? GROUP BY stock", session["user_id"])

    # Get shares user sold
    shares_sold = db.execute("SELECT stock, SUM(shares) AS total_sold FROM sales WHERE seller_id = ? GROUP BY stock", session["user_id"])

    # Convert shares to dictionary for quick lookup (O(1) lookup time by stock name, as opposed to O(n) for a list)
    bought_dict = {item["stock"]: item["total_bought"] for item in shares_bought}

    # Convert sales to dict as well for consistency and speed
    sold_dict = {item["stock"]: item["total_sold"] for item in shares_sold}

    # Iterate through shares bought and index into sold dict for match and do substraction
    for stock in bought_dict.keys():
        if stock in sold_dict:
            bought_dict[stock] -= sold_dict[stock]

    # Build portfolio with all relevant information looked up
    portfolio = []
    for stock, shares in bought_dict.items():
        quote_data = lookup(stock)
        if not quote_data or shares == 0:
            continue # Skips if nothing looked up or stock was all sold

        # Append relevant info to portfolio
        portfolio.append({
            "stock": stock,
            "shares": shares,
            "price": quote_data["price"],
            "total": (quote_data["price"] * shares),
        })

    # Query database for users ket\y value pair
    user_cash_call = db.execute("SELECT cash FROM users WHERE id = ?", session["user_id"])

    # Extract from the query the value
    user_cash_total = (user_cash_call[0]['cash']) if user_cash_call else 0

    portfolio_total = sum(item["price"] * item["shares"] for item in portfolio)

    user_balance_total = (portfolio_total + user_cash_total)

    # If Portfolio empty
    if not portfolio:
        return render_template("index.html", portfolio=[], user_cash_total=user_cash_total, user_balance_total=user_balance_total)


    return render_template("index.html", portfolio=portfolio, user_cash_total=user_cash_total, user_balance_total=user_balance_total)
4 Comments
2024/12/21
11:56 UTC

2

Final project frontend framework

So, I'm about to start my final project. And I'm planning to do the backend with FastAPI. What framework would you recommend for the frontend?

Also, do you have any suggestions for a final project idea?

2 Comments
2024/12/21
10:23 UTC

4

CS50’s Introduction to Databases with SQL

In final project do I need to have db to run the schema.sql? Im confused since in the sample final project there is no folder for db.
Thanks guys!

0 Comments
2024/12/21
01:19 UTC

0

Vanity Plates

My code worked and successfully passed the check, but having looked at everyone else's code I feel like I passed this check by luck. Specifically, the first number check for the 0. Can someone please give me feedback?

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


def is_valid(s):
    a = s[0:1].isalpha()           ### check if first and second letter is a a-z char
    b = 2 <= len(s) <= 6           ### return length of plate

    def rule(s):                   ### define function to check for last 2 rules
        for letter in s:
        ### iterate over every letter in the plate

            if s[-1].isalpha() and letter.isdigit():
            ### if last letter is a a-z char and a char is a digit

                return False
                

            if s.isalnum() == False:
            ### if any letter is not an a-z char and is not a number

                return False

            if letter == "0" and s.endswith("0") == False
            ### if first number char is a 0, return false

                return False
        else:
            return True

    c = rule(s)

    rules = [a, b, c]

    if all(rules):
        return True
    else:
        return False



main()
0 Comments
2024/12/21
01:15 UTC

14

Is cs50x the hardest for you guys?

I just finished the course, and I’ve read a lot of posts here saying that cs50x is just too hard, but ain’t cs50x the core of the whole course? That’s why they begin with it in week 1 and all, just curious to know.

14 Comments
2024/12/21
01:13 UTC

0

Vanity Plates

My code worked and successfully passed the check, but having looked at everyone else's code I feel like I passed this check by luck. Specifically, the first number check for the 0. Can someone please give me feedback?

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


def is_valid(s):
    a = s[0:1].isalpha()           ### check if first and second letter is a a-z char
    b = 2 <= len(s) <= 6           ### return length of plate

    def rule(s):                   ### define function to check for last 2 rules
        for letter in s:
        ### iterate over every letter in the plate

            if s[-1].isalpha() and letter.isdigit():
            ### if last letter is a a-z char and a char is a digit

                return False
                

            if s.isalnum() == False:
            ### if any letter is not an a-z char and is not a number

                return False

            if letter == "0" and s.endswith("0") == False
            ### if first number char is a 0, return false

                return False
        else:
            return True

    c = rule(s)

    rules = [a, b, c]

    if all(rules):
        return True
    else:
        return False



main()
2 Comments
2024/12/21
01:11 UTC

0

Vanity Plates

My code worked and successfully passed the check, but having looked at everyone else's code I feel like I passed this check by luck. Specifically, the first number check for the 0. Can someone please give me feedback?

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


def is_valid(s):
    a = s[0:1].isalpha()           ### check if first and second letter is a a-z char
    b = 2 <= len(s) <= 6           ### return length of plate

    def rule(s):                   ### define function to check for last 2 rules
        for letter in s:
        ### iterate over every letter in the plate

            if s[-1].isalpha() and letter.isdigit():
            ### if last letter is a a-z char and a char is a digit

                return False
                

            if s.isalnum() == False:
            ### if any letter is not an a-z char and is not a number

                return False

            if letter == "0" and s.endswith("0") == False
            ### if first number char is a 0, return false

                return False
        else:
            return True

    c = rule(s)

    rules = [a, b, c]

    if all(rules):
        return True
    else:
        return False



main()
0 Comments
2024/12/21
01:11 UTC

0

How to submit two final projects for two CS50 courses at once?

Hi all!

I'm trying to submit final projects for both CS50x and CS50p at the same time, but both assignments indicate that we need to create a folder ~/project and put our project within it with the name "project" (e.g. project.py). How am I supposed to do this for both projects, as these identical naming conventions will obviously conflict with one another?

Or am I being too literal here, and project can be replaced with my actual project name?

Thank you!

2 Comments
2024/12/21
00:16 UTC

3

Some SQL pset's expected results are possibly incorrect

I was frustrated in the problems not because it was hard, on the contrary it was quite easy and fun to do but when my results didn't match the expected results in their website, i lost my mind, wasted a lot of time until i used check50 and gave me the green light.

2 Comments
2024/12/20
23:19 UTC

1

Visual Studio Code Settings

I installed VSC and am having trouble with the settings to allow my workspace to look similar to what is being shown in the course. Any advice would be helpful. Attached are photos of what my program looks like vs what is in class. I want to get rid of "lakenschulz@Lakens-MacBook-Pro ~ %" and obtain a cleaner and simpler look for learning purposes.

https://preview.redd.it/fz2h7wri338e1.png?width=3022&format=png&auto=webp&s=18bfd2224be1d47b52d8108fd23c128f5e4e3f1a

https://preview.redd.it/04h6qwri338e1.png?width=3024&format=png&auto=webp&s=c5929784e8fed587d8435f85ef6fa0882b16ffcb

https://preview.redd.it/jxc910si338e1.png?width=3024&format=png&auto=webp&s=cf067ec0d2d12c1c80ad79d445d2c759c811dbf2

4 Comments
2024/12/20
23:01 UTC

21

OC: Completed CS50X as a non-computer working medical person. Here is My Video Review

Here are my thoughts on the course as someone who isn't considered a computer person working a busy job as a medical resident physician. I'm happy to answer any questions.

1 Comment
2024/12/20
21:36 UTC

2

need help with PSET 2, plates, CS50P

my question is where can i place my "return True" statement for the elif statement "new_s[i].isalpha()" without breaking the for loop prematurely. Pls help, ive spent days just getting to this point. TIA.

requirements of the problem in question:

https://preview.redd.it/k7dv6aanaz7e1.png?width=896&format=png&auto=webp&s=a75cd39617d49e746a9e2f90c55c234b71f04c57

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


def is_valid(s):
    new_s = list(s)
    flag = False


    if not (len(new_s) >= 2 and len(new_s) <= 6):
            return False
    if not (new_s[0].isalpha() and new_s[1].isalpha()):
            return False

    for i in range(len(new_s)):
        if new_s[i].isdigit():
            if new_s[i] == "0":
                return False
            else:
                for j in range(i, len(new_s)):
                    if new_s[j].isdigit():
                        flag = True
                break

        elif new_s[i].isalpha():


        else:
            return False


    if flag:
        return True

    else:
        return False



main()

my code:

5 Comments
2024/12/20
10:12 UTC

4

CS50 Codespace Carryover to new Year

I finished all problem sets of CS50x but won't be able to complete my final project before the new year. I would like to write the project in the codespace provided by CS50. Will there be a reset or something next year? Should I make a backup of my code?

2 Comments
2024/12/20
09:39 UTC

5

Cs50 verified Certificate

Hello, i just finished cs50 and once I finished i upgraded for the verified certificate. Is everything is ok now or there is something additional i have to do to get the verified certificate?

3 Comments
2024/12/20
08:30 UTC

3

The codespace is not available

https://preview.redd.it/l2yho7nljy7e1.png?width=957&format=png&auto=webp&s=edad96af16c055623c94b1f971ca963f296ec079

I added a post about bank.py not being able to save only yesterday and today it says that my codespace is not available. Can someone please help me fix this. Who should I talk to ?

5 Comments
2024/12/20
07:42 UTC

17

About four months of learning and almost a whole year off - and now back at it!

I started CS50P when I had some down time at work last year and was able to get through about half the modules when things started kicking. Then life being life and the busy things happening to me I found myself struggling to get back into it. I watched the File I/O Youtube video like four times over the last year and would stare a blank github screen. I felt like I had been hitting a wall since Lesson 4, it had been getting harder to grasp the concepts. But today (after nearly a year of not coding) I finally submitted Lines.py the first assignment for Lesson 6. Trying to turn this back into momentum - and you can too if you're struggling!

0 Comments
2024/12/20
02:47 UTC

3

VSCODE Error

https://preview.redd.it/mrquqg2hcu7e1.png?width=564&format=png&auto=webp&s=b5ef3d08f713dfdf55e405ca8bb3f6358942da4b

Hey guys can someone please help me with this error. I have no idea how to continue. Even if I hit Overwrite it does not save the bank.py file. Matter of fact the autosave feature does not seem to be working.

2 Comments
2024/12/19
17:34 UTC

16

Roadmap to Data Engineering After CS50x and CS50P?

Hi everyone,

I just finished CS50x and CS50P and want to become a data engineer. With my current knowledge, what should my roadmap be?

Thanks in advance for your help!

8 Comments
2024/12/19
15:10 UTC

Back To Top