How to convert this function from javascript to python?

Does anybody know how to convert this javascript function to python ?

javascript:

function ding(t, a, e, n) {
  return t > a && t <= e && (t += n % (e - a)) > e && (t = t - e + a), t
}

This is my try on doing so:

def ding(t, a, e, n):
    return t > a and t <= e and (t + n % (e - a)) > e and (t = (t - e + a)), t

It returns a syntax error at the "=" in (t = (t - e + a)) and idk how to solve this right.

When giving it these values: ding(53, 47, 57, 97) it should return 50 in the original javascript function.

2 answers

  • answered 2022-01-24 20:27 lusc

    Does it have to be a one-liner? Why not just split it into a few lines:

    def ding(t, a, e, n):
        if t > a and t <= e:
            t += n % (e - a)
    
            if t > e:
                t -= e - a
        
        return t
        
    print(ding(53, 47, 57, 97)) # 50
    

  • answered 2022-01-24 20:29 KokoseiJ

    that is because python doesn't support evaluating value assignment as assigned value. (t = (t - e + a)) causes SyntaxError instead of returning (t - e + a).

    && operators on the original code seems to be used to eliminate the usage of if operators. This should behave the same way as it did on JS.

    def ding(t, a, e, n):
        if a < t <= e:
            t += n % (e - a)
            if t > e:
                t -= (e - a)
        return t
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum