0

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.

XEOX
  • 27
  • 5
  • You need to use the walrus operator `:=` to use an assignment in an expression. – Barmar Jan 24 '22 at 20:24
  • Python's comma operator isn't the same as JS's. You're creating a tuple in the python version. – Barmar Jan 24 '22 at 20:24
  • I suggest you first convert the JS version to `if` syntax instead of ternary. Then it will be easier to see how to convert it to Python. – Barmar Jan 24 '22 at 20:25
  • 1
    Is there a reason why you're trying to do this all in one line with minified variable names? – Samathingamajig Jan 24 '22 at 20:26
  • @Barmar I tried doing so `t := (t - e + a)`, but it still returns a bad value 43, it should return 50 – XEOX Jan 24 '22 at 20:27
  • @Samathingamajig Not really, but I just got told to convert it as it is so ... – XEOX Jan 24 '22 at 20:28
  • You also need to use `t := t + n % (e - a)` – Barmar Jan 24 '22 at 20:29
  • Technicaly it would be possible to do this in one line with something like this https://stackoverflow.com/questions/37315247/python-one-line-return-value-if-availab-if-not-return-none but it wouldn't be very clean – 35308 Jan 24 '22 at 20:37

2 Answers2

1

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
lusc
  • 1,206
  • 1
  • 10
  • 19
0

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
KokoseiJ
  • 163
  • 6