Reputation: 21
Challenge : to find the minimum and maximum sums which can be obtained out of four elements from the list containing 5 elements.
Approach followed : Sort the list in descending and ascending order and store them into two different variables. Finding the sum of first 4 elements in both of the lists. One sum would be the minimum most and the second one would be the maximum most.
Code :
arr = [2,1,3,4,5]
arr.sort()
asc = arr
print(asc[0],asc[1],asc[2],asc[3])
arr.sort(reverse = True)
des = arr
print(des[0],des[1],des[2],des[3])
maxi = 0
mini = 0
for j in range(4) :
mini = mini + asc[j]
print(mini, asc[j])
maxi = maxi + des[j]
print(maxi,des[j])
print(mini, maxi)
Few print statements are introduced here for debugging purpose. As visible in the code, bot the sorted versions are printed before entering into the for loop and after entering into the loop. Its clearly visible as seen in the output that, the list which should be holding the elements in ascending order is having the elements in the descending order.
Output :
11 12 13 14 - list in the ascending order
15 14 13 12 - list in the descending order
15 15 - round 0
15 15
29 14 - round 1
29 14
42 13 - round 2
42 13
54 12 - round 3
54 12
54 54 - final output
why the elements present in one particular list change their order when they enter into the for loop ??
Upvotes: 2
Views: 372
Reputation: 5669
When you are doing asc = arr
and des = arr
a new list is not created. asc
, des
and arr
are linked to one list object so whey you change any of them all variables will be changed as it's single object.
In [1]: a = [1, 2]
In [2]: b = a
In [3]: id(a), id(b)
Out[3]: (140601802913048, 140601802913048)
In [4]: b = a[:]
In [5]: id(a), id(b)
Out[5]: (140601802913048, 140601819243872)
If you want to have a copy of list do
asc = arr[:]
des = arr[:]
Upvotes: 5
Reputation: 26039
You need to do:
asc = arr.copy()
# or asc = arr[:]
Or else, when arr
is sorted reverse, asc
also changes. asc
is a pointer to the array and when arr
changes, asc
changes. Better, you create a copy of arr
, so changes won't reflect back.
arr = [2,1,3,4,5]
print(sum(sorted(arr)[:4])) # 10
print(sum(sorted(arr, reverse=True)[:4])) # 14
# Or print(sum(sorted(arr)[-4:])) instead of the last print.
Upvotes: 2