This pattern transforms a loop that computes the product of a list of numbers into a call to math.prod
(introduced in Python 3.8).
Apply with the Grit CLI
grit apply math_prod
Transforms for loop to math.prod
BEFORE
from math import log n = 1 for x in range(10): n *= x n = 1.0 for x in range(10): n = n * x n = 1 for x in range(10): n = x * n prod = 1 for x in [4, 5, 6]: prod *= x # Left as is n = 1 for x in range(10): y = n * x n = 1 for x in range(10): n = y * x n = 1 for x in range(10): n *= x print("multiplied")
AFTER
from math import log import math math.prod(range(10)) math.prod(range(10)) math.prod(range(10)) math.prod([4, 5, 6]) # Left as is n = 1 for x in range(10): y = n * x n = 1 for x in range(10): n = y * x n = 1 for x in range(10): n *= x print("multiplied")