Codewars第三天--The museum of incredible dull things

41 篇文章 1 订阅

Codewars第三天–The museum of incredible dull things

题目描述:
The museum of incredible dull things wants to get rid of some exhibitions. Miriam, the interior architect, comes up with a plan to remove the most boring exhibitions. She gives them a rating, and then removes the one with the lowest rating.
However, just as she finished rating all exhibitions, she's off to an important fair, so she asks you to write a program that tells her the ratings of the items after one removed the lowest one. Fair enough.
Task
Given an array of integers, remove the smallest value. Do not mutate the original array/list. If there are multiple elements with the same value, remove the one with a lower index. If you get an empty array/list, return an empty array/list.
Don't change the order of the elements that are left.

Examples
remove_smallest([1,2,3,4,5]) = [2,3,4,5]
remove_smallest([5,3,2,1,4]) = [5,3,2,4]
remove_smallest([2,2,1,2,1]) = [2,2,2,1]

这题需要我们找出给定的一个数组的最小值,并移除他,如果最后数组为空,则返回一个空数组,如果存在多个相同的最小值,则移除下标最小的那个值。最后结果中的数组顺序不能够改变。最最重要的一点就是:
Do not mutate the original array/list.
开始没反应过来这个问题,以为只要数组的顺序不变,就改变没有mutate 原数组。在这里没用用python3自带的min() 来写,用了一个for 循环找最小值的索引。开始代码如下:

def remove_smallest(numbers):
    #raise NotImplementedError("TODO: remove_smallest")
    if len(numbers) == 0:
        return numbers
    else:
        key = numbers[0]
        temp = 0
        new_num = []
        for i in range(1, len(numbers)):
            if numbers[i] < key:
                key = numbers[i]
                temp = i
        del numbers[temp]
        return numbers

这样的结果是test用例都通过了,但是出现了一个错误:
check for mutations to original list
Mutated list: [373, 370] should equal [373, 370, 134]

开始一直想不通就去看了论坛,发现很多人都提出了这个问题。解决办法都说去修改自己的代码,因为真的改变了初始的数组。又回头仔细看了下代码,发现我真的改变了原始数组,问题出在我移除最小值的那句语句:del numbers[temp] 。我对初始数组进行了删除操作,将初始数组的元素减少了一个。很多人都忽略了这个问题。因此,在这里不能够直接删除掉原数组的最小值来得到最后的结果,而是需要将最小值找出来,然后越过这个值,将其他值链接起来。代码如下:

def remove_smallest(numbers):
    #raise NotImplementedError("TODO: remove_smallest")
    if len(numbers) == 0:
        return numbers
    else:
        key = numbers[0]
        temp = 0
        new_num = []
        for i in range(1, len(numbers)):
            if numbers[i] < key:
                key = numbers[i]
                temp = i
        return numbers[0:temp] + numbers[temp+1:]
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值