Sum w/o Smallest Values w/o using sum() or min()

Question:

I have the problem:

Write a function def sum_without_smallest(values)
that computes the sum of a list of values, except for the smallest one, in a single loop, without using the sum() function nor the min() function.

I am struggling to understand how to do this. I’ve tried putting multiple searches on here for different parts of the code but can’t seem to figure it out.

The only code I have is the definition that it requires:

def sum_without_smsallest(values):

Reminder: I can’t use sum() or min() and it has to be in one loop.

Asked By: Mak_Ward04

||

Answers:

Iterate over the list once to get the sum of all elements, while keeping track of the smallest element so far. After the loop, the answer is the smallest element subtracted from the total.

def sum_without_smallest(values):
    m = values[0]
    tot = 0
    for v in values:
        tot += v
        if v < m: m = v
    return tot - m
Answered By: Unmitigated

Iterate over the values, keeping track of the smallest value and the running total (start with the first value as a special case). At the end, return the total minus the smallest element.

>>> def sum_without_smallest(values):
...     total = smallest = values[0]
...     for v in values[1:]:
...         total += v
...         smallest = v if v < smallest else smallest
...     return total - smallest
...
>>> sum_without_smallest([3, 4, 2, 3])
10
Answered By: Samwise

Reminder: I can’t use sum() or min() and it has to be in one loop.

Okey dokey:

import math

def sum_without_smsallest(values):
    for _ in None,:
        return math.fsum(values) - max(values, key=lambda x: -x)

Or:

import math
import itertools

def sum_without_smsallest(values):
    for _ in None,:
        return max(map(math.fsum, itertools.combinations(values, len(values) - 1)))
Answered By: Kelly Bundy
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.