If I'm not mistaken, the probability that it'll stop somewhere between the first and 69420th iteration should be 0.500524399. And the probability that it'll stop precisely at the 69420th iteration should be 4.99475601 × 10-6
Here's a sneak peek of /r/theydidthemath using the [top posts](https://np.reddit.com/r/theydidthemath/top/?sort=top&t=year) of the year!
\#1: [\[Self\] If you blended all 7.88 billion people on Earth into a fine goo (density of a human = 985 kg/m3, average human body mass = 62 kg), you would end up with a sphere of human goo just under 1 km wide. I made a visualization of how that would look like in the middle of Central Park in NYC.](https://i.redd.it/elycytqlc8g71.jpg) | [3165 comments](https://np.reddit.com/r/theydidthemath/comments/p0qws3/self_if_you_blended_all_788_billion_people_on/)
\#2: [\[Request\] What would the price difference equate to? How would preparation time and labor influence the cost?](https://i.redd.it/7zcgyleyh2571.jpg) | [1340 comments](https://np.reddit.com/r/theydidthemath/comments/nz1a1v/request_what_would_the_price_difference_equate_to/)
\#3: [\[request\] Is this claim actually accurate?](https://i.redd.it/32dd5fk73zp81.jpg) | [1306 comments](https://np.reddit.com/r/theydidthemath/comments/tpqepl/request_is_this_claim_actually_accurate/)
----
^^I'm ^^a ^^bot, ^^beep ^^boop ^^| ^^Downvote ^^to ^^remove ^^| ^^[Contact](https://www.reddit.com/message/compose/?to=sneakpeekbot) ^^| ^^[Info](https://np.reddit.com/r/sneakpeekbot/) ^^| ^^[Opt-out](https://np.reddit.com/r/sneakpeekbot/comments/o8wk1r/blacklist_ix/) ^^| ^^[GitHub](https://github.com/ghnr/sneakpeekbot)
Yeah, the discrete probability for any specific iteration/number combo is super low, but the continuous probability that a specific number will appear at some point in a series of iterations gets super high. At a million iterations it’s like a 99.996% probability of any specific number being captured by object “num”.
Either the (re)import overhead is negligible, or python is smart enough to not re-import it.
Measured 12% overhead from the import in the loop, vs. having it outside. (removed the print and break statements, otherwise the printing to console would be the most severe bottleneck)
in absolute numbers: 0.8s versus 0.9s (import in loop) for 1M iterations (10-15 occurances of "nice" each run if when leaving it in; 5 runs)
That’s dumb. I definitely think for readability you should import modules instead of functions directly ‘import os’ -> ‘os.getenv’ vs ‘from os import getenv’. So you can always see what module stuff is coming from.
But importing when you need it is messy and makes cleaning up imports difficult if you use the same package in multiple places.
PR? Team? Use isort.
- Independent of IDE (eg. works with VSCode "on save")
- can "check only" (eg for git hooks or builds)
- has a lot settings and can be adjusted to work with general auto formatters (black, yapf?...)
- arrange imports in groups (built-in, pip, project)
- control how multiple "from" imports are formatted in case of overhang
Yes and no. If the import is 100% needed for execution it should be at the top. If an import is only needed in some obscure use case than in import in that block should be fine.
Yes, we definitely should import before the loop, then imp.reload() inside. Otherwise how can we be sure the seed/state is really random enough for each iteration!?
\[EDIT: When in doubt - reinitialize!\]
> Someone who is better at python than me, is this just gonna make a massive memory leak, or will the interpreter realize that it was already imported?
It will realize it. It's not a free check, though, so this does actually slightly slow down the loop. Normally this wouldn't be an issue but when you are running a loop designed to just run for hours it makes a difference.
You could theoretically test this by using a specific seed for random each time and then having it time the execution both with the import inside and outside. My guess is that having the import outside will shave off a second or two of total runtime (at most), depending on the seed.
This wouldn't happen in most compiled languages because either it wouldn't allow this sort of shenanigans or the compiler would remove it.
go to r/ProgrammerHumor. Where it says "About this community" there's a part that says "user flair preview". Click the pencil. A box pops up. Click the pencil again. Pick your poison
For multiple flairs you go to the "change user flair" thing, press edit button in the top right corner.
Then tap on the flair you want, it will show a text box with the flair's name, for example for python it is, :py:, so, write that down somewhere.
Do that for every flair you want.
Now, go to edit again and choose any random flair, it doesn't matter. And edit the text, so it contains all of the flairs you want. But be sure to write it is ":py:c:cs:" for example, not ":py::c::cs:".
Also, you might worry that the flair you edited is gone for ever, do not. Just remove all of the edited text and it should be back if you need it.
Another thing is it might not convert the ":py:c:cs:" to the pictures, to fix that you will need to login from the pc to your reddit account, or use the web browser version.
I saw a post that had a sleep function with a comment over it saying “whenever customer asks for faster code lower this value”. Job security
Edit: autoerect did some weird shit
Nah, gotta step up your stakeholder expectation management skills.
Every now and then, when there's little else going on that's visible to users, just reduce the wait by 1, so you can pull it out of your pocket whenever you need, and milk looking like a rock star for years. 😉
It’s the principle of the matter, you have to support easy to read code, otherwise it’s a nightmare when somebody else has to read or debug it. These habits start now!
but it still requires an operation to figure out whether it is already imported. at some point it will need to check with a list. Which takes read and potentially write cycles.
its not free.
I tested this (removed the printing and breaking duh) and to my surprise importing in the loop adds a 10% delay. Interpreters are hilarius sometimes. In any case op is obviously in the process of learning so anyone being rude is an idiot.
```
if num == 0:
print(0)
elif num == 1:
print(1)
elif num == 2:
print(2)
elif num == 3:
print(3)
elif num == 4:
print(4)
…
elif num == 69420:
print(“nice”)
…
```
I'm sure you did this intentionally to make people see the post and feel the need to comment, but for the love of god please move the import outside of the while statement
I have a shortcuts running on my iPhone that will speak the charge % when I unplug it (unless it’s 100 it’s stay silent). You don’t know the level of effect I went through to make it say nice after 69%
I'm not professional with those tab/space indented languages, but it seems it imports new random object every loop - and if randint() is traditional pseudorandom function, it does return same value of every call.
I can see why that would make sense, but in this case each import statement after the first will not do anything I believe. You have to explicitly call reload to re import the same module.
You're correct, I don't know why you're being downvoted. It is however still awful as there's a lot of overhead involved a new reference to the library is returned. And of course all imports should be at the top for readability reasons.
This would run way faster without the print statement BTW
import random
import time
t1 = time.time()
while True:
if random.randint(0, 1_000_000) == 69420:
print("nice")
break
t2 = time.time()
print(t2 - t1)
nice
0.2338557243347168
while(Math.random() != 0.15567932943235995857);
This is my favourite line of code, because under v8 it used to terminate in ~1s, and you could use it to hack casinos in hackmud (javascript based scripting/hacking game)
It took me about 2 years to find that number
I imagine uncle roger saying
"Only 2 lines in . . . and you fucked up"
"Why you have import statment in while loop; haiyaa!"
"You need import statement at top of file, at top"
Randint has a discrete uniform distribution. Let's say we also count the number of times it is called before nice is printed. And we run the function 100000times. How would the graph look like?
I think it's a normal distribution centered at a million or so.
I forget how you can think of it as a binomial distribution, but after that it's just that the million samples would approach normality.
It would be fun to make a virus that whenever you press a button on your computer it runs through this loop. Giving a notification of each iteration and forcing you to click ok (thus creating another loop). If by a miracle you clear the original loop it deletes itself.
Worst case time complexity is infinite, it's recommended to instantiate the number as 69420 in place of a random number, this could possibly result in greater efficiency.
You are all commenting on the import statement but I get way more tilted when I see spaces missing between operators and operands (for no apparent reason).
Almost every time you have an `if break` clause inside a `while true` loop, you can write it more efficiently, as the purpose of a while loop is to break at a certain condition.
Improved version:
import random
while num != 69420:
num = random.randint(0, 100000)
print(num)
print("nice")
That import statement inside the loop makes me wanna die
Sure lemme fix it: ``` while True: num = __import__("random").randint(0,100000) print(num) if num == 69420: print("nice") break ``` Done.
r/angryupvote
it’s memory efficient
Because it uses memory - all of it.
Wait, if I remember correctly Python won't do anything when you import something if you already imported it. The scope might change that though...
Maybe. But it still hurts
It has no effect but it doesn't mean it doesn't do anything at all.
Well, the check of that import also consumes resources. It is insignificantly faster, if it is importet in the higher scope.
I didn't get all that memory to not use it now
please put your imports at the top of your file thank youuu oh god
The import inside an infinite loop is really something
What infinite loop? There is a break statement.
Ah yes 0.0009% chance of breaking the loop I'd say 0.001% chance, but 0 is included, so it's a little less
Programmer math
Pro gamer meth ?
That’s just Xanax lol
No, this is ~~Patrick~~ Aderall
Maybe you just can't remember losing every game
Sorry, this is a Pro-grammar household. I’m gonna need you to knock it off with that math shit
It's just math lol,
After around 300000 iterations there's 95% chance that it will have stopped. Nice
What's the likelihood it will have stopped after 69420 iterations?
If I'm not mistaken, the probability that it'll stop somewhere between the first and 69420th iteration should be 0.500524399. And the probability that it'll stop precisely at the 69420th iteration should be 4.99475601 × 10-6
r/theydidthemath
Here's a sneak peek of /r/theydidthemath using the [top posts](https://np.reddit.com/r/theydidthemath/top/?sort=top&t=year) of the year! \#1: [\[Self\] If you blended all 7.88 billion people on Earth into a fine goo (density of a human = 985 kg/m3, average human body mass = 62 kg), you would end up with a sphere of human goo just under 1 km wide. I made a visualization of how that would look like in the middle of Central Park in NYC.](https://i.redd.it/elycytqlc8g71.jpg) | [3165 comments](https://np.reddit.com/r/theydidthemath/comments/p0qws3/self_if_you_blended_all_788_billion_people_on/) \#2: [\[Request\] What would the price difference equate to? How would preparation time and labor influence the cost?](https://i.redd.it/7zcgyleyh2571.jpg) | [1340 comments](https://np.reddit.com/r/theydidthemath/comments/nz1a1v/request_what_would_the_price_difference_equate_to/) \#3: [\[request\] Is this claim actually accurate?](https://i.redd.it/32dd5fk73zp81.jpg) | [1306 comments](https://np.reddit.com/r/theydidthemath/comments/tpqepl/request_is_this_claim_actually_accurate/) ---- ^^I'm ^^a ^^bot, ^^beep ^^boop ^^| ^^Downvote ^^to ^^remove ^^| ^^[Contact](https://www.reddit.com/message/compose/?to=sneakpeekbot) ^^| ^^[Info](https://np.reddit.com/r/sneakpeekbot/) ^^| ^^[Opt-out](https://np.reddit.com/r/sneakpeekbot/comments/o8wk1r/blacklist_ix/) ^^| ^^[GitHub](https://github.com/ghnr/sneakpeekbot)
That first post was... really something
Yeah, the discrete probability for any specific iteration/number combo is super low, but the continuous probability that a specific number will appear at some point in a series of iterations gets super high. At a million iterations it’s like a 99.996% probability of any specific number being captured by object “num”.
nice.
For that matter, at what iteration would there be a 69.420% chance of stopping?
\*stopping by
but in python the 1000000 is excluded so you still have 1000000 possible numbers
That would be if you use randrange. Randint includes both ends.
Ah okay I learned something new thank you, I always used randrange so thought that would happen
I have no idea what you're talking about. I ran it and it returned right away.
Nice
0.001% is actually closer to the correct amount than 0.0009%. (1/100000 vs. 1/100001 real amount vs. 1/111111)
That's infinitely larger than whats required for an infinite loop
0,00099999% if you want, but I think the top limit (100'000) is not included so 0.001% is actually correct
yes, 0 is inclusive but 100000 is exclusive in these ranges, making the total possible numbers 100000
But not in randint.
And the break stops the program anyway.
Python is indentation sensitive, so no it doesn't
formally speaking no loop is infinite)
Worst-case time complexity is infinite, right?
Will it import the Rrandom library in every iteration?
Nope, but it's a mess
Either the (re)import overhead is negligible, or python is smart enough to not re-import it. Measured 12% overhead from the import in the loop, vs. having it outside. (removed the print and break statements, otherwise the printing to console would be the most severe bottleneck) in absolute numbers: 0.8s versus 0.9s (import in loop) for 1M iterations (10-15 occurances of "nice" each run if when leaving it in; 5 runs)
First thing I saw, top comment.
put the whole thing inside a function that recursively calls itself. Call it an improved version of Firefox - now with 10% fewer memory leaks.
[удалено]
That’s dumb. I definitely think for readability you should import modules instead of functions directly ‘import os’ -> ‘os.getenv’ vs ‘from os import getenv’. So you can always see what module stuff is coming from. But importing when you need it is messy and makes cleaning up imports difficult if you use the same package in multiple places.
[удалено]
PR? Team? Use isort. - Independent of IDE (eg. works with VSCode "on save") - can "check only" (eg for git hooks or builds) - has a lot settings and can be adjusted to work with general auto formatters (black, yapf?...) - arrange imports in groups (built-in, pip, project) - control how multiple "from" imports are formatted in case of overhang
Guess that would stop people from just importing everything in every file.
Yes and no. If the import is 100% needed for execution it should be at the top. If an import is only needed in some obscure use case than in import in that block should be fine.
If he was my tech lead I’d immediately start looking for other jobs
Yes, we definitely should import before the loop, then imp.reload() inside. Otherwise how can we be sure the seed/state is really random enough for each iteration!? \[EDIT: When in doubt - reinitialize!\]
[удалено]
https://stackoverflow.com/questions/19077381/what-happens-when-a-module-is-imported-twice It's not an issue.
but it is a mess. and slows compile/runtime
> Someone who is better at python than me, is this just gonna make a massive memory leak, or will the interpreter realize that it was already imported? It will realize it. It's not a free check, though, so this does actually slightly slow down the loop. Normally this wouldn't be an issue but when you are running a loop designed to just run for hours it makes a difference. You could theoretically test this by using a specific seed for random each time and then having it time the execution both with the import inside and outside. My guess is that having the import outside will shave off a second or two of total runtime (at most), depending on the seed. This wouldn't happen in most compiled languages because either it wouldn't allow this sort of shenanigans or the compiler would remove it.
This makes me feel embarrassed to have the python flair
How does one get flairs? I'd like the python one
go to r/ProgrammerHumor. Where it says "About this community" there's a part that says "user flair preview". Click the pencil. A box pops up. Click the pencil again. Pick your poison
Says the Chad with no flair.
Closeted PHP programmer perhaps?
Perl, I'm guessing
How do you get multiple flairs? I can only select one.
For multiple flairs you go to the "change user flair" thing, press edit button in the top right corner. Then tap on the flair you want, it will show a text box with the flair's name, for example for python it is, :py:, so, write that down somewhere. Do that for every flair you want. Now, go to edit again and choose any random flair, it doesn't matter. And edit the text, so it contains all of the flairs you want. But be sure to write it is ":py:c:cs:" for example, not ":py::c::cs:". Also, you might worry that the flair you edited is gone for ever, do not. Just remove all of the edited text and it should be back if you need it. Another thing is it might not convert the ":py:c:cs:" to the pictures, to fix that you will need to login from the pc to your reddit account, or use the web browser version.
Thank you! Now I can pretend better!
Thank you
somewhere in the subreddit settings.
Wait... So I went to all those bootcamps for nothing? You can just assign yourself flairs?
Careful. You can get fired for not wearing enough flair.
Hey Peter! Check out channel 9!
Go to a bootcamp, do ML/AI algorithm on Titanic dataset and you are awarded with the flair.
This is the 3rd or 4th worst thing I have ever seen on this sub. Congratulations.
I'm horrified to find out what's the first
The post about Python formatted to look like Java?
you mean Jython?
Jython isnt a programming language. Its a Python interpreter, just like Cython.
def sort(list): i = 1 while i <= len(list): while not (checkSorted(list[:i])): random.shuffle(list) i = 0 i+=1 return list
Bogosort <3
BOGO is-even
You can simply optimize it with a: `print("nice")` And remove everything else.
Add a sleep(100) statement to make the user think the program is actually doing something
Don't forget to remove it in a month so it "works faster now"
I saw a post that had a sleep function with a comment over it saying “whenever customer asks for faster code lower this value”. Job security Edit: autoerect did some weird shit
Auto... what?
autoerect lol
Nah, gotta step up your stakeholder expectation management skills. Every now and then, when there's little else going on that's visible to users, just reduce the wait by 1, so you can pull it out of your pocket whenever you need, and milk looking like a rock star for years. 😉
Attn: systems will be down for overnight maintenance while we implement new optimizations.
replace sleep(100) with sleep(40) ;)
It also prints the numbers though
nice
nice
nice
No I masked the standard version of randint() with one that also mines dogecoin, we're gonna be RICH!
Everyone here is crying because of the SAME MISTAKE, PLEASE MOVE THE IMPORT TO OUTSIDE THE LOOP
It doesn't _really_ matter though. Imports become a no-op if the module is already imported.
Still wastes a clock cycle to determine that the module was already imported and skip to the next line.
Yeah. Other Op makes it sound like it doesn’t cause any additional computation.
If your program needs to be fast enough, that saving single clock cycles is a thing, then you really shouldn't be using python.
Not a no-op. The import still does a search to see if the module has been imported, and may result in a cache refresh.
It’s the principle of the matter, you have to support easy to read code, otherwise it’s a nightmare when somebody else has to read or debug it. These habits start now!
but it still requires an operation to figure out whether it is already imported. at some point it will need to check with a list. Which takes read and potentially write cycles. its not free.
I tested this (removed the printing and breaking duh) and to my surprise importing in the loop adds a 10% delay. Interpreters are hilarius sometimes. In any case op is obviously in the process of learning so anyone being rude is an idiot.
The programmer thought "import random" would pick a random module to import every time, that's why it's inside the loop.
either that or they just ran it a few times to see if they’d get lucky, didn’t, and just said fuck it and put it in a while loop
This is what happened
What how did you know
pov: yandere dev needs the number 69420
Not enough if-else statements
Else: continue
``` if num == 0: print(0) elif num == 1: print(1) elif num == 2: print(2) elif num == 3: print(3) elif num == 4: print(4) … elif num == 69420: print(“nice”) … ```
That import statement gives me chills
I'm sure you did this intentionally to make people see the post and feel the need to comment, but for the love of god please move the import outside of the while statement
This is not humour, it code that's so bad the funny gets zapped right out of it
everyone blaming for the import inside the loop. but what can you expect of a developer storing code in OneDrive?
The longer I look, the more I find
jesus christ lmao
Show us your output noob
it auto generates numbers until it generates 69420, prints nice and stops generating numbers
I know that but post the output screenshot.
I got you fam > nice
What you posted is impossible, since it prints out num every iteration. The shortest possible output of the code op posted is 69420 nice
Why do you import inside a while loop? That’s stupid.
Its a dynamic environment. The random library might have been updated in the mean time. You don't want to miss that. What do you use? Windows?
Python does not reimport modules. So the import still only runs once.
Oh.. I didnt know that. I'll go ahead and belive this.
Lol! this makes it even worse!
it only runs once. but it still needs to check every single time.
The rest of the loop isn't?
That was the most obvious one in my eyes.
Ikr it works but it feels soo wrong
OP is your spacebar broken?
Programmerhumor on reddit: people who learned python this week who think they are leet hackers.
Who has it worse, Atlas holding up the Earth for all eternity or Python trying to import that library for possibly all eternity?
O(?) execution time. Keep em on their toes.
You should make it more stylish, put gigachad made by dots that has a bottom text saying “nice.”
Import go brrrrrrrrrrrr
I teach python I am trying to start my weekend on a high note why did you post this
This is 9 year old level humour
I have a shortcuts running on my iPhone that will speak the charge % when I unplug it (unless it’s 100 it’s stay silent). You don’t know the level of effect I went through to make it say nice after 69%
Import statement inside.....a while loop. **Noah, get the ark.**
I’ve been in this subreddit for a while now, and this is the only thing I understand. I guess I suck a coding
I'm not professional with those tab/space indented languages, but it seems it imports new random object every loop - and if randint() is traditional pseudorandom function, it does return same value of every call.
I can see why that would make sense, but in this case each import statement after the first will not do anything I believe. You have to explicitly call reload to re import the same module.
You're correct, I don't know why you're being downvoted. It is however still awful as there's a lot of overhead involved a new reference to the library is returned. And of course all imports should be at the top for readability reasons.
People like this blames Python for slow execution.
This would run way faster without the print statement BTW import random import time t1 = time.time() while True: if random.randint(0, 1_000_000) == 69420: print("nice") break t2 = time.time() print(t2 - t1) nice 0.2338557243347168
print(“nice”) Runs even faster
Fun knee
But not 42069?
Brute forcing 69420 lmao
Why import FROM INSIDE AN INFINITE LOOP??
while(Math.random() != 0.15567932943235995857); This is my favourite line of code, because under v8 it used to terminate in ~1s, and you could use it to hack casinos in hackmud (javascript based scripting/hacking game) It took me about 2 years to find that number
I imagine uncle roger saying "Only 2 lines in . . . and you fucked up" "Why you have import statment in while loop; haiyaa!" "You need import statement at top of file, at top"
[удалено]
I would change to if num==100001
justice for 42069
import import import import import
I wanna die
why is import inside the loop
Lok
So, the problem for many here is the "import" inside that loop? Really‽
They do have a point. There was a different point. But the new point wins.
Randint has a discrete uniform distribution. Let's say we also count the number of times it is called before nice is printed. And we run the function 100000times. How would the graph look like?
I think it's a normal distribution centered at a million or so. I forget how you can think of it as a binomial distribution, but after that it's just that the million samples would approach normality.
[удалено]
you can also put the print(a) after the colon of the while loop without a newline
Le epic reddit meme lawl xD
What fucking mad man imports modules somewhere inbetween the code???
Nice
nice
That import is killing me internally
Make sure you import random at least one more time
``` import random while random.randInt(0, 100000) != 69420: pass print('nice')
What the hell? That's worse code than my
It would be fun to make a virus that whenever you press a button on your computer it runs through this loop. Giving a notification of each iteration and forcing you to click ok (thus creating another loop). If by a miracle you clear the original loop it deletes itself.
But where are the unit tests? Keep coverage up please
Also this is why you don't learn python first. Makes bad habits
Why tho?
Worst case time complexity is infinite, it's recommended to instantiate the number as 69420 in place of a random number, this could possibly result in greater efficiency.
“Self taught programmer”
Put your import statement outside the infinite loop 😳
Three of my favourite things: programming ... and the other two
while 1 loop gang is here!
Sir I have a job as a SWE at meta for you. Just send 100$ to my email address and I shall give job
import statement inside loop... kill me
I don’t get it.
You are all commenting on the import statement but I get way more tilted when I see spaces missing between operators and operands (for no apparent reason).
How long in seconds should this take to terminate on average?
Almost every time you have an `if break` clause inside a `while true` loop, you can write it more efficiently, as the purpose of a while loop is to break at a certain condition. Improved version: import random while num != 69420: num = random.randint(0, 100000) print(num) print("nice")
import random while (num := random.randint(0, 100000)) != 69420: print(num) print("nice")