patternpythonMinor
Taking the first few items of a list until a target sum is exceeded
Viewed 0 times
thetargetuntilfewitemsfirstsumlistexceededtaking
Problem
I'm a rank beginner in Python, and I am working my way through various relevant OpenCourseware modules. In response to the prompt
Write a procedure that takes a list of numbers, nums, and a limit,
limit, and returns a list which is the shortest prefix of nums the sum
of whose values is greater than limit. Use for. Try to avoid using
explicit indexing into the list.
I wrote the following simple procedure
It gets the job done, but the division of labor between if and else seems inelegant, as does the use of both return and print. Is there a better way to structure this basic loop?
Write a procedure that takes a list of numbers, nums, and a limit,
limit, and returns a list which is the shortest prefix of nums the sum
of whose values is greater than limit. Use for. Try to avoid using
explicit indexing into the list.
I wrote the following simple procedure
def numberlist(nums,limit):
sum=0
i=0
for i in nums:
sum=sum+i
if sum>limit:
return i
else:
print iIt gets the job done, but the division of labor between if and else seems inelegant, as does the use of both return and print. Is there a better way to structure this basic loop?
Solution
So, a couple things:
-
The problem statement says nothing about printing data, so you can omit the
-
The problem statement says to return a list, and you're just returning the last item in that list, not the entire list.
Here's a short but inefficient way to do it:
or a more efficient but longer way:
-
The problem statement says nothing about printing data, so you can omit the
print statement, and thus the entire else: clause, entirely.-
The problem statement says to return a list, and you're just returning the last item in that list, not the entire list.
Here's a short but inefficient way to do it:
def numberlist(nums, limit):
i = 0
while sum(nums[:i]) < limit:
i += 1
return nums[:i]or a more efficient but longer way:
def numberlist(nums, limit):
prefix = []
sum = 0
for num in nums:
sum += num
prefix.append(num)
if sum > limit:
return prefixCode Snippets
def numberlist(nums, limit):
i = 0
while sum(nums[:i]) < limit:
i += 1
return nums[:i]def numberlist(nums, limit):
prefix = []
sum = 0
for num in nums:
sum += num
prefix.append(num)
if sum > limit:
return prefixContext
StackExchange Code Review Q#12753, answer score: 9
Revisions (0)
No revisions yet.