Reputation: 251
I'm learning python and I'm training myself on different exercises. For one of them I have to find the minimum sums of the product of two numbers from a list. For this I had the idea of making a list and sort it in order and to create a second list where I'll sort it in reverse order then I will make the product of the first element of each list and sum them together.
Here's a little example:
list[5, 4, 2, 3]
list_sorted = [2, 3]
list_sorted_rev = [5, 4]
expectation = 22
calcul made: 5 * 2 + 3 * 4
But I have a problem, when I do that in a loop, my loop iterate through the second list with the first value of my first list and then it goes to the second value of my first list.
Here's the code I've done.
def min_sum(arr):
my_list = []
my_rev = []
srt = sorted(arr)
rev = sorted(arr, reverse=True)
rng = len(arr) / 2
res = 0
for i in range(0, int(rng)):
my_list.append(srt[i])
my_rev.append(rev[i])
for i in my_rev:
for j in my_list:
res += i * j
print(res)
Upvotes: 0
Views: 451
Reputation: 447
This is because you're using a nested loop which makes it iterate over the first list multiple times. You can use this code instead:
def min_sum(arr):
my_list = []
my_rev = []
srt = sorted(arr)
rev = sorted(arr, reverse=True)
rng = len(arr) / 2
res = 0
for i in range(0, int(rng)):
my_list.append(srt[i])
my_rev.append(rev[i])
for ind in range(len(my_rev)):
res += my_rev[ind] * my_list[ind]
print(res)
min_sum([5, 4, 2, 3])
Upvotes: 2
Reputation: 1153
Instead of using the nested for loops:
for i in my_rev:
for j in my_list:
res += i * j
You must iterate over both list simultaneously. This can be done using zip(*iterables):
for i, j in zip(my_rev, my_list):
res += i * j
Upvotes: 2