• redxef@feddit.org
    link
    fedilink
    arrow-up
    17
    ·
    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
    18
    ·
    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
      5
      ·
      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.