/r/cs50
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
Status Page
Filter by Problem Flair (undo)
cash ⋅ caesar ⋅ credit ⋅ dna ⋅ filter ⋅ finance ⋅ houses ⋅ ide ⋅ mario ⋅ movies ⋅ plurality ⋅ project ⋅ readability ⋅ recover ⋅ runoff ⋅ scratch ⋅ speller ⋅ substitution ⋅ tideman ⋅ games track ⋅ web track ⋅ android track ⋅ iOS track ⋅
Filter by Other Flair (undo)
CS50-Law ⋅ CS50-Business ⋅ CS50-Technology ⋅ CS50-Games ⋅ CS50-Mobile ⋅ CS50-Web ⋅
/r/cs50
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:
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!
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!
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
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
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.
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
I am getting this error message on week 9 finance. I am getting this back from check50
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!
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
Contact me. Write your college and previous cool projects in the comment section.
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?
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.
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.
I'm just following the seminar on setting up the IDE, and the pip wasn't working
And is computer science as a field still as money making as it was before?
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?
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!
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 ?
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)
The code and logic seems fine to me, can’t get my head around the problem.
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
Hey I'm new to programming. What is the ideal path as I'm in my middle teenage. But without stem background.
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?
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?
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("/")
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.