ALL Python Programmers Should Know This!!

  Рет қаралды 1,923,327

b001

b001

Күн бұрын

Пікірлер: 1 000
@b001
@b001 2 жыл бұрын
Correction: 1 is not prime. My is_prime function is flawed!
@JimMaz
@JimMaz 2 жыл бұрын
You've made a b001 of yourself
@damian4601
@damian4601 2 жыл бұрын
just make nums range(2,1000) to exclude 1 instead of making 999 num!=1 comparison
@careca_3201
@careca_3201 2 жыл бұрын
@@damian4601 or just add another condition, because you might want to use 1 in a non prime numbers list
@thefredster55
@thefredster55 2 жыл бұрын
Couldn't you just set nums equal to 1000 instead of range(1,1000) since you're passing it into a range in the function? (Genuine question, literal n00b here)
@Killercam1225
@Killercam1225 2 жыл бұрын
@@thefredster55 Nope, because it creates an array of numbers in that given range. So the function iterates through each number in the list and and the filter function creates an object, which then he passes the object through the [list] method which puts all of the values contained in that object into a [list] where the output can be comprehended.
@boredd9410
@boredd9410 2 жыл бұрын
Minor thing, but you can make the prime checking function faster by going up to floor(sqrt(n)) instead.
@slammy333
@slammy333 2 жыл бұрын
Could make it even faster by only iterating over odd numbers as well
@programmertheory
@programmertheory 2 жыл бұрын
def is_prime(x): if x < 2: return False if x
@darkfireguy
@darkfireguy 2 жыл бұрын
​@@slammy333 you can make it even faster by only checking n-1 and n+1 where n is each multiple of 6
@sidneydriscoll5579
@sidneydriscoll5579 2 жыл бұрын
def isPrime(x): if x == 1: return False if x == 2: return False if x == 3: return True if x == 4: return False This is what you call fast!
@FuzioN2006
@FuzioN2006 2 жыл бұрын
Why is a youtube comment thread more productive than my work team... FML
@back2710
@back2710 Жыл бұрын
For those concerned for its complexity, remember you can always use sieve of eratosthenes in most cases, this only would be required in case of big numbers
@nagyzoli
@nagyzoli Жыл бұрын
Sieve works for any number, and it is the most optimal way of generating sequences of primes.
@philfernandez835
@philfernandez835 Жыл бұрын
primes = [x for x in range(2, 1000) if isPrime(x)]
@krakenzback7971
@krakenzback7971 Жыл бұрын
yeah cuz 1 is not prime
@BookOfSaints
@BookOfSaints Жыл бұрын
I think his point is to use list comprehension which is the better choice here.
@krakenzback7971
@krakenzback7971 Жыл бұрын
@@BookOfSaints yeah this is list comprehension
@BeasenBear
@BeasenBear Жыл бұрын
It says "isprime" or "Prime" is not defined when I tried this code. What did I miss?
@ItzMeKarizma
@ItzMeKarizma 11 ай бұрын
@@BeasenBear kinda late but he's calling a function called isPrime and you probably didn't define that function (I don't know if it's supposed to be imported or written by yourself, I use C++).
@sinterkaastosti988
@sinterkaastosti988 4 ай бұрын
primes=[ n for n in range(2, 1000) if all(n%x for x in range(2, int(n**0.5))) ]
@nickm.4274
@nickm.4274 13 күн бұрын
Yes, but the point of this isn't for is_prime. If you have a complex function, doing the video's way would be a lot more readable
@brianhull2407
@brianhull2407 11 ай бұрын
A better is_prime function would be: def is_prime(num): if num == 1 or num == 0: return False for x in range(2, floor(sqrt(num))): if num % n == 0: return False return True This does three things. First, it factors in the fact that 1 is not prime. (It’s neither prime nor composite.) Second, it accounts for the fact that 0 isn’t prime either (as 0 is highly composite, having literally every integer as a factor). And third, it increases the speed of the function since it only needs to go to the square root of the number. This works because every composite number has at least one factor that is greater than 1 and less than or equal to its square root. Indeed, given any integer x such that x > 1, for every factor _a_ of x that is less than √x, there is exactly one other factor _b_ of x that is greater than √x such that _a_ × _b_ = x. (For 1, it has exactly one factor (itself), and its lone factor is also its square root. For 0, it has infinite factors (everything), but its square root (itself) is less than all other whole numbers.) Incidentally, if num is less than 2, then both range(2, num) and range(2, floor(sqrt(num))) will return an empty iterable that will cause the body of the for loop to never be executed. As such, any value for num that is less than 2 will return True for the original version of is_prime, and any value for num that is less than 0, between 0 and 1, or between 1 and 2 will return True for my version of is_prime. We could add a check for nonintegers: if num != floor(num): return False However, that isn’t strictly necessary, since the input should be an integer, and in Python, we assume the developer would not put a fraction into the function. And it’s not like the code would throw an error in such a case, anyways. The better question is with regards to negative numbers. There are four ways to consider this. First, we could just assume that the developer would never input a negative number. This is fine… unless we’re getting input from a user, in which case either the developer or the function should do a check. The second way is to treat all negative numbers as composite on the grounds that they each have at least three factors: 1, itself, and −1 (where we only include −1 as a factor if the number itself is negative), and prime numbers must have exactly 2. In that case, our first conditional would instead be: if num == 1 or num
@tyrigrut
@tyrigrut 11 ай бұрын
As a mathematician, #3 and #4 are the correct options here. Either you're working over positive integers, in which case you should throw an exception if negative, or you are working over all integers, which you can use the general definition of a prime element over a commutative ring: p is prime if p is non zero, p is not a unit (here a unit is 1 or -1), and if p=a*b for a and b integers then either p divides a or p divides b. You can see based on this definition that 6 is not a prime: 6=2*3 but 6 does not divide 2 or 3 evenly (i.e. 2/6 and 3/6 are not integers). Similarly for (-6)=(-2)*3, so -6 is not prime. And for positive primes p, we must have p=(±1)*(±p), and p divides ±p. Similarly, -p=(∓1)*(±p), and -p divides ±p. So p is prime is equivalent to saying -p is prime. Notice that over all integers, all primes p have 4 factors: 1, -1, p, -p. It is incorrect to assume all primes have 2 factors, otherwise the only primes over the integers would be 1 and -1.
@brianhull2407
@brianhull2407 11 ай бұрын
@@tyrigrut Thank you for your input! I was unaware of how primes work under anything other than nonnegative integers, so I wasn’t aware of the “four factor” definition. I figured there probably _was_ something, though. That said, it is worth noting that, in computing, we don’t always want perfect mathematical accuracy. Sometimes, we prefer speed over accuracy.
@tree_addict280
@tree_addict280 4 ай бұрын
but its almost as if when trying to explain a topic you use the most relative and easy things to understand.
@Boltkiller96
@Boltkiller96 3 ай бұрын
you wrote the whole documentation for this function hats off!
@surrixhd9846
@surrixhd9846 Ай бұрын
I have been learning python for a while now. And this is the first random short on python i actually understood and would pe capable of replicating. I love this feeling
@foxerity
@foxerity Жыл бұрын
my man actually made the least efficient function in the history of functions
@chervilious
@chervilious Жыл бұрын
Not only that, it's also wrong
@chemma9240
@chemma9240 Жыл бұрын
😂
@rkidy
@rkidy 11 ай бұрын
Crazy that when doing a demonstration you focus on ease of understanding the concept rather than efficient of an algorithm unrelated to what he is demonstrating 🤯🤯🤯
@fruitguy407
@fruitguy407 11 ай бұрын
False, I can and do write worse code with more flaws. You're welcome.
@ImThatGuy000
@ImThatGuy000 10 ай бұрын
im new to python, could you explain why?
@aciddev_
@aciddev_ 2 жыл бұрын
"all python programers should know this: pep-8" when
@yujielee
@yujielee 2 жыл бұрын
💀💀💀
@feDUP1337
@feDUP1337 2 жыл бұрын
So damn true
@Cristobal512
@Cristobal512 Жыл бұрын
What is that?
@vorpal22
@vorpal22 Жыл бұрын
@@Cristobal512 PEP-8 consists of the Python recommended standards and best practices.
@Shaman-h3k
@Shaman-h3k 10 ай бұрын
Pep8 is just for jealous and mean programmers..... It just unreadable
@AndrewMycol
@AndrewMycol Жыл бұрын
Even as a junior web developer, I really like how you do these shorts. It concisely and simply explains whats going on in the shorts.
@b001
@b001 Жыл бұрын
Thanks so much! Glad you enjoy!
@originalbinaryhustler3876
@originalbinaryhustler3876 Жыл бұрын
​@@b001 keep these shorts coming ❤❤❤❤
@prouddesk6577
@prouddesk6577 10 ай бұрын
His code is horrible. I am sorry but dont watch this guy.
@reef2005
@reef2005 2 жыл бұрын
For a relatively large number, the isprime func will take a long time to return true or false. Instead of checking every integer
@alexwhitewood6480
@alexwhitewood6480 2 жыл бұрын
Previous primes upto square root of nums*
@reef2005
@reef2005 2 жыл бұрын
@@alexwhitewood6480 yes indeed
@Siirxe
@Siirxe 2 жыл бұрын
You can also do primes = [i for i in list(nums) if is_prime(i)]
@kazzaaz
@kazzaaz 2 жыл бұрын
this is the way it should be done
@danielf5393
@danielf5393 2 жыл бұрын
You don’t need to cast to list (and you shouldn’t if nums is a long generator)
@kazzaaz
@kazzaaz 2 жыл бұрын
​@@danielf5393 For long inputs or generators, another generator also outperforms map/filter pipeline. gen = (i for i in list(nums) if is_prime(i)) for x in gen: print(x)
@danielf5393
@danielf5393 2 жыл бұрын
@@kazzaaz hence prime_generator = ( i for i in nums if is_prime(i) ) I’m complaining about “list(nums)” specifically.
@hrocxvid
@hrocxvid Жыл бұрын
This was the first thing I thought of
@ubiabrail6773
@ubiabrail6773 Жыл бұрын
Sieve of Eratosthenes is much better for this , but only if u need nums from 1 sieve works with O(n) in spite of this which works withO(n*sqrt(n))
@vorpal22
@vorpal22 Жыл бұрын
Doesn't this actually run in O(n^2) since for a prime number, he's checking up to n-1 instead of sqrt(n)? Agreed that Sieve of Eratosthenes is the way to go, and it's a really easy algorithm to understand.
@МаксимФомин-у4ф
@МаксимФомин-у4ф 5 ай бұрын
​@@vorpal22 yes
@BeasenBear
@BeasenBear Жыл бұрын
I tried your code and it worked! I'll check your channel for more!
@rutabega306
@rutabega306 Жыл бұрын
Okay that time complexity tho
@TheG7
@TheG7 Жыл бұрын
Ikr, it would’ve help to use the root of num but still
@moy92
@moy92 Жыл бұрын
newbie here, how would you improve? i thought list comprehensions but dont know ways improve on time complexity
@rogerab1792
@rogerab1792 Жыл бұрын
​@@moy92 memoization
@rutabega306
@rutabega306 Жыл бұрын
@moy92 There are a few ways you can reduce the time complexity because the one in the video is so suboptimal (quadratic time) You can bring it down to O(Nsqrt(N)) by just checking for factors below the square root. But since we are already collecting a list of primes, we can use some kind of sieve algorithm (look up Sieve of Eratosthones on wikipedia). This will be O(NloglogN) or even less depending on the algorithm.
@TheG7
@TheG7 Жыл бұрын
you don't even need if statements to find prime numbers
@leszekkalota2407
@leszekkalota2407 Ай бұрын
In line 5, you can use for x in range(2, num/2). You don't need to check number bigger than the half.
@KillToGame
@KillToGame Жыл бұрын
scientists: use powerful computers to find new primes me: types infinity intead of 1000
@raiyanfahmid
@raiyanfahmid 2 ай бұрын
nums=range (1,1000) def is_prime(num): for × range(2,num): if(num%×) == 0: return False return True primes=list(filter(is_prime,nums)) print (primes)
@salvatorearpino9243
@salvatorearpino9243 2 жыл бұрын
I usually prefer the list comprehension method instead of filter ie: [n for n in nums if is_prime(n)]
@arjundureja
@arjundureja 2 жыл бұрын
List comprehension is also faster since. you don't need to convert it back to a list
@salvatorearpino9243
@salvatorearpino9243 2 жыл бұрын
@@codeman99-dev timing performance was pretty similar between the two methods. When you check out the disassembled python bytecode (using the dis module), list comprehension has more operations with the python interpreter, so it will most likely not be preferable for code that uses multiple threads (it's more susceptible to global interpreter lock slowing it down)
@vorpal22
@vorpal22 Жыл бұрын
List comprehensions are faster, and in this case, a generator would be even better. Both map and filter are discouraged in Python 3.
@rohakdebnath8985
@rohakdebnath8985 Жыл бұрын
Sieve of Eratostenes where you take a vector bool of all trues, then you start a loop from i²(i = 2 to √N) and flag all the multiples in the vector. The position of the trues left in the vector are all the prime numbers till N. This is simpler shorter and well known.
@AWriterWandering
@AWriterWandering 2 жыл бұрын
Alternatively, you can use a conditional within a list comprehension: [ n for n in nums if is_prime(n) ]
@HussamHadi
@HussamHadi 2 жыл бұрын
This is the correct pythonic way of solving it. Avoid using filter whenever possible
@e1ke1k96
@e1ke1k96 2 жыл бұрын
Or even : [n for n in nums if n%2==0]
@nullopt5174
@nullopt5174 2 жыл бұрын
@@e1ke1k96 that’s not how you define a prime number.
@patrickcuster2348
@patrickcuster2348 2 жыл бұрын
The tradeoff is that a list comprehension is going to store the whole list in memory while filter keeps it as a generator until needed. Both are pythonic and have their uses
@AWriterWandering
@AWriterWandering 2 жыл бұрын
@@patrickcuster2348 yes, but in the video he used to list function, so a list was the intended output anyway.
@rubenvanderark4960
@rubenvanderark4960 10 ай бұрын
``` from math import floor, sqrt def is_prime(x): if x==1: return False for i in range(floor(sqrt(x)): if x%i == 0: return False return True ```
@Rando2101
@Rando2101 5 ай бұрын
The range should be range(2, floor(sqrt(x))+1) tho
@wiccanwanderer82
@wiccanwanderer82 2 жыл бұрын
You only need to check if it's divisible by smaller primes.
@alpacalord507
@alpacalord507 Жыл бұрын
But than you need to have a list with primes, so this does not really help
@thesnakednake
@thesnakednake Жыл бұрын
@@alpacalord507 You can build the list as you go; if you let the is_prime function take the existing prime list into account, you can just append new primes you find until you reach the end of the range. However, you can only do this when you’re making the list in order from 2 like this, since you wouldn’t have all the prior primes otherwise
@alpacalord507
@alpacalord507 Жыл бұрын
@@thesnakednake And? That's still not solving the problem of checking if a number is prime. You're making a list of primes now, which does not (really) help us checking if a number is prime.
@dfsgjlgsdklgjnmsidrg
@dfsgjlgsdklgjnmsidrg Жыл бұрын
@@alpacalord507 u stupid but your profilpic is meliodas so im not mad
@thesnakednake
@thesnakednake Жыл бұрын
@@alpacalord507 The task in the video is to make a list of the primes from 1 to 1000, not just to check if a number is prime. The function that checks it in this video is a means to an end, not the end goal
@Naturescenario507
@Naturescenario507 25 күн бұрын
Must admit that im a little mad that this didnt show up when i needed it but this tips are very cool and informative
@Tomyb15
@Tomyb15 2 жыл бұрын
I would use a generator function to generate a (possibly infinite) sequence of primes by keeping a record of all previously found primes and checking if the next number is divisible by any of those (that should all be smaller than the number) in order. Uses a tiny bit more memory but cuts down on a lot of division operations.
@jaserogers997
@jaserogers997 Жыл бұрын
Using a sieve (if you had an upper limit) would be faster than that.
@plaskut
@plaskut Жыл бұрын
generator with sieve
@OMGclueless
@OMGclueless 9 ай бұрын
@@plaskut It's possible to make an infinite generator with a sieve but it's actually pretty complicated. The sieve by default marks all multiples of a prime the first time you encounter that prime, which is impossible if the generator is infinite. Instead you'd need to suspend and then resume the markings later as you advance through the generator, which is possible but pretty tricky to get right.
@plaskut
@plaskut 9 ай бұрын
@@OMGclueless I think I might try doing this. I believe it's a divergent function, so at some point it might have to check to see if the universe has ended yet.
@stareSimulVelCadere
@stareSimulVelCadere 6 ай бұрын
getting more and more declarative, love it
@uselessschmuck190
@uselessschmuck190 Жыл бұрын
Dude makes me wanna get programing socks and learn python
@TheSkepticSkwerl
@TheSkepticSkwerl Жыл бұрын
This also 100% explains why functions are amazing. Return is better than break.
@user-th2cp8uh8r
@user-th2cp8uh8r 2 жыл бұрын
I must admit that I'm a little mad that this didn't show up when I needed it but this tips are very cool and informative!
@Dmitrii-q6p
@Dmitrii-q6p Жыл бұрын
open book
@DeepFriedOreoOffline
@DeepFriedOreoOffline Жыл бұрын
This is really awesome! I was making a program the other day and I kept getting a similar return to the one you show at the end there and had no idea what was going on! Life saver!
@しめい-l4m
@しめい-l4m 6 ай бұрын
so if you had a list from 1 to 1000... *proceeds to show a list from 1 to 999
@marcelovcoutinho
@marcelovcoutinho 3 ай бұрын
nums = range(1, 1000) def is_prime(number): if number < 2: return False for divisor in range(2, int(number ** 0.5) + 1): if number % divisor == 0: return False return True
@newsjuice7404
@newsjuice7404 2 жыл бұрын
I love python even more bcoz of you. You are absolutely amazing thanks & keep uploading such clips
@vorpal22
@vorpal22 Жыл бұрын
He's not teaching you modern Python practices. You should not use filter and map in Python 3.
@BlastinRope
@BlastinRope 2 ай бұрын
nums = [2] + list(range(3,1000,2)) def is_prime(n): for i in range(3, (n**(1/2)).__floor__() + 1, 2): if n%i==0: return False return True primes = [p for p in nums if is_prime(p)]
@zay1649
@zay1649 2 жыл бұрын
bro what is that vscode theme its so nice
@hezztia
@hezztia 2 жыл бұрын
It's "SynthWave '84" from Robb Owen. It has an option (called "neon dreams") that makes the letters glowy, but i don't use it because i don't like it.
@Matias-rx1wk
@Matias-rx1wk Жыл бұрын
@@hezztiafont?
@leosteiner1161
@leosteiner1161 Ай бұрын
The code only provides all odd numbers. Heres a corrected version: nums = range(1, 1000) def is_prime(num): if num < 2: # Handle edge cases return False for x in range(2, int(num**0.5) + 1): # Check divisors up to the square root of num if (num % x) == 0: return False return True primes = list(filter(is_prime, nums)) print(primes)
@davesharp5472
@davesharp5472 Жыл бұрын
Props to you for making videos where you know that 90% of the comments will be “well actually….” Or some other form of telling you how you are wrong and should have done it their way.
@davesharp5472
@davesharp5472 Жыл бұрын
​@Harrod Thou Thanks for chiming in. Id say its more ironic you dont view comments like "Thanks for teaching job applicants to not format their code properly and also use a less readable alternative of list comprehensions." as negative. I'm offering support to b001 and props for sticking his neck out there. This field particularly is filled with people who love nothing more than to correct people, not too dissimilar to your response to me. See Stack Overflow for example. Have a good day.
@zhairewelch8291
@zhairewelch8291 Жыл бұрын
@Harrod Thou the neg comments are there, it just doesn’t take up 90% of the comment section.
@Pharisaeus
@Pharisaeus Жыл бұрын
Not sure if it's such a great idea. I personally always report such videos, eg. as "misinformation" and choose for them to not be recommended any more.
@oustted
@oustted Ай бұрын
I’ve been trying to learn python so this is nice to know I’m still trying to figure something out much out
@skylo706
@skylo706 20 күн бұрын
Thats normal, the basics are the hardest to learn when starting out. After that it gets easier, trust me :)
@schlopping
@schlopping 2 жыл бұрын
Great example of what the filter class does, but when converting to other datatypes you should use that specific class's comprehension. Example: print([number for number in range(1000) if is_prime(number)])
@MewingStreak31
@MewingStreak31 2 ай бұрын
For anyone confused, the weird object number thing is called OOP, Objected Oriented Programming, which Python is built from. In order to print something it must be an iterable, and making it a list allows such.
@llollercoaster
@llollercoaster Жыл бұрын
Beautiful exponential time complexity
@lawnjittle
@lawnjittle Жыл бұрын
It's quadratic, not exponential
@llollercoaster
@llollercoaster Жыл бұрын
@@lawnjittle good catch. you're right
@mistermiggens5555
@mistermiggens5555 Жыл бұрын
Def getPrimes(array): ReturnVal = [] For I in range(len(array)): If math.sqrt(array[i]) == int(math.sqrt(array[i])): ReturnVal.append(array[i]) Return ReturnVal
@Jwellsuhhuh
@Jwellsuhhuh Ай бұрын
use lst, L, or myList instead
@mhmd_old7
@mhmd_old7 2 жыл бұрын
Map function easier?
@tinahalder8416
@tinahalder8416 2 жыл бұрын
I was also thinking the same
@natelance6713
@natelance6713 11 ай бұрын
If you're going to immediately turn it back into a list, don't use filter, use a list comprehension because it's faster. If you only need an iterator, then use filter.
@AndoroidP
@AndoroidP Жыл бұрын
Just use Sieve of Eratosthenes, get better time complexity of O(nloglogn)
@SegFaultMatt
@SegFaultMatt Жыл бұрын
That’s the way I’d do it. Much better than this method, sad your only upvote is me.
@NathanSMS26
@NathanSMS26 Жыл бұрын
The prime thing was just an example to show off the filter function
@jackomeme
@jackomeme Жыл бұрын
Combine that with memorization, you can reduce the big O
@Rando2101
@Rando2101 5 ай бұрын
​@@jackomeme I'm late, but how? I can't really see it
@Kr1sc0s
@Kr1sc0s 14 күн бұрын
def is_prime(num): for x in range(2, num): if (num % x) == 0: return False return True def sieve_of_eratosthenes(limit): sieve = [True] * limit sieve[0] = sieve[1] = False # 0 and 1 are not prime numbers for start in range(2, int(limit ** 0.5) + 1): if sieve[start]: for multiple in range(start * start, limit, start): sieve[multiple] = False return [num for num, is_prime in enumerate(sieve) if is_prime] limit = 100 primes = sieve_of_eratosthenes(limit) print(primes)
@lordfirespeed
@lordfirespeed 2 жыл бұрын
Nice demo of filter(). In reality one should use the Eratosthenes' sieve to obtain large lists of primes in python
@Rugg-qk4pl
@Rugg-qk4pl 2 жыл бұрын
In double reality one should download a large list of primes
@GordieGii
@GordieGii 2 жыл бұрын
Is that because it takes less time, less ram, fewer lines of code, or is easier to understand?
@Rugg-qk4pl
@Rugg-qk4pl 2 жыл бұрын
@@GordieGii Sieve is going to be significantly faster, but more lines of code. Not sure on the memory usage. But as long as it's clear you are implementing the sieve, difficulty to understand shouldn't be an issue.
@GordieGii
@GordieGii 2 жыл бұрын
@@Rugg-qk4pl That makes sense. The original video said that one objective was to save memory. Since range is an itterable, it only produces the next number and returns it to filter so the list only ever contains the primes. To do Eratosthenes' sieve you need to have all the numbers in the list and then prune them. I suppose you would only need a bool or a bit for each number, but then you would need bit handling routines. Probably already libraries for that sort of thing.
@newgamingchannel6805
@newgamingchannel6805 Жыл бұрын
Thank you. I love your channel
@unknownman6978
@unknownman6978 Жыл бұрын
we have all of the prime numbers 1, 2, 3 💀💀
@-sn4k3-94
@-sn4k3-94 Жыл бұрын
It’s prime, what’s wrong?
@finnyass1407
@finnyass1407 Жыл бұрын
@@-sn4k3-94 1 isn’t a prime number tho
@asi3136
@asi3136 Жыл бұрын
​@@finnyass1407argument of semantics, it's generally not considered a prime but the arguments are vibes
@alensoftic7227
@alensoftic7227 28 күн бұрын
Upper limit of sqrt(num) is sufficient when looping, which i find very interesting. Also, you can only loop through the odd numbers if num is not even - which you can check before the loop in is_prime function and return False immediately.
@Lurkartiist
@Lurkartiist Жыл бұрын
I want to learn to code but it’s intimidating tbh . I’m no genius . Not gonna let that stop me from going for it though 💯
@AbdulRehman-rf2cc
@AbdulRehman-rf2cc Жыл бұрын
less gooo
@bonquaviusdingle5720
@bonquaviusdingle5720 Жыл бұрын
it has a steep learning curve in the beginning but gets very easy, like learning to drive a car
@jimgorycki4013
@jimgorycki4013 11 күн бұрын
I took a few of the poster's example, as well as @b001 and tweaked the code so it is a function. I have taken a course called python for network engineers, so this may be a novice approach. I have done this program in the past in Pascal and C (yeah I know I old) import math def is_prime(num): if num == 1 or num == 0: return False for n in range(2, int(math.sqrt(num))+1): if num % n == 0: return False return True for x in range (1,100): num = int(x) test = is_prime(num) if (test): print(num, " is a prime number")
@tpd_
@tpd_ 2 жыл бұрын
Print(list(filter(list(map(lambda x: x is not any([x%y==0 for y un range (2,x)]), [i for i in range (1000)])))))
@RayTracingX
@RayTracingX 11 ай бұрын
Imao😮
@heoungminkim1108
@heoungminkim1108 5 ай бұрын
Bro, You are truly pythonic. :)
@Rando2101
@Rando2101 5 ай бұрын
Imagine changing x%y==0 to (not x%y) tho
@gellirollz
@gellirollz Ай бұрын
Prefect and easy to follow
@FirstnameLastname-rl4qi
@FirstnameLastname-rl4qi 2 жыл бұрын
Could be more efficient, when checking for a prime you only have to check for factos up too the square root of the number, so if you square root the high end of the range it should work faster!
@andrewfischer-garbutt2867
@andrewfischer-garbutt2867 6 ай бұрын
"A prime number (or a prime) is a natural number greater than 1 that is not a product of two smaller natural numbers." -- Wikipedia page for prime numbers. You need to make sure x > 1 in your is prime function. Although I suppose the point of the video is to illustrate the use of filter function and not to go into the details of what a prime number is.
@monolith-zl4qt
@monolith-zl4qt 6 ай бұрын
this is not how you would search for primes in a real scenario. first and foremost, you'd start with C..
@looknom2567
@looknom2567 6 ай бұрын
the x > 1 is the edge case that wasn't considered in the video. in python the sieve of eratosthenes is better/faster. i do know for python large chunks of it are just c under the hood
@eck1997rock
@eck1997rock 2 жыл бұрын
Thanks for teaching job applicants to not format their code properly and also use a less readable alternative of list comprehensions.
@archigan1
@archigan1 2 жыл бұрын
beat me to it
@kaniran1
@kaniran1 2 жыл бұрын
Was looking for the list comprehension answer :-D
@johnr3936
@johnr3936 Жыл бұрын
Actually terrible way to write python. Do you think its just bait? I would not merge that
@the_lava_wielder6996
@the_lava_wielder6996 Жыл бұрын
Bro you guys unironically code in python it doesn't matter anyways
@eck1997rock
@eck1997rock Жыл бұрын
What should we use sensei?
@75424ht
@75424ht Жыл бұрын
Thanks man you're the best!
@marcelchukwuma9655
@marcelchukwuma9655 Жыл бұрын
Using list comprehension for this would be more pythonic
@wintur2856
@wintur2856 Жыл бұрын
I hate list comphrensions
@Rando2101
@Rando2101 5 ай бұрын
​@@wintur2856seems like changing programming language is the best option for you.
@complexity8851
@complexity8851 Ай бұрын
You can optimize it more by just checking odd numbers in the range, because even numbers will always be divisible by 2. Or maybe you can just generate odd numbers in a range
@bl4z3_kanazaki
@bl4z3_kanazaki 2 жыл бұрын
Sheesh nice trick my friend!!
@gingeral253
@gingeral253 Жыл бұрын
You can also remove checks by going up to the square root of the value because anything past that would a repeat of something already checked.
@tubefile100
@tubefile100 2 жыл бұрын
Pythons freedom to not declare variables and data types makes me appreciate Java.
@tinahalder8416
@tinahalder8416 2 жыл бұрын
Huuhhh? Ur word confuses me wise man
@eazyg885
@eazyg885 2 жыл бұрын
@@tinahalder8416 in Java you have to specify the type of a variable when declaring it (String, int, char) which cannot be changed afterwards, while in Python the type of a variable is dynamic (i.e. it changes based on the input). This makes it easier to make mistakes if you’re not paying enough attention
@gJonii
@gJonii 2 жыл бұрын
@@eazyg885 Python has type hints though. You can get some of the benefits of statically typed languages from having them present. But yeah, lack of proper static typing support, and lack of immutability as an option, are to me the two biggest weaknesses in the language. Third weakness kinda being the dependency management.
@revenevan11
@revenevan11 Жыл бұрын
I'm just learning python, thanks for showing me the filter function!
@asdanjer
@asdanjer 2 жыл бұрын
People using pandas: 😂🤣
@BlackLightning0Games
@BlackLightning0Games Жыл бұрын
Make the range go to the sqrt(num) instead of num, because that is the max you can go without the smallest and largest of the multiples switching. To check is 49 is prime, you only have to check up to 7 because 7*7 = 49 This changes from o(n) to o(sqrt(n)) If you can do this it will save you on at least one coding interview.
@zackm2299
@zackm2299 Жыл бұрын
I had to code that in assembly once
@Jakku_Azzo
@Jakku_Azzo Жыл бұрын
Had to code it in brain fuck the other day *cracks knuckles* R/iamverysmart
@pound9799
@pound9799 5 күн бұрын
Another fucking thing to memorize thank you
@ayecaptainjack6930
@ayecaptainjack6930 2 жыл бұрын
If you wanna use filter, go back to JavaScript! Pythonic would be, to use a list comprehension.
@FatahChan
@FatahChan 4 күн бұрын
If you need a list of primes up to x, using a sieve function might be more performant
@Luther_Luffeigh
@Luther_Luffeigh 2 жыл бұрын
Please don’t stop making shorts, your shorts content is the best I have seen 🙌🏽
@roiqk
@roiqk 2 жыл бұрын
Then you have seen nothing
@reminderIknows
@reminderIknows 3 ай бұрын
primes = list(filter(lambda x: len([i for i in range(2, x) if x % i == 0]) == 0, range(2, 1000)))
@GoofyGoober6694
@GoofyGoober6694 Жыл бұрын
🤓*snorts* actually, you should have set the range to 1,1001 to print out the entire 1000 numbers instead of 999
@GoofyGoober6694
@GoofyGoober6694 Жыл бұрын
@@MCRuCr it's ironic
@MCRuCr
@MCRuCr Жыл бұрын
@@GoofyGoober6694 ok my bad its hard to tell.. there are just so many people complaining about his method of prime computation when in fact it is about the python language instead of a specific problem you can solve with it
@thetroiimaster
@thetroiimaster 19 күн бұрын
You can cut the time down by about 65% if you use the range: range(3, floor(sqrt(num)), 2). You just need to add a case for dividing by 2. This only checks odd numbers, dividing the whole thing by 2, and only going up to the sqrt of that number, which I won't explain here why that is the upper limit. To find how much faster it is, calculate this: (sqrt(2)/2)*0.5, or trust me bc it equals about 0.35, or 65% faster.
@maximebeauchemin2100
@maximebeauchemin2100 2 жыл бұрын
This is terribly inefficient lol. You should just Calculate all the prime numbers ahead of time instead of calling this function for every number. Even with that slow function it'd be O(n^2) instead of O(n^3)
@b001
@b001 2 жыл бұрын
Thanks for the feedback! You're totally right, but the main point of the video was to show what the filter function does.
@maximebeauchemin2100
@maximebeauchemin2100 2 жыл бұрын
@@b001 fair enough
@aroop818
@aroop818 2 жыл бұрын
Hi mate, I am new to Python. Could you please explain how we can calculate primes ahead of time? Like applying modulo to the list of numbers of a specific range then appending them to a list and printing it? Please correct me if I’m wrong
@RazeVX
@RazeVX Жыл бұрын
Love to see a beginner friendly version of this codeing practice because I know how it looks after generations of programmer optimized the shit out of it in countless different languages since primes are essential for cryptography 😅
@xgorntv
@xgorntv 4 ай бұрын
thanks for the tips!
@nobodyofconsequence6522
@nobodyofconsequence6522 5 ай бұрын
personally I'd use a list comprehension myself primes = [num for num in range(0,1000) if is_prime(num)] print(primes)
@zakzak24
@zakzak24 Жыл бұрын
wow filter function is a time saver, before I used to go for the slower solution : for num in nums: if is_prime(num): print(nums[num]) else: continue ty for the vid🎉
@PriestPoppy
@PriestPoppy 2 жыл бұрын
You can also do: primes = [x for x in nums if is_prime(x) == True] And this will output a list of prime numbers without needing to convert it (if you instantly need to use the list and not the object)
@gavinhofer4588
@gavinhofer4588 2 жыл бұрын
You don’t need the == True
@PriestPoppy
@PriestPoppy 2 жыл бұрын
@@gavinhofer4588 you're right! my bad
@Nikhil-Tomar
@Nikhil-Tomar Жыл бұрын
You could also use primes = [x for x in nums if is_prime(x)]
@sven179
@sven179 Жыл бұрын
I was about to comment 1 is not prime and you only need to check up to the square root of a number to check if it’s prime. I was happy to see others already said this.
@philfernandez835
@philfernandez835 Жыл бұрын
square root + 1 right?
@sven179
@sven179 Жыл бұрын
@@philfernandez835 No, only up to the square root (and including it in the case that it happens to be an integer), but square root + 1 is completely unnecessary. The argument is as follows: suppose a number has no prime divisors
@ryugane243
@ryugane243 17 күн бұрын
For increased readability, you should prefer a list comprehension instead of the filter method primes = [x for x in nums if is_prime(x)]
@tvpremieratozseries173
@tvpremieratozseries173 5 ай бұрын
Thanks for helping
@andreydoroshenkov5123
@andreydoroshenkov5123 Жыл бұрын
primes = filter(lambda num: all(num%x != 0 for x in range(2,num)), nums)
@josgibbons6777
@josgibbons6777 Жыл бұрын
With the Sieve of Eratosthenes, you don't judge each number like that: you create a list of bools you update to eliminate multiples of whatever's still prime. It's more efficient.
@oreoforlife720
@oreoforlife720 8 ай бұрын
Alternative way that is much easier to remember: condition list comprehension
@Xiaika
@Xiaika Жыл бұрын
You can massively improve performance of finding primes by searching between 2 and sqrt(n) since if we have two integers x and y such that n = x*y then it’s not possible for both x and y to be greater than the sqrt(n).
@richardchurchill5181
@richardchurchill5181 Жыл бұрын
You do not need to check numbers from 2 to num. No divisor of greater than the square root of num needs to be checked if you check those less than that square root.
@why_notO
@why_notO 3 ай бұрын
You can shorten the function if the range is num//2+1
@PabloEscobarmitzvah
@PabloEscobarmitzvah Жыл бұрын
Good to check the potential factors twice to ensure we can display a nice "Loading..." screen 😊but in case you're looking for efficiency you could start by checking up to sqrt(n), because I'm pretty sure a*b = b*a for integers so if one of the factors is > sqrt(N), the other will for sure have to be below sqrt(N) and we can stop the primality check. I think you'd better show the use of a library rather than careless "tricks"
@davidmachado132
@davidmachado132 Жыл бұрын
Wow, that one was very helpful
@thedeegan
@thedeegan Жыл бұрын
range is non inclusive, so it gives you a list of numbers between 1-999.
@metroexodus4388
@metroexodus4388 11 ай бұрын
def sieve_of_eratosthenes(limit): primes = [] is_prime = [True] * (limit + 1) is_prime[0] = is_prime[1] = False for num in range(2, int(limit**0.5) + 1): if is_prime[num]: primes.append(num) for multiple in range(num * num, limit + 1, num): is_prime[multiple] = False for num in range(int(limit**0.5) + 1, limit + 1): if is_prime[num]: primes.append(num) return primes limit = 1000 primes = sieve_of_eratosthenes(limit) print(primes)
@Yupppi
@Yupppi Жыл бұрын
This is really nice, but you can't save shorts to your playlists so you'd have a library of useful tips and methods.
@rondamon4408
@rondamon4408 Жыл бұрын
Much easier: For i in range(list): If input(f"is {I} prime?") == "of course": Result.append(I) Sorted. I'm a genius
@OctagonalSquare
@OctagonalSquare Жыл бұрын
If you ever have to find if a number is prime, you don’t have to divide by every number up until that number. You just have to divide by every number until half of that number. Cuts the amount of calculations by half
@sumanyuanand6651
@sumanyuanand6651 2 ай бұрын
n = range(1, 1000) primes = list(filter(lambda x: x > 1 and all(x % i != 0 for i in range(2, int(x**0.5) + 1)), n)) print(primes)
@darrenxavierjohan861
@darrenxavierjohan861 9 ай бұрын
1 is definitely my favorite prime number, innit?
@Jakku_Azzo
@Jakku_Azzo Жыл бұрын
He said, “Able Prize here I come”😂🔥
The Truth About Learning Python in 2024
9:38
Internet Made Coder
Рет қаралды 215 М.
5 Good Python Habits
17:35
Indently
Рет қаралды 622 М.
ТЫ В ДЕТСТВЕ КОГДА ВЫПАЛ ЗУБ😂#shorts
00:59
BATEK_OFFICIAL
Рет қаралды 4,5 МЛН
МЕНЯ УКУСИЛ ПАУК #shorts
00:23
Паша Осадчий
Рет қаралды 5 МЛН
Learn Java in 14 Minutes (seriously)
14:00
Alex Lee
Рет қаралды 4,8 МЛН
Python Tutorial for Beginners (with mini-projects)
8:41:54
freeCodeCamp.org
Рет қаралды 689 М.
How To Use List Comprehension In Python
6:41
Taylor's Software
Рет қаралды 11 М.
ASMR Programming - Coding Pacman - No Talking
1:21:19
Servet Gulnaroglu
Рет қаралды 2,9 МЛН
How I Would Learn Python FAST in 2024 (if I could start over)
12:19
Thu Vu data analytics
Рет қаралды 551 М.
Learn Any Programming Language In 3 Hours!
22:37
Code With Huw
Рет қаралды 550 М.
Python 101: Learn the 5 Must-Know Concepts
20:00
Tech With Tim
Рет қаралды 1,2 МЛН
Python Tutorial for Beginners - Learn Python in 5 Hours [FULL COURSE]
5:31:30
TechWorld with Nana
Рет қаралды 6 МЛН
10 Important Python Concepts In 20 Minutes
18:49
Indently
Рет қаралды 300 М.
Learn Python With This ONE Project!
55:04
Tech With Tim
Рет қаралды 1,8 МЛН
ТЫ В ДЕТСТВЕ КОГДА ВЫПАЛ ЗУБ😂#shorts
00:59
BATEK_OFFICIAL
Рет қаралды 4,5 МЛН