PROBLEM SET 7: NUMB3RS | SOLUTION (CS50 PYTHON)

  Рет қаралды 17,426

Dors Coding School

Dors Coding School

Күн бұрын

Пікірлер: 59
@DorsCodingSchool
@DorsCodingSchool Жыл бұрын
👨‍💻 Learn How to Code with Private Classes - www.dorscodingschool.com/coachingplans ❓Having a hard time with CS50, FreeCodeCamp or Odin Project? Practice with our exclusive free coding platform: www.codingdors.com/ 🎯 Are You A Coding Expert? Take Our Free Quiz and Find Out - www.dorscodingschool.com/quiz
@pieterjdw
@pieterjdw 2 жыл бұрын
Here I am again ;) Maybe make the number regex more strict to accept only numbers with a length of 1-3. Something like `\d{1,3}`
@DorsCodingSchool
@DorsCodingSchool 2 жыл бұрын
This is a good idea! If you want, we have one Telegram Group to help people learn how to code and we can discuss it. Check www.dorscodingschool.com/products
@colmduffy2272
@colmduffy2272 2 жыл бұрын
I posted an approach below. That is a good idea, but only part of what is necessary. Never had to use re before, lots of things to trip over, but, a few things to be aware of. The "|" is your friend. You need several groups of potential numbers in the first set. You need to define these alternatives using brackets. I found the 101 site suggested in the video very helpful. It lets you test and debug. Once you have one pattern figured out, you pretty much have them all except for the tail end of it.
@CaratacusAD
@CaratacusAD 2 жыл бұрын
Word of warning!!! the check50 code is a bit buggy. I constantly got ":( test_numb3rs.py catches numb3rs.py only checking first byte of IPv4 address" error. Nothing wrong with my code at all. I finally got it to pass by trying a number other than 255 in some of my test cases. Nuts huh!!! wasted over an hour, but it's a new course and it's free so i won't complain too much hahaha Looks like Giovanna had the same issue too. Also the RE library has a few quirks. For instance if you want to use quantifiers with groups for example ([0-9]{1,3}) it will only capture the last group, not all three, which is annoying :( So you'll need to split out the expressions/groups. In the end I wrote an uber REGEX where i didn't even need to inspect the groups and test. But i come from a telco background, so i'm pretty familiar with REGEX. Good luck guys
@DorsCodingSchool
@DorsCodingSchool 2 жыл бұрын
Thank you for your comment! By the way, we have a Telegram Group to help people learn how to code and where you can connect with learners from all over the world. Over there you can ask any question about programming and you can easily get your questions answered within 24 hours. Besides that, you will have access to our membership with more than 400 problems made by us to ease your learning curve and 2 hours of group coaching every week! Check www.dorscodingschool.com/products
@JeanJacquesPotgieter
@JeanJacquesPotgieter 2 жыл бұрын
That error means you're only trying to check that the first group of numbers is correct, which is to say you're testing that 355.10.20.30 is False when you should also have a case that checks the other groups, e.g.: assert validate("10.1.355.0") == False. The error isn't saying that anything is wrong with your code, but that test cases are a bit incomplete.
@rafaelparish
@rafaelparish Жыл бұрын
I had this problem too, thank you so much for this hint.
@YallLieBad
@YallLieBad 7 ай бұрын
@@JeanJacquesPotgieter that's super helpful thank you. i didnt think that would matter beacuse im iterating over a list but i see how it might effect someone checking the values as seperate variables x1,x2,x3,x4 or someone maybe checking the whole string at once but not correctly identifying each group or value. super cool i need to get better at understanding edge cases and what might go wrong in all codes not just mine.
@basey456
@basey456 3 ай бұрын
@@JeanJacquesPotgieter Thx, helped
@MehdiHuseynzad
@MehdiHuseynzad 5 ай бұрын
I don't think we should worry about numbers below zero because it would have to have a minus which would not be how the re is coded
@deemon710
@deemon710 2 жыл бұрын
You got me past on of the last checks where I had to check the range for each octet. Thanks!
@DorsCodingSchool
@DorsCodingSchool 2 жыл бұрын
You're welcome! By the way, we have a Telegram Group to help people learn how to code and where you can connect with learners from all over the world. Over there you can ask any question about programming and you can easily get your questions answered within 24 hours. Besides that, you will have access to our membership with more than 400 problems made by us to ease your learning curve and 1 hour of group coaching every month! Check www.dorscodingschool.com/products
@SkySesshomaru
@SkySesshomaru 3 ай бұрын
I have managed to solve this problem my using regex only, but man was that hard, damn. This way is WAY easier and better, I thought about doing it this way but forced myself to practice the regex usage.
@hamayun1112
@hamayun1112 2 жыл бұрын
Is there no way of verifying that the numbers are between 0 and 255 inside the re.search command?
@DorsCodingSchool
@DorsCodingSchool 2 жыл бұрын
I believe there isn't.
@danielp6011
@danielp6011 2 жыл бұрын
There is, I also implemented that one, but it seems like the code50 test fails on that, as they had something different in mind.... I specified as follows: ip_range = "([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])" if match := re.fullmatch(fr'{ip_range}\.{ip_range}\.{ip_range}\.{ip_range}', ip): return True else: return False Therfore, values in each ip_range can be only 0-255, which eliminates the possibility of leading zeros as well. If someone spots an error, I am thankful!
@luanpires1784
@luanpires1784 Жыл бұрын
@@danielp6011 Mine looks pretty much like yours. But I was wondering what if we decide to use f-string and the regex special character {}, for example {m} or {m,n}. I looked up and, to clarify, we need to escape the special character by doubling it, therefore using {{}}.
@who_what
@who_what Жыл бұрын
there is, and i would argue its actually a 'better' solution for learning seeing how this entire lecture is dedicated to regex. might as well implement a solution that completely uses regex for the check.
@kyrylldmytrenko8996
@kyrylldmytrenko8996 2 жыл бұрын
Also possible to execute this using groups() instead of split() like this: ... #check if it's IP patter (digit.digit...) matches = re.search(r"^(\d+)\.(\d+)\.(\d+)\.(\d+)$", ip) #check if group is within 0-255 range if matches: for group in matches.groups(): if int(group)
@vijivarghese9195
@vijivarghese9195 2 жыл бұрын
came here to say this.. I think this is the recommended solution as it is also hinted in the hints of the problem
@marktran8472
@marktran8472 2 жыл бұрын
make sure that the int isn't negative either but that method is just as good i'd say Edit: I think the for loop will be iterating on single digits unless I've done mine incorrectly. Perhaps it's because the .group() is not actually an iterable list and is rather an object
@penteronto
@penteronto Жыл бұрын
You can design this code better if you instead of: for group in matches.groups(): if int(group) 255: return False return True Much more readable in my opinion
@AnhThach-wh6ut
@AnhThach-wh6ut 4 ай бұрын
you realize you cant put sys.exit under return
@Sheng-JuiChang
@Sheng-JuiChang Жыл бұрын
Could anyone help look at the code? the terminal shows the 'invalid syntax' error import re try: if re.search(r'^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$', ip): split_number = ip.split('.') for a in split_number: if a < 0 or a > 255: return False except: return True else: return False
@MrRyuhayabusa12
@MrRyuhayabusa12 Жыл бұрын
Life saver!
@giannisfilippou7460
@giannisfilippou7460 2 жыл бұрын
my solution for numb3rs using the match expression (although i have to admit that your solution with the list is more clever :) ) import re import sys def main(): ad = input("IPv4 Address: ") x = validate(ad) print(x) def validate(ip): if match := re.search(r"^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$",ip): one = int(match.group(1)) two = int(match.group(2)) three = int(match.group(3)) four = int(match.group(4)) if one
@DorsCodingSchool
@DorsCodingSchool 2 жыл бұрын
Great job!
@abdqasrawi
@abdqasrawi 8 ай бұрын
it's much quicker if you use \d instead of [0-9] import re import sys def main(): print(validate(input("IPv4 Address: "))) def validate(ip): if re.search(r"^\d+\.\d+\.\d+\.\d+$",ip): ip=ip.split(".") for number in ip: if 255 < int(number) >0 : return False return True return False if __name__ == "__main__": main()
@andrejg3086
@andrejg3086 5 ай бұрын
you don't need import sys
@vigneshkarthi3321
@vigneshkarthi3321 Жыл бұрын
Hey why can't we use [0-225] ?
@markobondaruk4213
@markobondaruk4213 Жыл бұрын
not sure whether you're still interested in it after 2 weeks, but the answer for this is: *** RegEx interpret it as a character in range from 0 to 2 or 5. *** So basically if there's a 3-4 or 6-9 it won't catch that.
@yuz5185
@yuz5185 9 ай бұрын
I used Try Except to catch any wrong input: def validate(ip): try: if match:= re.search(r"^(.+)\.(.+)\.(.+)\.(.+)$", ip): for i in range(4): ip_number = int(match.group(i+1)) if ip_number not in range(256): raise ValueError return True else: return False except ValueError: return False
@Lukytazcuervo
@Lukytazcuervo 3 ай бұрын
This code will fail if any 'number' in 'list_of_numbers' starts with 0 and has another digit after it. Although int(num) removes redundant zeros, I want the user to write an IP address correctly.
@beibeiliu5510
@beibeiliu5510 2 жыл бұрын
I pass the check test by only using 255 and 512 numbers for test_range part. FYI
@DorsCodingSchool
@DorsCodingSchool 2 жыл бұрын
Great job!
@dries59dep
@dries59dep 6 ай бұрын
thanks for the solution (i have been cursing a whole day , but now i am glad i works).
@penteronto
@penteronto Жыл бұрын
Line 10 of the code: if int(number) < 0 or int(number) > 255: return False int(number) < 0 will always be false so is an unnecessary addition to this if statement. Wonder why? The answer lays in the regular expression. the only thing accepted in the regex is digit or a dot so there won't be any '-' character so it's impossible to get a negative number from it Another thing, else statement at the end is unnecessary too. I say so because the only way to reach the end of the function is by not passing the if statement which automatically means that the ip is wrong It may not be a big of a deal but it results in a shorter code that does less operations which should be ideal goal
@rongarza9488
@rongarza9488 Жыл бұрын
That's right! BUT CHECK50 is a moron. I really wish I had done this class somewhere else. I was going to do AI at HarvardX/edX but there is no way I will put myself through this hell again.
@zaxpeedy
@zaxpeedy Жыл бұрын
very nice approach. here is mine without using a for loop (technically because i'm still telling regex to test it for next parts XD): import re import sys def main(): print(validate(input("IPv4 Address: "))) def validate(ip): # expects an IPv4 address as Input as a str # and then return True or False parts = ip.split(".") if len(parts) > 4: return False try: if re.search(r"(\b25[0-5]|\b2[0-4][0-9]|\b[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}", ip): return True else: return False except: return False if __name__ == "__main__": main()
@Rational_consumer
@Rational_consumer 6 ай бұрын
my solution works perfectly fine and is much shorter: import re def main(): print(validate(input("IPv4 Address: "))) def validate(addy): matches = re.search(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$", addy) if matches and (int(matches.group(1))
@ojasgoyal20
@ojasgoyal20 6 ай бұрын
hi , i made a very similar code just used a for loop but my last 3 checks related to tests are not working .
@Rational_consumer
@Rational_consumer 6 ай бұрын
@@ojasgoyal20 mind sharing both of your codes?
@markobondaruk4213
@markobondaruk4213 Жыл бұрын
re.split() was also a solution. RegEx is not as complicated in this case but the code is slightly larger :) def main(): print(validate(input("IPv4 Address: "))) def validate(ip): # Splits by dot numbers = re.split(r"[.]", ip) # Number of elements should be 4 if len(numbers) != 4: return False # Checks whether number is in range. Also handles the situations where non digits chars were passed to the program try: for num in numbers: if not int(num) in range(0, 256): return False except ValueError: return False # Returns True if passed return True if __name__ == "__main__": main()
@cinthyayotani5319
@cinthyayotani5319 10 ай бұрын
I passed this one without using regex at all. I think my solution in way simpler
@colmduffy2272
@colmduffy2272 2 жыл бұрын
I like these videos, I pick up lots of useful bits an pieces from them. However, I diagree with the approach here, which uses a for loop to do the job that re.search is meant to do. re.search is used for part of the problem, and it does work fine, but, I feel like re.search can be used to complete this without the use of a loop. It is complicated to put it in place, and has taken me a lot of trial and error to figure out, but this is the pattern I was using, repeated the required times. ((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9][0-9])|([0-9]))\. Its a tricky problem for sure, and this comment is not meant to be overly critical, just to highlight that there are a few ways to approach it. Which is best is subjective in many instances, and I really do not want to undermine the value of this video series, its a great resource, very well explained and very worthwhile engaging with. I feel I have improved watching them. Thanks Dors for all your hard work.
@DorsCodingSchool
@DorsCodingSchool 2 жыл бұрын
Thank you for your message! We appreciate your feedback and we will fix our code as you explained :)
@colmduffy2272
@colmduffy2272 2 жыл бұрын
@@DorsCodingSchool thank you ... But, I don't think it's a "fix" ... Just different. Thanks for the content ❤️
@penteronto
@penteronto Жыл бұрын
@@colmduffy2272 While i get your point and also think that completing entire function with one regex would be ideal, notice that you had to verify all possibilities and if the range of those numbers would be bigger than 0-255 you would have to consider even more of those especially if pattern would be sth like #.#.#.#.#...............# and by that i mean very long
@colmduffy2272
@colmduffy2272 Жыл бұрын
@@penteronto As I mentioned, a solution that "works" can take many paths. However, the solution I put through was done with re. It is also worth noting that extending the "what if" beyond the scope of the problem (>255) means your IP address would not be valid. Meaning you are making an accomodation for a failing case. The problems can all be solved with re, and though not required, I think doing so provides a learning opportunity. But that is just my opinion.
@Engr_Abdul_Basit
@Engr_Abdul_Basit 9 ай бұрын
import re def main(): print(validate(input("IPv4 Address: "))) def validate(ip): if re.search(r"^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$", ip): list = ip.split(".") for i in list: num = int(i) if num < 0 or num > 255: return False return True else: return False if __name__ == "__main__": main()
@hamadafridi1017
@hamadafridi1017 Жыл бұрын
My approach is diifferent import re import sys def main(): print(validate(input("IPV4 Address: "))) def validate(ip): if match_ip := re.search(r"^(\d+)\.(\d+)\.(\d+)\.(\d+)$",ip): if int(match_ip.group(1))
PROBLEM SET 7: WATCH ON YOUTUBE | SOLUTION (CS50 PYTHON)
13:19
Dors Coding School
Рет қаралды 14 М.
PROBLEM SET 7: REGULAR, UM, EXPRESSIONS | SOLUTION (CS50 PYTHON)
11:58
Dors Coding School
Рет қаралды 10 М.
The Best Band 😅 #toshleh #viralshort
00:11
Toshleh
Рет қаралды 22 МЛН
Numb3rs -Problem Set 7 (CS50's Introduction to Programming with Python)
15:12
PROBLEM SET 7: WORKING 9 TO 5 | SOLUTION (CS50 PYTHON)
24:49
Dors Coding School
Рет қаралды 24 М.
CS50P NUMB3RS | Python Programming
16:01
The IT Shed
Рет қаралды 762
15 Python Libraries You Should Know About
14:54
ArjanCodes
Рет қаралды 410 М.
Numb3rs Solution CS50P - Problem Set 7
15:31
Simple Easy Python
Рет қаралды 156
I gave 127 interviews. Top 5 Algorithms they asked me.
8:36
Sahil & Sarra
Рет қаралды 684 М.
CS50P - Lecture 4 - Libraries
1:17:29
CS50
Рет қаралды 317 М.
PROBLEM SET 1: MEAL TIME | SOLUTION (CS50 PYTHON)
16:09
Dors Coding School
Рет қаралды 37 М.
«Бақыттың кілті» телехикаясы І 19-бөлім
52:55
Qazaqstan TV / Қазақстан Ұлттық Арнасы
Рет қаралды 492 М.
Полыхание №2
18:58
Metal Family Xydownik
Рет қаралды 908 М.