Wednesday, March 24, 2021

Looping over an iterable (array/list) in JavaScript Vs Python

 Lets see what it takes to loop over an iterable using for-loop in both JavaScript Vs Python. By the way, an iterable is an object capable of returning its members one at a time, permitting it to be iterated over in a for-loop.

Assuming we have this iterable : m = [3.23, 4.56, 5.3, 2.44, 6.7, 12.4, 566] and we want to perform some math operation on each element (in this case: 2 to the power of element divided by 2).

The math formulae is as follow:-

For JavaScript

Math.pow(2, element) / 2


For Python

(2**element)/2


The solutions

JavaScript Solution

m = [3.23, 4.56, 5.3, 2.44, 6.7, 12.4, 566]

for (let i=0; i<m.length; ++i){
console.log(Math.pow(2, m[i]) / 2);
}


m = [3.23, 4.56, 5.3, 2.44, 6.7, 12.4, 566]

for (let i in m){
console.log(Math.pow(2, m[i]) / 2);
}

Python Solution

m = [3.23, 4.56, 5.3, 2.44, 6.7, 12.4, 566]

for i in m:
    print((2**i)/2)




That is it!

No comments:

Post a Comment