Home > Enterprise >  Remove the smallest value in a list python question
Remove the smallest value in a list python question

Time:01-25

The question asks to build a function that will return the list of numbers except the first encountered minimum number in that list. And if an empty list is provided than return an empty list. For example: [1, 2, 3, 1, 1] -> [2, 3, 1, 1] My code though is returning [2, 3] only even though the two ones in the back of the list were not encountered before the first one and thus should not be returned. My code:

def remove_smallest(numbers):
    list1 = []
    if len(numbers) == 0:
        return numbers
    for number in numbers[:len(numbers)]:
        if numbers.index(number) != numbers[numbers.index(min(numbers))]:
            list1.append(number)
    return list1

Expected: [1, 2, 3, 1, 1] -> [2, 3, 1, 1] Output: [2, 3]

CodePudding user response:

With the for loop and the if statement, you have filtered all the numbers that are not the minimum number.

def remove_smallest(numbers):
    if len(numbers) == 0:
        return numbers
    for number in numbers[:len(numbers)]:
        if(number == min(numbers)):
            numbers.remove(number)
            break
    return numbers  

This would be a better code. There is a break statement to exit the loop when the if condition is satisfied and the pointer goes into the if block.

There can be more efficient ways to solve this too.

CodePudding user response:

Take a copy of the input list then:

def remove_smallest(numbers):
    if numbers is None or len(numbers) == 0:
        return []
    copy = numbers.copy()
    copy.remove(min(numbers))
    return copy

print(remove_smallest([1,0,0,1]))

output:

[1, 0, 1]

Alternative:

def remove_smallest(numbers):
    if numbers is None or len(numbers) == 0:
        return []
    i = numbers.index(min(numbers))
    return numbers[:i]   numbers[i 1:]

CodePudding user response:

The solution is pretty simple. Use this:

def remove_smallest(numbers):
    smallest = min(numbers)
    for number in numbers:
        if number == smallest:
            numbers.remove(number)
    return numbers

Hope this is what you needed

Edit: From your problem, I assume there can be multiple smallest numbers. So instead, use this:

def remove_smallest(numbers):
    smallest = min(numbers)
    newList = []
    for number in numbers:
        if number != smallest:
            newList.append(number)
    return newList

Edit2: Ok so now I finally understood your problem. Here is the working code:

def remove_smallest(numbers):
    smallestIndex = numbers.index(min(numbers))
    print(smallestIndex)
    numbers.pop(smallestIndex)
    return numbers

print(remove_smallest([1, 2, 3, 1, 1]))

Output is: [2, 3, 1, 1] This worked on all the tests

  •  Tags:  
  • Related