I wrote this code in JavaScript:
let b = [10, 20, 3, 4, 5, 30, 44, 90, 100];
let pairNum = 0;
for (let i = 0; i < b.length; i++) {
if (b[i] % 10 == 0) {
if (b[i + 1] % 10 == 0) {
pairNum+= 1;
}
}
}
console.log(pairNum);
But I can’t write the same code in Python because b[i+1] is not allowed. Does anyone know how to write it similar in Python?
This is my code in Python :
b = [10, 20, 3, 4, 5, 30, 44, 90, 100]
pairNum= 0
for i in range (1, len(b)):
if(b[i]%10 == 0):
if(b[i+1]%10 == 0):
pairNum+= 1
print(pairNum)
>Solution :
Change range(1, len(b)) to range(len(b)-1).
Your code is ignoring the first element because it starts the iteration at i = 1, and trying to access the element after the last element.
Or you could keep your existing range, and use b[i-1] and b[i] instead of b[i] and b[i+1].
You can also use zip() to pair each element with the following element. Since zip() stops when it gets to the end of the shortest input, you won’t go outside the list.
for curnum, nextnum in zip(b, b[1:]):
if curnum % 10 == 0 and nextnum % 10 == 0:
pairNum += 1