• redxef@feddit.org
    link
    fedilink
    arrow-up
    16
    ·
    5 hours ago
    def is_even(n: int) -> bool:
        if n < 0:
            return is_even(-n)
        r = True
        for _ in range(n):
            r = not r
        return r
    
  • Euphoma@lemmy.ml
    link
    fedilink
    English
    arrow-up
    15
    ·
    7 hours ago
    def even(n: int) -> bool:
        code = ""
        for i in range(0, n+1, 2):
            code += f"if {n} == {i}:\n out = True\n"
            j = i+1
            code += f"if {n} == {j}:\n out = False\n"
        local_vars = {}
        exec(code, {}, local_vars)
        return local_vars["out"]
    

    scalable version

    • xthexder@l.sw0.com
      link
      fedilink
      arrow-up
      2
      ·
      4 hours ago

      Not even else if? Damn, I guess we’re checking all the numbers every time then. This is what peak performance looks like

  • ferric_carcinization@lemmy.ml
    link
    fedilink
    English
    arrow-up
    4
    ·
    5 hours ago

    I hope that the language’s ints are at most 32 bits. For 8 bits it could even be written by hand & the source code for a 32 bit version would only take up avg_line_len * 4GiB space for the source code of the function. But it might take a bit of time to compile a version that supports the full range of 64 or 128 bit ints.

    • Patches@ttrpg.network
      link
      fedilink
      arrow-up
      4
      ·
      edit-2
      3 hours ago

      My mate, Paul, says all numbers after 700 repeat so we can stop there.

      We just give them different names so you think they’re going up.

  • Caveman@lemmy.world
    link
    fedilink
    arrow-up
    12
    ·
    edit-2
    8 hours ago

    I’ll join in

    const isEven = (n) 
      => !["1","3","5","7","9"]
        .includes(Math.round(n).toString().slice(-1)) 
    
    • Two9A@lemmy.world
      link
      fedilink
      arrow-up
      3
      ·
      4 hours ago

      I’ve actually written exactly that before, when I needed to check the lowest bit in an SQL dialect with no bitwise operators. It was disgusting and awesome.

  • pivot_root@lemmy.world
    link
    fedilink
    arrow-up
    37
    arrow-down
    2
    ·
    edit-2
    10 hours ago

    That code is so wrong. We’re talking about Jason “Thor” Hall here—that function should be returning 1 and 0, not booleans.

    If you don't get the joke...

    In the source code for his GameMaker game, he never uses true or false. It’s always comparing a number equal to 1.

    • Aqarius@lemmy.world
      link
      fedilink
      arrow-up
      6
      ·
      6 hours ago

      Frankly, it’s what I did, too, after coming out of Uni-level C.

      My code was goddamn unreadable.

      • pivot_root@lemmy.world
        link
        fedilink
        arrow-up
        3
        ·
        edit-2
        3 hours ago

        It’s the same for a lot of people. Beginners are still learning good practices for maintainable code, and they’re expected to get better over time.

        The reason people are ragging on PirateSoftware/Jason/Thor isn’t because he’s bad at writing code. It’s because he’s bad at writing code, proclaiming to be an experienced game development veteran, and doubling down and making excuses whenever people point out where his code could be better.

        Nobody would have cared if he admitted that he has some areas for improvement, but he seemingly has to flaunt his overstated qualifications and act like the be-all, end-all, know-it-all of video game development. I’m more invested in watching the drama unfold than I should be, but it’s hard not to appreciate the schadenfreude from watching arrogant influencers destroy their reputation.

      • Croquette@sh.itjust.works
        link
        fedilink
        arrow-up
        5
        ·
        5 hours ago

        I am working with C in embedded designs and I still use 1 or 0 for a bool certain situations, mostly lines level.

        For whatever pea-brained reason, it feels yucky to me to set a gpio to true/false instead of a 1/0.

        • xthexder@l.sw0.com
          link
          fedilink
          arrow-up
          5
          ·
          edit-2
          4 hours ago

          GPIOs are usually controlled by a single bit of a register anyway. Most likely you need to do something like:

          // Set high
          PORTB |= 1 << PINB5;
          // Set low
          PORTB &= ~(1 << PINB5);
          
          • Croquette@sh.itjust.works
            link
            fedilink
            arrow-up
            2
            ·
            2 hours ago

            I am a lazy dev (not really, clients always want fast code), so I use the provided HAL libraries 99.9% of the time.

            But I have seen code where someone would write something like

            gpio_write(PIN_X, true) 
            

            and it always stood out to me.

  • Aedis@lemmy.world
    link
    fedilink
    arrow-up
    27
    arrow-down
    1
    ·
    11 hours ago

    I’m partial to a recursive solution. Lol

    def is_even(number):
        if number < 0 or (number%1) > 0:
            raise ValueError("This impl requires positive integers only") 
        if number < 2:
            return number
        return is_even(number - 2)
    
    • tetris11@lemmy.ml
      link
      fedilink
      arrow-up
      16
      ·
      edit-2
      11 hours ago

      I prefer good ole regex test of a binary num

      function isEven(number){
         binary=$(echo "obase=2; $number" | bc)
         if [ "${binary:-1}" = "1" ]; then
               return 255
         fi
         return 0
      }
      
      • balsoft@lemmy.ml
        link
        fedilink
        arrow-up
        7
        ·
        edit-2
        10 hours ago

        Amateur! I can read and understand that almost right away. Now I present a better solution:

        even() ((($1+1)&1))
        

        (I mean, it’s funny cause it’s unreadable, but I suspect this is also one of the most efficient bash implementations possible)

        (Actually the obvious one is a slight bit faster. But this impl for odd is the fastest one as far as I can tell odd() (($1&1)))

        • tetris11@lemmy.ml
          link
          fedilink
          arrow-up
          3
          ·
          9 hours ago

          woah your bash is legit good. I thought numeric pretexts needed $(( blah )), but you’re ommiting the $ like an absolute madman. How is this wizardy possible

            • tetris11@lemmy.ml
              link
              fedilink
              arrow-up
              3
              ·
              5 hours ago

              Oh I see it, but for some reason I was taught to always use $(( arith )) instead of (( arith )) and I guess I’m just wondering what the difference is

              • balsoft@lemmy.ml
                link
                fedilink
                arrow-up
                5
                ·
                edit-2
                5 hours ago

                The difference is that (( is a “compound command”, similar to [[ (evaluate conditional expression), while $(( )) is “aritmetic expansion”. They behave in almost exactly the same way but are used in different contexts - the former uses “exit codes” while the latter returns a string, so the former would be used where you would expect a command, while the latter would be used where you expect an expression. A function definition expects a compound command, so that’s what we use. If we used $(( )) directly, it wouldn’t parse:

                $ even() $((($1+1)&1))
                bash: syntax error near unexpected token `$((($1+1)&1))'
                

                We would have to do something like

                even() { return $(($1&1)); }
                

                (notice how this is inverted from the (( case - (( actually inverts 0 -> exit code 1 and any other result to exit code 0, so that it matches bash semantics of exit code 0 being “true” and any other exit code being “false” when used in a conditional)

                But this is a bit easier to understand and as such wouldn’t cut it, as any seasoned bash expert will tell you. Can’t be irreplaceable if anyone on your team can read your code, right?

                I can’t think of many use-cases for ((. I guess if you wanted to do some arithmetic in a conditional?

                if (( $1&1 )); then echo "odd!"; else echo "even!"; fi
                

                But this is pretty contrived. This is probably the reason you’ve never heard of it.

                This (( vs. $(( )) thing is similar to how there is ( compound command (run in a subshell), and $( ) (command substitution). You can actually use the former to define a function too (as it’s a compound command):

                real_exit() { exit 1; }
                fake_exit() ( exit 1 )
                

                Calling real_exit will exit from the shell, while calling fake_exit will do nothing as the exit 1 command is executed in a separate subshell. Notice how you can also do the same in a command substition (because it runs in a subshell too):

                echo $(echo foo; exit 1)
                

                Will run successfully and output foo.

                (( being paired with $((, and ( with $(, is mostly just a syntactic rhyme rather than anything consistent. E.g. { and ${ do very different things, and $[[ just doesn’t exist.

                Bash is awful. It’s funny but also sad that we’re stuck with it.