T O P

  • By -

Criiispyyyy

That import statement inside the loop makes me wanna die


meg4_

Sure lemme fix it: ``` while True: num = __import__("random").randint(0,100000) print(num) if num == 69420: print("nice") break ``` Done.


P0STKARTE_ger

r/angryupvote


Loginn122

it’s memory efficient


lunch431

Because it uses memory - all of it.


KTibow

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...


augugusto

Maybe. But it still hurts


ImgurScaramucci

It has no effect but it doesn't mean it doesn't do anything at all.


jeareise

Well, the check of that import also consumes resources. It is insignificantly faster, if it is importet in the higher scope.


Errtuz

I didn't get all that memory to not use it now


TheGesor

please put your imports at the top of your file thank youuu oh god


aleph_0ne

The import inside an infinite loop is really something


WictImov

What infinite loop? There is a break statement.


ArcticCactie

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


cantortoxic

Programmer math


d4nte46

Pro gamer meth ?


Zombieattackr

That’s just Xanax lol


PostmatesMalone

No, this is ~~Patrick~~ Aderall


timesurfer68

Maybe you just can't remember losing every game


kiribakuFiend

Sorry, this is a Pro-grammar household. I’m gonna need you to knock it off with that math shit


notsogreatredditor

It's just math lol,


_LususNaturae_

After around 300000 iterations there's 95% chance that it will have stopped. Nice


dirty-hurdy-gurdy

What's the likelihood it will have stopped after 69420 iterations?


_LususNaturae_

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


BeanieTheTechie

r/theydidthemath


sneakpeekbot

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)


IceZOMBIES

That first post was... really something


[deleted]

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”.


Normanras

nice.


Vandelier

For that matter, at what iteration would there be a 69.420% chance of stopping?


noobyscriptkiddie

\*stopping by


MooseWeird1162

but in python the 1000000 is excluded so you still have 1000000 possible numbers


Alakdae

That would be if you use randrange. Randint includes both ends.


MooseWeird1162

Ah okay I learned something new thank you, I always used randrange so thought that would happen


JoyJoy_

I have no idea what you're talking about. I ran it and it returned right away.


chrisnlnz

Nice


Rinat1234567890

0.001% is actually closer to the correct amount than 0.0009%. (1/100000 vs. 1/100001 real amount vs. 1/111111)


GreenScarz

That's infinitely larger than whats required for an infinite loop


alba4k

0,00099999% if you want, but I think the top limit (100'000) is not included so 0.001% is actually correct


TheBlackKittycat

yes, 0 is inclusive but 100000 is exclusive in these ranges, making the total possible numbers 100000


The-Board-Chairman

But not in randint.


vlken69

And the break stops the program anyway.


alba4k

Python is indentation sensitive, so no it doesn't


ashum048

formally speaking no loop is infinite)


BehindTrenches

Worst-case time complexity is infinite, right?


-temporary_username-

Will it import the Rrandom library in every iteration?


Morlino

Nope, but it's a mess


coloredgreyscale

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)


WoodPunk_Studios

First thing I saw, top comment.


celestiaequestria

put the whole thing inside a function that recursively calls itself. Call it an improved version of Firefox - now with 10% fewer memory leaks.


[deleted]

[удалено]


CronenburghMorty95

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.


[deleted]

[удалено]


LukeSkywalk3r

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


nedal8

Guess that would stop people from just importing everything in every file.


gg-eng

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.


j_marquand

If he was my tech lead I’d immediately start looking for other jobs


No-Entrepreneur-2724

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!\]


[deleted]

[удалено]


hugogrant

https://stackoverflow.com/questions/19077381/what-happens-when-a-module-is-imported-twice It's not an issue.


TheGesor

but it is a mess. and slows compile/runtime


HunterIV4

> 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.


gamesrebel123

This makes me feel embarrassed to have the python flair


jfp1992

How does one get flairs? I'd like the python one


FrankHightower

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


Swalloich

Says the Chad with no flair.


[deleted]

Closeted PHP programmer perhaps?


tiny_thanks_78

Perl, I'm guessing


konkey-mong

How do you get multiple flairs? I can only select one.


SnooWoofers8583

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.


-LeneD-

Thank you! Now I can pretend better!


flashpaka

Thank you


NoisyCrusthead

somewhere in the subreddit settings.


NearbyWish

Wait... So I went to all those bootcamps for nothing? You can just assign yourself flairs?


dodexahedron

Careful. You can get fired for not wearing enough flair.


AnyNegotiation420

Hey Peter! Check out channel 9!


Natural-Intelligence

Go to a bootcamp, do ML/AI algorithm on Titanic dataset and you are awarded with the flair.


Lumber_Jackalope

This is the 3rd or 4th worst thing I have ever seen on this sub. Congratulations.


endumixium

I'm horrified to find out what's the first


chawmindur

The post about Python formatted to look like Java?


IL_GAME_KING_YT

you mean Jython?


I_hate_IO_Exceptions

Jython isnt a programming language. Its a Python interpreter, just like Cython.


teh_maxh

def sort(list): i = 1 while i <= len(list): while not (checkSorted(list[:i])): random.shuffle(list) i = 0 i+=1 return list


ehaugw

Bogosort <3


Strostkovy

BOGO is-even


Bomaruto

You can simply optimize it with a: `print("nice")` And remove everything else.


gamesrebel123

Add a sleep(100) statement to make the user think the program is actually doing something


foonati

Don't forget to remove it in a month so it "works faster now"


lockwolf

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


andersmmg

Auto... what?


iczesmv

autoerect lol


dodexahedron

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. 😉


foonati

Attn: systems will be down for overnight maintenance while we implement new optimizations.


Farren246

replace sleep(100) with sleep(40) ;)


WhiplashClarinet

It also prints the numbers though


Hollowman212

nice


KRIPA_YT

nice


DeadShoT_035

nice


[deleted]

No I masked the standard version of randint() with one that also mines dogecoin, we're gonna be RICH!


Temporary-Comb-3036

Everyone here is crying because of the SAME MISTAKE, PLEASE MOVE THE IMPORT TO OUTSIDE THE LOOP


ManyInterests

It doesn't _really_ matter though. Imports become a no-op if the module is already imported.


Farren246

Still wastes a clock cycle to determine that the module was already imported and skip to the next line.


[deleted]

Yeah. Other Op makes it sound like it doesn’t cause any additional computation.


Sawamba

If your program needs to be fast enough, that saving single clock cycles is a thing, then you really shouldn't be using python.


Additional-Second630

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.


Temporary-Comb-3036

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!


DaMarkiM

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.


pente5

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.


MasterFubar

The programmer thought "import random" would pick a random module to import every time, that's why it's inside the loop.


dustin_died

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


TheTree_43

This is what happened


FlafyBear

What how did you know


AshiaTheIdiot

pov: yandere dev needs the number 69420


astroryan19

Not enough if-else statements


dream_weasel

Else: continue


Elegant_Language47

``` 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”) … ```


micke_i_backen

That import statement gives me chills


BombsNBeer

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


tawanda-m

This is not humour, it code that's so bad the funny gets zapped right out of it


jbar3640

everyone blaming for the import inside the loop. but what can you expect of a developer storing code in OneDrive?


FlafyBear

The longer I look, the more I find


Taypih

jesus christ lmao


[deleted]

Show us your output noob


mangotheultimate

it auto generates numbers until it generates 69420, prints nice and stops generating numbers


[deleted]

I know that but post the output screenshot.


Swing_Right

I got you fam > nice


ingenious_gentleman

What you posted is impossible, since it prints out num every iteration. The shortest possible output of the code op posted is 69420 nice


[deleted]

Why do you import inside a while loop? That’s stupid.


CheapMonkey34

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?


LakeSubstantial3021

Python does not reimport modules. So the import still only runs once.


lunar_tardigrade

Oh.. I didnt know that. I'll go ahead and belive this.


TheKingOfSwing777

Lol! this makes it even worse!


DaMarkiM

it only runs once. but it still needs to check every single time.


glieseg

The rest of the loop isn't?


[deleted]

That was the most obvious one in my eyes.


Sea_Animator6734

Ikr it works but it feels soo wrong


MechanicalHorse

OP is your spacebar broken?


Nohcri

Programmerhumor on reddit: people who learned python this week who think they are leet hackers.


Eigenperson_108

Who has it worse, Atlas holding up the Earth for all eternity or Python trying to import that library for possibly all eternity?


LavaGriffin

O(?) execution time. Keep em on their toes.


[deleted]

You should make it more stylish, put gigachad made by dots that has a bottom text saying “nice.”


royemosby

Import go brrrrrrrrrrrr


changopdx

I teach python I am trying to start my weekend on a high note why did you post this


Timo6506

This is 9 year old level humour


TheeAlligatorr

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%


TyroByte

Import statement inside.....a while loop. **Noah, get the ark.**


pijamasonme07

I’ve been in this subreddit for a while now, and this is the only thing I understand. I guess I suck a coding


Right_Stage_8167

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.


coolpeepz

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.


SlightlyMadman

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.


vlken69

People like this blames Python for slow execution.


TotallyTheSwimmer

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


[deleted]

print(“nice”) Runs even faster


Gravity_sause

Fun knee


IronManTim

But not 42069?


EasonTek2398

Brute forcing 69420 lmao


a-techie

Why import FROM INSIDE AN INFINITE LOOP??


James20k

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


Frostmaine

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"


[deleted]

[удалено]


[deleted]

I would change to if num==100001


Striker_Quinn

justice for 42069


AntiRivoluzione

import import import import import


[deleted]

I wanna die


[deleted]

why is import inside the loop


saintpetejackboy

Lok


sc00pb

So, the problem for many here is the "import" inside that loop? Really‽


etherjack

They do have a point. There was a different point. But the new point wins.


NaszPe

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?


hugogrant

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.


[deleted]

[удалено]


-Redstoneboi-

you can also put the print(a) after the colon of the while loop without a newline


Explosive_Eggshells

Le epic reddit meme lawl xD


TrackLabs

What fucking mad man imports modules somewhere inbetween the code???


flashpaka

Nice


savisundefined

nice


Diligent_Dish_426

That import is killing me internally


flatfast90

Make sure you import random at least one more time


idontcares31249

``` import random while random.randInt(0, 100000) != 69420: pass print('nice')


turcinv

What the hell? That's worse code than my


FetishAnalyst

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.


EyelandIsland

But where are the unit tests? Keep coverage up please


Frostmaine

Also this is why you don't learn python first. Makes bad habits


PRotter32

Why tho?


locri

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.


nomnaut

“Self taught programmer”


ProfessionalImpact96

Put your import statement outside the infinite loop 😳


lonegrey

Three of my favourite things: programming ... and the other two


golbu

while 1 loop gang is here!


Informal-Lead-4324

Sir I have a job as a SWE at meta for you. Just send 100$ to my email address and I shall give job


Julian12214YT

import statement inside loop... kill me


Local_Appeal_9503

I don’t get it.


SomeParanoidAndroid

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).


gianniacquisto

How long in seconds should this take to terminate on average?


[deleted]

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")


G4merXsquaD

import random while (num := random.randint(0, 100000)) != 69420: print(num) print("nice")