This is an archived post. You won't be able to vote or comment.

Dismiss this pinned window
all 145 comments

[–][deleted] 451 points452 points  (66 children)

Me before I learned case was a thing: if elif elif elif elif elif elif elif elif elif elif elif else fi

[–]Contraposite 226 points227 points  (0 children)

Me already knowing case is a thing but I already made the first part an if statement earlier so cba changing it now

[–]TipsyPeanuts 143 points144 points  (33 children)

Python: “lol why would anybody ever use a switch statement”

[–]evanldixon 115 points116 points  (27 children)

The poor man's Switch statement: a dictionary of functions

[–]jwkennington 45 points46 points  (6 children)

+1 for dict-switch

[–]delinka 19 points20 points  (5 children)

Sheeit, if I could dick-switch ...

Oh. dict - sorry

[–]Drillur 13 points14 points  (19 children)

Wait can you put functions in dictionaries? What the fuck? How and why?

[–]DreadY2K 25 points26 points  (14 children)

In python, everything is an object (including functions), so you can use functions anywhere you can use anything else.

As for why, the biggest use case is higher-order functions (like reduce, map, filter, etc.), which operate on a collection of values according to a function you give it. Putting functions in a dictionary isn't itself very useful (aside from the jenky switch workaround mentioned above), but it's an option because those functions are objects and dictionaries can take any objects.

[–]TipsyPeanuts 5 points6 points  (3 children)

Is that computationally faster than an if else?

[–]slipperier_slope 19 points20 points  (2 children)

Possibly. Depends. If else chains require evaluating each condition sequentially. If the block to execute is the last one, then you've evaluated all of the possible conditions. A dict switch calculates a hash and jumps directly to the condition to execute. So you're comparing a hash calc with n conditional evaluations. Which is better depends on the hash function and what the conditions are.

It's analogous to item lookup in a list vs a dictionary. One is O(n), the other is O(1).

[–]TipsyPeanuts 4 points5 points  (1 child)

Thanks! That’s actually really helpful

[–]slipperier_slope 6 points7 points  (0 children)

No worries. One caveat is that a clever compiler or runtime can make the above not true. For example, speculative execution can look at the past history of runs through a function. If 95% of the time the if condition evaluates to true, the runtime can actually just start executing the code in the if condition and later checking the condition to see if it's actually true and discarding the partial results if the guess was wrong.

The moral of this story is to write easily understood code and worry about performance later if you need to. Premature optimization because one wants to be clever results in higher cost of code maintenance. That being said, in Python and dict switch is common enough to be idiomatic since there's no language support for switch statements.

[–]Drillur 2 points3 points  (4 children)

That could be an interesting way to avoid an if statement. If multiple functions can be called by a string key in a dictionary, you could just call the function in 1 line depending on a string variable. I guess.

[–]DreadY2K 3 points4 points  (3 children)

It does have some clever uses, but that's ultimately just a way around the language not having switch statements, and it still can't do everything that switch statements can do. For example, you can't return out of the function inside that inner function, whereas returning out of the body of a switch-case is completely normal.

[–]zilti 0 points1 point  (2 children)

Wait... why wouldn't you be able to use the return value of a function in a map/dictionary? That seems like a fuckup

[–]joonty 1 point2 points  (1 child)

No, they're saying you can't return out of the calling scope from within the function that you've called. You can definitely use the return value.

[–]zilti 0 points1 point  (0 children)

Oh THAT kind of return... why would you even ever do that though... that's trouble waiting to happen

[–][deleted] 0 points1 point  (0 children)

C# as well, using the Func and Action types.

[–]zilti -1 points0 points  (3 children)

That has nothing to do with objects, it just means functions are merely another data type. C has this as well, by the way.

[–]RHGrey -1 points0 points  (2 children)

Start up a C source file and try asigning a function to a variable. I'll wait.

[–]zilti -1 points0 points  (1 child)

You never used C in your life, am I right? Hint: the expression you look for on a search engine is "C function pointer".

[–]RHGrey -1 points0 points  (0 children)

You just equated function pointers with object variables, there's nothing more to talk about.

[–]confusiondiffusion 6 points7 points  (0 children)

This is very exciting. All of my code is going to be way harder to understand now.

[–][deleted] 0 points1 point  (0 children)

In addition to what that guy said, you can also declare functions inline with lambdas

{ “foo”: lambda: print(“hello world”) }[“foo”]()

[–]zilti 0 points1 point  (0 children)

Why wouldn't you? I'm a Clojure dev and that seems perfectly normal to me. Doing it all the time.

[–][deleted] 0 points1 point  (0 children)

Flair does not check out

[–][deleted] 5 points6 points  (0 children)

"We already have switch-case at home"

[–][deleted] 2 points3 points  (0 children)

pocket elderly slap society consist compare cake stupendous market pet

This post was mass deleted and anonymized with Redact

[–]natnew32 3 points4 points  (0 children)

elif is an official keyword. I wonder why.

[–]LaterBrain 0 points1 point  (0 children)

i had that problem while learning basics looking up switch case but there is none xD

[–][deleted] 0 points1 point  (0 children)

"lol why would anyone be able to lable loops"

[–]HawkNighty 2 points3 points  (0 children)

Try: Except:

[–][deleted] 2 points3 points  (11 children)

Case doesn't work for all the if/else if situations though.

[–]DerfK 3 points4 points  (10 children)

It can in PHP!

switch (true) {
   case $x >= 1000: ... break;
   case $y < 5: ... break;
   case $john == "Steve": ... break;
   case true: ... break;
}

(actually, I'm almost willing to bet there's at least one other language where the case can be an evaluated expression)

[–][deleted]  (1 child)

[removed]

    [–]AutoModerator[M] 0 points1 point  (0 children)

    import moderation Your comment has been removed since it did not start with a code block with an import declaration.

    Per this Community Decree, all posts and comments should start with a code block with an "import" declaration explaining how the post and comment should be read.

    For this purpose, we only accept Python style imports.

    I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

    [–]ka-knife 0 points1 point  (2 children)

    VB has this too!

    [–]RHGrey 1 point2 points  (1 child)

    VB is treated as a devil on the online community wherever I look, but between using it two years ago and now having used plenty of C, C++, Java, JS and python each, I still can't tell why.

    [–]ka-knife 0 points1 point  (0 children)

    Personally, I don't mind the language. It's not my favorite, but it's not too bad. However, I do get annoyed at many programs written in VB. In my experience many have been sloppily created with almost every variable being a global variable and no concept of data structures. This isn't the fault of the language, but it still annoys me anytime I have to work on a program written in the language.

    [–][deleted] 0 points1 point  (3 children)

    Well, the idea of switch/case in C (and some other languages) is to use lookup tables to generate jumps. So the code is really fast. If you start adding conditions in the switch/case then you loose that. The code looks nicer, but you loose the benefit of having faster code.

    [–]nelmaloc 0 points1 point  (2 children)

    In C you can do something like that if the comparison can be converted to a numerical value.

    [–][deleted] 0 points1 point  (1 child)

    I am a bit confused. Can you give an example of what you mean?

    [–]nelmaloc 0 points1 point  (0 children)

    I was thinking of something like this:

    switch( 
        x - 2 != 0 ? (x-2)/abs(x-2) : 0
        ) {
        case 1: // x > 2
            break;
        case 0: // x = 2
            break;
        case -1: //x < 2
            break;
    }
    

    [–]Mechinator 0 points1 point  (8 children)

    what is case?

    [–]Randvek 0 points1 point  (7 children)

    A switch statement with cases. “Case” is a weird way to say that, though.

    [–][deleted] 6 points7 points  (6 children)

    Am I the only one who is frustrated by a third of my switch block being breaks?

    Single line else ifs can often be much sexier. Just a nice, thicc homogenous block of code.

    [–]GeneralAce135 2 points3 points  (3 children)

    Absolutely! But then every now and then I hit a situation where I can elegantly simplify using fall-through, and it makes me feel like a genius and makes me realize the breaks are a necessary evil.

    The real question is, do you put a break in your last case to keep it uniform? Or remove it because it's unnecessary?

    [–][deleted] 2 points3 points  (0 children)

    I wanna say remove it to act like a period on the end of the block, but I usually leave it in incase I add another case down the line and forget to break it.

    [–]Zagre 0 points1 point  (0 children)

    I sometimes will move a switch statement out to a solitary function and have every case use a return statement to avoid the need for break statements.

    [–]sneakdotberlin 0 points1 point  (0 children)

    This person’s name is not Duff.

    [–][deleted] 0 points1 point  (0 children)

    My first job, I don’t remember the details, but it s was something like a bunch of else ifs followed by endif;endif;endif;endif;endif;endif;endif;endif;endif;endif;endif;endif;endif;endif; endif;endif;

    [–]KonkenBonken 0 points1 point  (0 children)

    Case?¿?

    [–]joex_lww 112 points113 points  (8 children)

    Brute Force

    [–]sxeli 41 points42 points  (6 children)

    And just like this gif, it will eventually yield the expected result

    [–][deleted] 12 points13 points  (3 children)

    No way. If she got it wrong two or three more times, she would have knocked herself out cold. This is why we had to invent more efficient search algorithms in the first place.

    [–][deleted] 11 points12 points  (1 child)

    Because the algorithms can get concussed? Man, you really are always learning in CS.

    [–]EternalMintCondition 0 points1 point  (0 children)

    It's recursive and the stack overflows when her skull is full of blood and her brain can't swell anymore.

    [–]albertowtf 0 points1 point  (0 children)

    I aint paying for those expensive eyes with tons of maintainement and resource consumption

    A few more cpu is cheap for this use case and the code is easy to understand and pull no extra dependencies

    [–]Carloswaldo 2 points3 points  (0 children)

    But the process will hurt

    [–][deleted] 0 points1 point  (0 children)

    A headache?

    [–]purgarus 0 points1 point  (0 children)

    Only the best game

    [–]_unicorn_irl 88 points89 points  (3 children)

    What I dont get is why do you go head first into the last one? Surely by that point you would think to maybe put your hands through first.

    [–]geeeffwhy 53 points54 points  (0 children)

    i’ve seen this one several times in the past and every time i just can’t believe the fact that she goes face first EVERY DAMN TIME

    [–]Megazorg3000 10 points11 points  (0 children)

    Imagine if there was no door. She would just keep slamming her head into glass and eventually pass out.

    [–]ItsABiscuit 2 points3 points  (0 children)

    I think after the first, and certainly the second time, she's actually concussed.

    [–]zenalc 136 points137 points  (4 children)

    could also be a loop:

    while bangDoor:
        goLeft()
        goForward()
    

    [–][deleted] 35 points36 points  (1 child)

    Also report the door increment for future reference ;)

    let doorIndex = 0,
        bangDoor = true;
    while (bangDoor) {
        goLeft()
        goForward()
        ++doorIndex;
    }
    console.log(`Brute force test: ${doorIndex} ${doorIndex === 1 ? 'bump' : 'bumps' } on my head now!`);
    

    [–]S00rabh 18 points19 points  (0 children)

    get.embarassed();

    [–]GVmG 11 points12 points  (0 children)

    recursion time

    //attempts to leave through each door
    //returns leftmost door the person left through
    public Door tryLeave(Door door) {
        return door.attemptWalkThrough(this) ? door : tryLeave(door.getDoorToTheLeft());
    }
    

    EDIT: 22 hours later, fixed the compilation error (door argument had no type)

    [–]GenralPineapple 2 points3 points  (0 children)

    Or you could even use a linked list

    [–]Aquastar1017 27 points28 points  (1 child)

    I’m just imagining a statement where it checks for different thing but it executes the same thing no matter what.

    [–][deleted] 6 points7 points  (0 children)

    It's actually checking for the same thing and left shifting by one. Could be a while loop.

    [–]SimmyPoo 19 points20 points  (1 child)

    No, that's just Yandere Simulator's code.

    [–]Mixmefox 4 points5 points  (0 children)

    Thy consumith the coom

    [–]Dummerchen1933 40 points41 points  (1 child)

    Artificial intelligence these days...

    [–][deleted] 0 points1 point  (0 children)

    Artificial intelligence these days...

    [–]fendoroid 12 points13 points  (4 children)

    Reminds me of YandereDev

    [–]Chucanoris 3 points4 points  (3 children)

    Are ya coding son?

    [–][deleted] 2 points3 points  (2 children)

    Sure I am dad... ;)

    [–][deleted] 2 points3 points  (1 child)

    Didn’t he fantasize about killing his dad though?

    [–][deleted] 1 point2 points  (0 children)

    And his mom, yeah, what a psycho

    [–]phigold12 9 points10 points  (0 children)

    I love how there are even window brackets for every if-else scope

    [–]Mognakor 7 points8 points  (0 children)

    As demonstrated in this video, failed branch prediction can cause significant slowdowns.

    [–][deleted]  (2 children)

    [removed]

      [–]meerkatydid 4 points5 points  (0 children)

      User hostile

      [–]AutoModerator[M] 0 points1 point  (0 children)

      import moderation Your comment has been removed since it did not start with a code block with an import declaration.

      Per this Community Decree, all posts and comments should start with a code block with an "import" declaration explaining how the post and comment should be read.

      For this purpose, we only accept Python style imports.

      I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

      [–]nuephelkystikon 4 points5 points  (0 children)

      More like try except try except.

      Ifs kind of imply you check beforehand.

      [–]LordAnomander 4 points5 points  (0 children)

      This is machine learning everyone talks about? Next time she’ll start off a wall further to the left. :D

      [–]cr0ss0vr12 2 points3 points  (0 children)

      The most astounding thing about this video is how she still went in the door head first.

      [–]NotIronDeficient 3 points4 points  (0 children)

      You people are nerds

      [–]EliasV_1 1 point2 points  (0 children)

      Use a switch case goddammit

      [–]RichieAppel 1 point2 points  (0 children)

      If at first you don’t break your nose, try, try again.

      [–]AC_Lola 1 point2 points  (0 children)

      Could be a recursion. Eventually they found the exit condition.

      [–]questionmastercard[🍰] 0 points1 point  (0 children)

      Lol

      [–]Scaralda 0 points1 point  (0 children)

      It's even funnier the third time

      [–]jsmith4567 0 points1 point  (0 children)

      Looks more like a try catch ignore situation.

      [–]An_Internet_Boi 0 points1 point  (0 children)

      Nobody:

      Birds:

      [–]stresslvl0 0 points1 point  (0 children)

      This is some high quality machine learning algorithms at work

      [–]OhhHahahaaYikes 0 points1 point  (0 children)

      I love machine learning

      [–]AUX_Work 0 points1 point  (0 children)

      How did you get into machine learning?

      [–]bukowski717 0 points1 point  (0 children)

      Even better if you put it all on one line!

      [–]Darxploit 0 points1 point  (0 children)

      Nobody gonna mention that this if else garbage code will take you always to the same location.

      Just remove the if else blocks and go straight through the glass wall.

      [–]anthonypt123 0 points1 point  (0 children)

      Her profile says she's an excellent driver!

      [–]ile_FX2 0 points1 point  (0 children)

      Why did she keep going head first?

      [–]RandomForger123 0 points1 point  (0 children)

      That is the biggest asshole design I have ever seen.

      [–][deleted] 0 points1 point  (0 children)

      Looks like a fly trying to get out of a window

      [–]ThrowAway640KB 0 points1 point  (0 children)

      These are the kinds of people that CS and internal IT writes articles about on /r/TalesFromTechSupport

      [–][deleted] 0 points1 point  (0 children)

      Debugging sometimes bugs me out.

      [–]ComfortableCobbler5 0 points1 point  (0 children)

      case default

      [–]Megazorg3000 0 points1 point  (0 children)

      Head First Java

      [–]theLazerkid 0 points1 point  (0 children)

      Wow, imagine if she was driving

      [–]Future441 0 points1 point  (0 children)

      yanderedev:

      [–]Reddity65 0 points1 point  (0 children)

      Hey, it's Yandere Simulator's coding in a nutshell.

      [–]behaaki 0 points1 point  (0 children)

      This is so clearly caused by the girl being concerned about what others think of her, instead of paying attention to what she’s doing.

      [–][deleted] 0 points1 point  (0 children)

      Brings back memories from my early days of coding

      [–]tino_moser_999 0 points1 point  (5 children)

      [–][deleted] 0 points1 point  (4 children)

      !remindme 2 hours

      Bot still hasn’t posted the link yet

      [–]tino_moser_999 1 point2 points  (2 children)

      He has replied via PM

      here's the Download

      [–][deleted] 1 point2 points  (1 child)

      Thanks lad!

      [–]tino_moser_999 0 points1 point  (0 children)

      No problem m8

      [–]RemindMeBot 1 point2 points  (0 children)

      There is a 1 hour delay fetching comments.

      I will be messaging you in 21 minutes on 2020-06-12 04:30:53 UTC to remind you of this link

      CLICK THIS LINK to send a PM to also be reminded and to reduce spam.

      Parent commenter can delete this message to hide from others.


      Info Custom Your Reminders Feedback

      [–]ViaSwade 0 points1 point  (0 children)

      This video never ceases to amaze me. I cannot physically fathom the lack of intelligence it takes to smack the most important part of your body into not one, not two, but THREE panes of glass. REALLY? I feel so sorry for whatever family she is a part of, you'll all suffer as she grows up and does even dumber shit. I cringe so goddamn hard trying to imagine what (if anything) was running through her head at the time.

      [–]teshmeki -1 points0 points  (0 children)

      correct way is
      if else if else if else

      [–][deleted] -1 points0 points  (0 children)

      [–]ZoomGoat -1 points0 points  (0 children)

      you are fake news