Reputation: 103
So here is the problem:
Input an array of positive integers and need to return sum of all elements in new array with conditions: if Array[i] > Array[j]
then Array[i] = Array[i] - Array[j]
.
Example:
[1,2,3] => [1,2,1] => [1,1,1] => output: 3
My code:
def solution(a):
while max(a) != min(a):
u = max(a)
a[a.index(u)] = u - min(a)
return (a[0] * len(a))
But this code is very slow, how can I refactor it for better performance ?
Upvotes: 1
Views: 76
Reputation: 9010
The code you implemented roughly applies the Euclidean algorithm to a group of numbers. The following code is equivalent to yours, but more efficient:
from fractions import gcd
a = [1, 2, 3]
print reduce(gcd, a) * len(a) # 3
Whether or not your code does what you want it to do is another story. In Python 3.X, reduce
will have to be imported from functools
.
Upvotes: 2