Nearest Value

 

问题描述:

Find the nearest value to the given one.

You are given a list of values as set form and a value for which you need to find the nearest one.

(需要找到最接近目标值的值)

For example, we have the following set of numbers: 4, 7, 10, 11, 12, 17, and we need to find the nearest value to the number 9. If we sort this set in the ascending order, then to the left of number 9 will be number 7 and to the right - will be number 10. But 10 is closer than 7, which means that the correct answer is 10.

A few clarifications:

  • If 2 numbers are at the same distance, you need to choose the smallest one;
  • The set of numbers is always non-empty, i.e. the size is >=1;
  • The given value can be in this set, which means that it’s the answer;
  • The set can contain both positive and negative numbers, but they are always integers;
  • The set isn’t sorted and consists of unique numbers.

Input: Two arguments. A list of values in the set form. The sought value is an int.

Output: Int.

def nearest_value(values: set, one: int) -> int:
    # your code here
    return None


if __name__ == '__main__':
    print("Example:")
    print(nearest_value({4, 7, 10, 11, 12, 17}, 9))

    # These "asserts" are used for self-checking and not for an auto-testing
    assert nearest_value({4, 7, 10, 11, 12, 17}, 9) == 10
    assert nearest_value({4, 7, 10, 11, 12, 17}, 8) == 7
    assert nearest_value({4, 8, 10, 11, 12, 17}, 9) == 8
    assert nearest_value({4, 9, 10, 11, 12, 17}, 9) == 9
    assert nearest_value({4, 7, 10, 11, 12, 17}, 0) == 4
    assert nearest_value({4, 7, 10, 11, 12, 17}, 100) == 17
    assert nearest_value({5, 10, 8, 12, 89, 100}, 7) == 8
    assert nearest_value({-1, 2, 3}, 0) == -1
    print("Coding complete? Click 'Check' to earn cool rewards!")

由于集合(set)是一个无序的不重复元素序列。所以我的想法是把集合变成列表,把目标数字加入到列表,然后重新排序。找到加入数字的索引,利用索引找到相邻的数字,然后再比较。

def nearest_value(values: set, one: int) -> int:
    # your code here
    new=list(values)
    new.append(one)
    new.sort()
    p=new.index(one)
    if new[p]==new[-1]:
        return new[-2]
    elif p==0:
        return new[1]
    else:
        if abs(new[p-1]-one)<=abs(new[p+1]-one):
            return new[p-1]
        else:
            return new[p+1] 

其他解决方案:

def nearest_value(values: set, one: int) -> int:
    return min(values, key=lambda n: (abs(one - n), n))

果然能靠一行代码就行,学习一下lamda和min。

min(iterable*[, keydefault])

min(arg1arg2*args[, key])

返回可迭代对象中最小的元素,或者返回两个及以上实参中最小的。

如果只提供了一个位置参数,它必须是可迭代的,返回可迭代对象中最小的元素;如果提供了两个及以上的位置参数,则返回最小的位置参数。

有两个可选只能用关键字的实参。key 实参指定排序函数用的参数,如传给list.sort()的。default 实参是当可迭代对象为空时返回的值。如果可迭代对象为空,并且没有给 default ,则会触发ValueError。

如果有多个最小元素,则此函数将返回第一个找到的。这和其他稳定排序工具如 sorted(iterable, key=keyfunc)[0] 和 heapq.nsmallest(1, iterable, key=keyfunc) 保持一致。

lambda 表达式(有时称为 lambda 构型)被用于创建匿名函数。 表达式 lambda parameters: expression 会产生一个函数对象 。 该未命名对象的行为类似于用以下方式定义的函数:

def <lambda>(parameters):
    return expression

这道题让我大概搞懂了lambda和min(max),果然还是要做题,有了自己思考,再看看别人的更优解。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值