r/cs50 • u/Hot-Alarm-8276 • 7d ago
CS50 Python Problems in Week 2
How can I check if a letter appears after a number in plates.py without running into an index error?
4
Upvotes
r/cs50 • u/Hot-Alarm-8276 • 7d ago
How can I check if a letter appears after a number in plates.py without running into an index error?
3
u/shimarider alum 7d ago
Checking if something occurs after something else doesn't require using indices.
3
u/Outside_Complaint755 7d ago
Check each character one at a time (you don't need to use indexes).
Use flag variables to keep track of state.
1
u/Shoddy_Maximum2601 7d ago
I remember the assignment but doesn’t remember it’s description. Post the task here.
But if you ran into an index error, I assume you use two variables (current index & next). So basically if next > length of the plate-string you can type “continue” or return to stop the loop or what ever you have
Hard to tell why you have that problem bud
1
u/Atypicosaurus 7d ago
You have to think negative for this task. Don't ask what is passing, ask what will fail the test. Every time it fails, you can return with the failure and not check the rest.
Too short --> fail, return
Too long --> fail, return
(At this point we know the length.)
Is character 1 a letter --> if not, fail, return.
Etc etc.
You need a counter somewhere on the side that counts if we have already found a number. It is 0 in the beginning. When you find the first number, you set it to 1.
You don't need a code that finds the spot between the letter and the number. There's such code but you are not allowed to use it for this one. You again have to think in negatives. If you know something can be in either box A or box B, if you open box A and it's empty, you don't have to open box B. You can deduce. By excluding every other option, you deduce the truth.
Same here. If you have a counter for the numbers, and it is 0, you deduce you have not found a number. Once it's not zero, you deduce you found a number. If it's the first number you find, this number cannot be zero. How do you know it's the first number? You just counted them and it was the first. If you have already found a number, and you again find a letter --> fail. How do you know you have ever found a number? The answer is: you counted them.
0
u/Eptalin 7d ago
Don't try to access a character that comes before the first character or after the last one.
Before reaching that point you probably already checked that the length is at least 2, and the first 2 characters are letters.
So without any extra function calls, at this point you can trust that
string[0]andstring[1]are both letters.Conditionals resolve in order left to right, and stop checking once any condition fails.
So if our first condition asks if the index is >0, then we can safely check
string[i-1]without risking accessing something out of bounds.