/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

114,475 Subscribers

1

Chrome stuck on "Setting up your codespace" since last few days

Hi folks! a few days there was this incident where codespaces was not running. After the incident cleared, I was never able to access again with Chrome. It does work with Firefox, doesn't play that well with the codespace as it messes up with the color theme, etc.

Anyone else having the same? already tried clearing cache and cookies, restarting everything, rebuilding the codespace, etc... nothing worked.

These are the last few things it loads before stopping:

https://preview.redd.it/7vhj9zit5f0e1.png?width=412&format=png&auto=webp&s=854a622e0b6e086252a6ac381d468c092ae12131

The workbench error is present on Firefox as well, but not the other one. Anyway, it stops way to soon on the process. Any thoughts? many thanks for your input!

1 Comment
2024/11/12
07:02 UTC

3

Is it possible to complete CS50x before 2025 if I start today?

Hi everyone! I’m planning to start the CS50x course today, aiming to complete it before 2025. I noticed it says that the course is only available until December 31, 2024. Does that mean I can’t access the materials after that date? And, if so, would it still be possible to complete it on time if I stay consistent? I’d appreciate any tips or insights from those who've taken it recently!

6 Comments
2024/11/12
06:24 UTC

1

Issue when setting up my own programming environment after the Week10 class (before CS50x final project)

Hi, would someone be able to help me ? I get this error message when trying to run this command recommended by Andrew Holmes (TA) in his Flying the Nest seminar of week 10:

command: pip3 install cs50

error message:
**@**:.../CS50/CS50x$ pip3 install cs50

error: externally-managed-environment

× This environment is externally managed

╰─> To install Python packages system-wide, try apt install

python3-xyz, where xyz is the package you are trying to

install.

If you wish to install a non-Debian-packaged Python package,

create a virtual environment using python3 -m venv path/to/venv.

Then use path/to/venv/bin/python and path/to/venv/bin/pip. Make

sure you have python3-full installed.

If you wish to install a non-Debian packaged Python application,

it may be easiest to use pipx install xyz, which will manage a

virtual environment for you. Make sure you have pipx installed.

See /usr/share/doc/python3.12/README.venv for more information.

note: If you believe this is a mistake, please contact your Python installation or OS distribution provider. You can override this, at the risk of breaking your Python installation or OS, by passing --break-system-packages.

hint: See PEP 668 for the detailed specification.

should I override this and download anyway? and is this process of being able to use a Local Development Environment useful at all ?

Thanks a lot for the help

0 Comments
2024/11/12
01:20 UTC

3

Week5

I’m halfway through the main lecture and wtf. Even though I’ve touched upon linked lists in higher programming languages before (JavaScript), I find myself spinning. Any tips for this week? I planned on watching the shorts after the main lecture.

also, does it get easier after this week? Week 4 took me a month slready

1 Comment
2024/11/11
22:24 UTC

1

Unit test pset check50 issue

So I'm trying to submit my "Back to the Bank" PSet which is to test the "Home Federal Savings Bank" PSet from week 1 on conditionals. However, the check50 is coming out with all yellow faces except one red and one green. I don't think I've come across yellow before and when I click the link to the check50 site, it didn't explain them. The pytest passed all the functions so I don't know why it isn't passing on check50. I've attached a picture of the passing pytest and the failed check50.

https://preview.redd.it/e7tnm7z5lc0e1.png?width=2294&format=png&auto=webp&s=6573a730acae02064a844c93bfb781656667adec

1 Comment
2024/11/11
22:21 UTC

16

starting from scratch (below the bottom line if it exists)

I want to take cs50P to learn python but I have zero CS knowledge. Before I start, can someone please be real and let me know if I should take cs50x first and get my basics polished or does cs50P cover the basics enough for me to not off myself within the first week?

PS. Im an accounting student looking to enhance my skills before I start job hunting, and python would help with data analysis, and I had some time off classes so why not.

PPS. midlife crisis, some guidance would do wonders THANK YOU

7 Comments
2024/11/11
19:57 UTC

1

I don't understand Check50

I am getting this error message on week 9 finance. I am getting this back from check50

:( buy handles valid purchase

Cause
expected to find "112.00" in page, but it wasn't found

Log
sending POST request to /login
sending POST request to /buy
sending POST request to /buy
checking that "112.00" is in page:( buy handles valid purchase

Cause
expected to find "112.00" in page, but it wasn't found

I don't know what 112.00 is or where that should be so I don't know what I am doing wrong. Thanks in advance for the help!

1 Comment
2024/11/11
19:12 UTC

2

Problem with check50 on Marioless problemset. Keeps saying I have extra spaces but the output looks correct in vscode.

2 Comments
2024/11/11
16:49 UTC

10

Stuck in Tideman

Hi folks! I took CS50 twice before, but I keep getting stuck and end up quitting at the same point. I could solve the easier pset and move on to the next lecture, but I don't go to the next lesson until I've completed all the problem sets

This affects my motivation. I'm getting stuck on checking for cycles in the Tideman problem. I'm looking forward to any suggestions or advice you might have on this topic

9 Comments
2024/11/11
10:01 UTC

0

Looking for a co founder. Highly technical. Knows apis of different llms, android, apple dev. Knows web dev.

Contact me. Write your college and previous cool projects in the comment section.

0 Comments
2024/11/11
07:52 UTC

4

Runnoff done, should I try Tideman

So basically I finished runoff after a few hours, but I feel like it was a bit too easy. Probably due to using the duck AI. Should I give Tideman a try without using the AI as much?

9 Comments
2024/11/10
22:56 UTC

224

I finally got it 😭

37 Comments
2024/11/10
22:03 UTC

177

13 hours and a few coffees later - Tideman has finally been conquered

Two pieces of advice that I would have probably ignored myself LOL, but please, follow them:

1- Don’t code the whole day, if you’re stuck on one function for more than a few hours, go out, forget about Tideman for a good while, sleep, eat, then come back. Even if it’s the next day.

2- Learn some graph traversal algorithm to better understand recursion, once I learned DFS Lock_pairs became super easy.

Actually 3: Write stuff down in plain english then translate to code, I only started doing it in the last couple hours, I would have finished so much faster had I done this from the start.

1 Comment
2024/11/10
17:59 UTC

5

CS50x-2024 Final Project - Flask LocalHost not updating changes in browser

Hi all,

Has anyone else had this problem where changes are not reflected immediately on localhost when you make updates to HTML /css etc. Pressing refresh does nothing.

The only way is to see the changes is to quit flask and close browser then reopen both...

I must have missed something in the config. This is on VSCODE running locally on Mac.

Thanks in advance.

2 Comments
2024/11/10
17:28 UTC

1

pip3 not working!?

I'm just following the seminar on setting up the IDE, and the pip wasn't working

https://preview.redd.it/wyadkqvmtzzd1.png?width=1914&format=png&auto=webp&s=543faf6d64ac12640317a62909304e37470a150d

1 Comment
2024/11/10
03:25 UTC

0

Chat is is this true that innovation is dead in IT. And there will be no young tech billionaires?

And is computer science as a field still as money making as it was before?

6 Comments
2024/11/09
23:06 UTC

1

Tips please

I'm struggling with some of the problem sets in CS50, as they include topics that aren’t covered in the lectures. Should I go through the documentation and the extra materials linked in the notes to understand these topics, or is there a better way to handle this?

7 Comments
2024/11/09
16:08 UTC

57

As a dev with 2.5 YOE, cs50 is great!

My background: I am finishing a college of proffesional studies for IT(3 year program) and there is very little to none low level programming, it is mostly c#, php, html/css and js. While finishing college I worked as a .net developer for a company for around 2,5 years.

Cs50 helped glue together a lot of knowledge I had into a whole structure that now makes a lot more sense.

My point is that anyone who works in or studies IT and wants more bacic low level knowledge, cs50 is a such a well thought out course and an amazing start.

You might find parts of the course boring since you know the concepts, but the parts you did not know are so well put together that it is totally worth it!

PS: Doug Lloyd is actually comedy gold!

4 Comments
2024/11/09
11:56 UTC

1

Problem Set 9 Finance

Hello has anybody achieved this problem set ? I can’t get API from IEX as it’s closed now, what should I do ? Any idea ?

1 Comment
2024/11/09
09:56 UTC

2

Expected Exit Code 0, not 1

Problem Set 5: Refueling

Hoping someone with a keener eye can catch this

Check50 keeps returning 'Expected Exit Code 0, not 1'

Not sure where in my code there is an error...

test_fuel.py:

from fuel import convert, gauge
import pytest

def test_convert_values():             # Pytest, when it hits one wrong line, will just flag the overall test wrong -- it won't proceed to decode the other lines
    assert convert("1/100") == 1
    assert convert("99/100") == 99
    assert convert("1/3") == 33
    assert convert(" 3      / 4 ") == 75
    assert convert("4/5/6") == 80      # Potential bug here

def test_convert_exceptions():
    with pytest.raises(ValueError):
        convert("Cat")
    with pytest.raises(ZeroDivisionError):
        convert("1/0")
    with pytest.raises(ValueError):
        convert("X/0")
    with pytest.raises(ValueError):
        convert("4/3")

def test_gauge_values():
    assert gauge(99) == "F"
    assert gauge(1) == "E"
    assert gauge(55) == "55%"
    assert gauge(99.9) == "F"
    assert gauge(0.5) == "E"
    assert gauge(-1) == "E"             # Could be a future bug here

def test_gauge_exceptins():
    with pytest.raises(TypeError):
        gauge("Cat")

fuel.py provided as well

def main():
    user_input = input("Fraction: ")
    print(gauge(convert(user_input)))
    return(gauge(convert(user_input)))


def convert(fraction):
    num_denom = fraction.split(sep="/")
    try:
        x = int(num_denom[0])
        y = int(num_denom[1])
        division = x / y
    except ValueError:
        # print("ValueError")
        raise ValueError
    except ZeroDivisionError:
        # print("ZeroDivisionError")
        raise ZeroDivisionError
        # raise ValueError
    else:
        if x > y:
            # print("Improper Fraction")
            raise ValueError
        # else:
        #     pass
        result = round(division,2)
        percentage = int(result*100)
        # print(percentage)
        return(percentage)


def gauge(percentage):
    if percentage >= 99:
        # print("F")
        return("F")
    elif percentage <= 1:
        # print("E")
        return("E")
    else:
        # print(f"{percentage}%")
        return(f"{percentage}%")


if __name__ == "__main__":
    main()
# convert("1/3")
# gauge(100)
1 Comment
2024/11/09
04:31 UTC

5

What am I doing wrong? (Edges)

https://pastebin.com/kdAfBE40

The code and logic seems fine to me, can’t get my head around the problem.

2 Comments
2024/11/09
03:14 UTC

39

I FINALLY DID IT! I BEAT CAESAR!

I can't show the code but I finally beat it after almost 2 days nonstop coding and raging, I almost gave up, I almost punch my computer

And I needed the duck, so my meta of using the duck less failed as I needed him to almost give me the answer with many tips and guides of how on earth I should make the cypher works, I still need to work on how to learn better

17 Comments
2024/11/09
02:18 UTC

24

I am a total noob. What should I do first CS50 or 100 days of coding by dr Angela wu?

Hey I'm new to programming. What is the ideal path as I'm in my middle teenage. But without stem background.

8 Comments
2024/11/09
00:26 UTC

2

Problem receiving my certificate after completion of the course

Hello, I am having an issue receiving my certificate and I am wondering if anyone else has experienced something similar and what possible solutions there may be so I can receive it.

For context, I originally signed up in 2023 for this course, but got caught up in other projects and tried again starting in 2024. All of the problem sets I did were the 2024x version and I submitted them all to the correct submit link, when I go to my gradebook where I submitted the problem sets and my final project, it says they were marked and the link extension/slug is 2024.

However, after I have submitted my final project and received my marks on it, I went to click the link in the syllabus "Be sure to visit your gradebook at cs50.me/cs50x a few minutes after you submit."
And it tells me " You are not enrolled in the course", but I am enrolled and have been for several months and have already completed every problem set and the final project.

How can this be resolved so I can receive my certificate of completion of the course?

2 Comments
2024/11/08
19:23 UTC

8

Skip CS50 and go straight to CS50 Web?

Hi, I wanted get a view on whether I can skip CS50 and go straight to CS50 Web (Python & JavaScript).

The background is that I actually graduated back in 2006 with a Computer Science degree, during that I learnt Linux, Java, C++ and SQL. Professionally, I started my career as a developer using primarily the Microsoft tech stack (mostly c#, some ASP.net and a fair amount of SQL Server) but never really developed anything for Web. I've had little/no hands on coding over the the last 10 years since I've progressed to more senior leadership positions.

I'm keen to build a web app as a hobby (and was considering using the PERN stack) and came across CS50 Web. What are peoples thoughts on whether I'd be able to go straight to that or whether I'd also need to do the prerequisite CS50?

6 Comments
2024/11/08
13:03 UTC

1

POBLEM WITH CS50 Finance : Internal Server Error 500 each time I try to access index.html

So I don't have any issues accessing all the other html pages I created for this problem set.

However, each time when I login and try to enter the homepage aka index.html, I get Internal server error. When I replace everything I wrote in my index function with the 'return apology("TODO")' I don't have that issue, I just get the cat meme and 400 TODO.

The code I managed to write in app.py after abusing the rubber duck is pretty long so please bear with me. If anyone's willing to help me, I can post what I wrote in the html pages too.

Here's my code :

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

    cash = db.execute("SELECT cash FROM users WHERE username = ?", username=session["username"] )
    total_shares = db.execute("SELECT symbol, SUM(shares) AS total_shares FROM transactions WHERE user_id = ? GROUP BY symbol HAVING total_shares > 0", session["user_id"] )
    return render_template("index.html", cash, total_shares)

@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
    """Buy shares of stock"""

    if request.method =="POST":

        if not request.form.get("symbol"):
            return apology("must provide stock symbol",400)

        if not request.form.get("shares"):
            return apology("must provide number of shares", 400)

        if int(request.form.get("shares")) < 0:
            return apology("must provide a positive integer",400)

    else:
        return render_template("buy.html")

    stock = lookup(request.form.get("symbol"))

    if stock is None:
        return apology("invalid stock symbol",400)

    total_cost = stock['price'] * request.form.get("shares")
    user_cash = db.execute("SELECT cash FROM users WHERE id = ?", id) [0]['cash']

    if total_cost > user_cash:
       return apology("not enough cash", 400)

    db.execute("INSERT INTO transactions (user_id, symbol, shares, price) VALUES (?, ?, ?,?)", id, stock['symbol']
             , shares, stock['price'] )

    db.execute("UPDATE users SET cash = cash - ? WHERE id = ?", total_cost, id)



@app.route("/history")
@login_required
def history():
    """Show history of transactions"""

    user_id = session["user_id"]
    transactions = db.execute("SELECT * FROM transactions WHERE user_id = ?", user_id)
    return render_template("history.html", transactions=transactions)


@app.route("/login", methods=["GET", "POST"])
def login():
    """Log user in"""

    # Forget any user_id
    session.clear()

    # User reached route via POST (as by submitting a form via POST)
    if request.method == "POST":
        # Ensure username was submitted
        if not request.form.get("username"):
            return apology("must provide username", 403)

        # Ensure password was submitted
        elif not request.form.get("password"):
            return apology("must provide password", 403)

        # Query database for username
        rows = db.execute(
            "SELECT * FROM users WHERE username = ?", request.form.get("username")
        )

        # Ensure username exists and password is correct
        if len(rows) != 1 or not check_password_hash(
            rows[0]["hash"], request.form.get("password")
        ):
            return apology("invalid username and/or password", 403)

        # Remember which user has logged in
        session["user_id"] = rows[0]["id"]

        # Redirect user to home page
        return redirect("/")

    # User reached route via GET (as by clicking a link or via redirect)
    else:
        return render_template("login.html")


@app.route("/logout")
def logout():
    """Log user out"""

    # Forget any user_id
    session.clear()

    # Redirect user to login form
    return redirect("/")


@app.route("/quote", methods=["GET", "POST"])
@login_required
def quote():
    """Get stock quote."""

    if request.method == "POST":

        if not request.form.get("symbol"):
              return apology("must provide stock symbol", 400)
    else:
        return render_template("quote.html")

    stock = lookup(request.form.get("symbol"))

    if stock is None:
        return apology("invalid stock symbol",400)
    else:
        return render_template("quoted.html", stock=stock)




@app.route("/register", methods=["GET", "POST"])
def register():
    """Register user"""

    if request.method == "POST":

         if not request.form.get("username"):
            return apology("must provide username", 400)

         if not request.form.get("password"):
            return apology("must provide password", 400)

         if not request.form.get("confirmation"):
             return apology("must provide confirmation", 400)

         if request.form.get("password") != request.form.get("confirmation"):
             return apology("password and confirmation must match", 400)

         hashed_password = generate_password_hash(request.form.get("password"))

         try:
             db.execute("INSERT INTO users (username, hash) VALUES (?, ?)", request.form.get("username"), hashed_password)
         except ValueError:
             return apology("username already exists", 400)

         return redirect("/")

    else:
        return render_template("register.html")


@app.route("/sell", methods=["GET", "POST"])
@login_required
def sell():
    """Sell shares of stock"""

    if request.method == "POST":

        if not request.form.get("symbol"):
          return apology("must provide stock symbol", 400)

        if not request.form.get("shares"):
            return apology("must provide number of shares", 400)

        if int(request.form.get("shares")) < 0:
            return apology("must provide a positive integer",400)


        rows = db.execute("SELECT shares FROM transactions WHERE user_id = ? AND stock_symbol = ?", user_id, stock_symbol)

        if len(rows) == 0 or rows[0]["shares"] == 0:
            return apology("You do not own any shares of this stock", 400)

    else:
        return render_template("sell.html")

    rows = db.execute("SELECT DISTINCT symbol FROM transactions WHERE user_id = ?", user_id)

    return redirect("/")


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

    cash = db.execute("SELECT cash FROM users WHERE username = ?", username=session["username"] )
    total_shares = db.execute("SELECT symbol, SUM(shares) AS total_shares FROM transactions WHERE user_id = ? GROUP BY symbol HAVING total_shares > 0", session["user_id"] )
    return render_template("index.html", cash, total_shares)

@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
    """Buy shares of stock"""

    if request.method =="POST":

        if not request.form.get("symbol"):
            return apology("must provide stock symbol",400)

        if not request.form.get("shares"):
            return apology("must provide number of shares", 400)

        if int(request.form.get("shares")) < 0:
            return apology("must provide a positive integer",400)

    else:
        return render_template("buy.html")

    stock = lookup(request.form.get("symbol"))

    if stock is None:
        return apology("invalid stock symbol",400)

    total_cost = stock['price'] * request.form.get("shares")
    user_cash = db.execute("SELECT cash FROM users WHERE id = ?", id) [0]['cash']

    if total_cost > user_cash:
       return apology("not enough cash", 400)

    db.execute("INSERT INTO transactions (user_id, symbol, shares, price) VALUES (?, ?, ?,?)", id, stock['symbol']
             , shares, stock['price'] )

    db.execute("UPDATE users SET cash = cash - ? WHERE id = ?", total_cost, id)



@app.route("/history")
@login_required
def history():
    """Show history of transactions"""

    user_id = session["user_id"]
    transactions = db.execute("SELECT * FROM transactions WHERE user_id = ?", user_id)
    return render_template("history.html", transactions=transactions)


@app.route("/login", methods=["GET", "POST"])
def login():
    """Log user in"""

    # Forget any user_id
    session.clear()

    # User reached route via POST (as by submitting a form via POST)
    if request.method == "POST":
        # Ensure username was submitted
        if not request.form.get("username"):
            return apology("must provide username", 403)

        # Ensure password was submitted
        elif not request.form.get("password"):
            return apology("must provide password", 403)

        # Query database for username
        rows = db.execute(
            "SELECT * FROM users WHERE username = ?", request.form.get("username")
        )

        # Ensure username exists and password is correct
        if len(rows) != 1 or not check_password_hash(
            rows[0]["hash"], request.form.get("password")
        ):
            return apology("invalid username and/or password", 403)

        # Remember which user has logged in
        session["user_id"] = rows[0]["id"]

        # Redirect user to home page
        return redirect("/")

    # User reached route via GET (as by clicking a link or via redirect)
    else:
        return render_template("login.html")


@app.route("/logout")
def logout():
    """Log user out"""

    # Forget any user_id
    session.clear()

    # Redirect user to login form
    return redirect("/")


@app.route("/quote", methods=["GET", "POST"])
@login_required
def quote():
    """Get stock quote."""

    if request.method == "POST":

        if not request.form.get("symbol"):
              return apology("must provide stock symbol", 400)
    else:
        return render_template("quote.html")

    stock = lookup(request.form.get("symbol"))

    if stock is None:
        return apology("invalid stock symbol",400)
    else:
        return render_template("quoted.html", stock=stock)




@app.route("/register", methods=["GET", "POST"])
def register():
    """Register user"""

    if request.method == "POST":

         if not request.form.get("username"):
            return apology("must provide username", 400)

         if not request.form.get("password"):
            return apology("must provide password", 400)

         if not request.form.get("confirmation"):
             return apology("must provide confirmation", 400)

         if request.form.get("password") != request.form.get("confirmation"):
             return apology("password and confirmation must match", 400)

         hashed_password = generate_password_hash(request.form.get("password"))

         try:
             db.execute("INSERT INTO users (username, hash) VALUES (?, ?)", request.form.get("username"), hashed_password)
         except ValueError:
             return apology("username already exists", 400)

         return redirect("/")

    else:
        return render_template("register.html")


@app.route("/sell", methods=["GET", "POST"])
@login_required
def sell():
    """Sell shares of stock"""

    if request.method == "POST":

        if not request.form.get("symbol"):
          return apology("must provide stock symbol", 400)

        if not request.form.get("shares"):
            return apology("must provide number of shares", 400)

        if int(request.form.get("shares")) < 0:
            return apology("must provide a positive integer",400)


        rows = db.execute("SELECT shares FROM transactions WHERE user_id = ? AND stock_symbol = ?", user_id, stock_symbol)

        if len(rows) == 0 or rows[0]["shares"] == 0:
            return apology("You do not own any shares of this stock", 400)

    else:
        return render_template("sell.html")

    rows = db.execute("SELECT DISTINCT symbol FROM transactions WHERE user_id = ?", user_id)

    return redirect("/")
3 Comments
2024/11/08
12:38 UTC

2

Beyond Introduction

Hello all, I'd like to know whether the online courses offered by Harvard and CS50 team, also offers more advanced courses including those on systems engineering, DSA, Software Development and other things that are covered within CS courses. Or is that to be discovered on one's own? Is there a community wherein people can help newbies figure out the real world applications and the principles and associated technical words that are used? Kindly offer your suggestions if you've been on the same road beyond the realm of CS50.

2 Comments
2024/11/08
12:34 UTC

Back To Top