Search code examples
pythonfor-loopindexingfor-in-loop

Possible to rewrite for i in range loop on i, i+1 into for i in loop in Python?


Is it possible to rewrite this loop below:

from typing import List 

def adjacentElementsProduct(inputArray: List[int]) -> int:  
    product_list = []
    for i in range(len(inputArray) - 1):
        product_list.append(inputArray[i] * inputArray[i+1])
    return max(product_list)

Into something like:

for i in inputArray:
    product_list.append(i, the thing after i)

Solution

  • To get all adjacent pairs you can use zip

    pairs = zip(inputArray, inputArray[1:])
    

    Then you can use max and pass it another generator that multiplies the pairs to get the maximum sum

    max(a * b for a, b in pairs)