Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

converting javascript function to python with comma operator

I have the following javascript code

var d = Math.random(),
   k = parseInt((1e3 * d)/2),
   s = d + ""

output of d : 0.6715250159864421

Similarly, I have the python code that I was able to write up and as close to

d, k, s = random.random(), int((1e3*random.random()/2)), d + ''

The output are completely different.

0.8018834108596731

Am I not using the comma operator properly

PS: I understand output is going to be different, however I want to validate that my python code is correctly translated to the shown JS snippet.

question from:https://stackoverflow.com/questions/65546679/converting-javascript-function-to-python-with-comma-operator

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In your Python code you're not using d when you calculate k, you're calculating a different random number.

In Python you can't concatenate strings with numbers. JS is using that to convert the number to a string, in Python you do that with the str() function.

The translation should be:

d = random.random()
k = int(1e3 * d) / 2
s = str(d)

In Python 3.8 you could use the "walrus" operator to assign to d in a one-liner

k, s = int(1e3 * (d := random.random())) / 2, str(d)

But this is confusing, so I don't recommend it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...