I wanted to compute the below equation but using list comprehension in Python. How would I be able to do so?
Below is the equation:-
Below are the values of x,y and n-
x=54
y=12
n= Varies from range (1,5)
CodePudding user response:
You could try something like below:
x=54
y=12
n=5
print(sum([(x - y) ** 2 for _ in range(n)]))
idea is, the inner list comprehension provides a list of (x - y) ^ 2 'n' times and then we apply the sum() on the returned list.
To understand better, try the below statement and then add the sum() to it
print([(x - y) ** 2 for _ in range(n)])