I have list and k = 8 (maximum sum). I want to add those elements of list whose total sum is equal or smaller than k = 8 and I want the number of elements only whom I have added.
What I have tried:
lst = [1,2,3,4,7,9,12]
final = []
sum = 0
for i in range(len(lst)):
if sum < 8:
sum = sum +i
final.append(i)
print(final)
The list is sorted. it may be unsorted by user input. First I will sort the list. Then I will check the condition and adding one by one and append only those elements.
As this code doesn't give correct output as I want, what should I do?
as Aravind said.the i
is index not value
lst = [1,2,3,4,7,9,12]
final = []
sum = 0
for item in lst:
if sum < 8:
sum = sum +item
final.append(item)
print(final)
and according to Ram.you should not use sum
as a variable.is a keyword in python.
From what I have understood from your question.
You are given a list of elements (not necessarily sorted) and a value
k
. You must return the items of list whose sum is less than or equal tok
.
Here is the code
lst = [1,2,3,4,7,9,12]
lst.sort()
final = []
sums = 0
k = 10
for i in lst:
if sums + i <= k:
sums = sums + i
final.append(i)
print(final)
# Output
final = [1, 2, 3, 4]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.