/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
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?
I checked my gradebook and it said i have missing assignments but I turned them in, why is that?
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!
Does anyone know what cs50 courses are being updated this year other than cs50x? Such as cs50 w, ai, and cyber?
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?
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:
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.
flag
and flag1
are initialized to True
before the loop starts.flag
to False
. However, you don't seem to reset flag
if you find a valid sequence later.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
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
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!
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.
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)
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?
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!
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()
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.
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()
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()
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!
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.
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.
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.
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:
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:
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?
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?
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 ?
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!
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.
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!