|
发表于 2018-7-23 23:31:36
|
显示全部楼层
判断浮点数是否相等,可以用判断两者是否足够接近的方法
- import math
- def fun(lst):
- if len(lst) >1:
- lst = sorted([(abs(len(lst)*i - sum(lst)), i) for i in lst],
- key=lambda x:x[0]) # 这个key指明才能保证元组顺序
- return (lst[0][1], lst[1][1]) if math.isclose(lst[0][0], lst[1][0]) \
- and lst[0][1] != lst[1][1] else (lst[0][1],)
复制代码
不要排序那个推导式和三元操作符,消耗小得多
- import math
- def fun2(lst):
- length = len(lst)
- average = sum(lst) / length
- result, minimum = (lst[0],), max(lst)
- for i in lst:
- temp = abs(i - average)
- if math.isclose(temp, minimum) and i not in result:
- result = result[0], i
- elif temp < minimum:
- minimum = temp
- result = i,
-
- return result
复制代码
换成又能列表元组又能直接一串数字,
试下不用浮点型,确定精度后直接在整型里处理
- def fun3(*args, ndigits=9):
- """args参数为列表或元组或直接一组数字,数据保留小数点后ndigits位,返回元组"""
-
- if not isinstance(args[0], int):
- args = args[0]
-
- if len(args) > 1:
- args_cp = [round(i * 10**ndigits) for i in args]
- dic = {j: abs(len(args_cp) * i - sum(args_cp)) for i, j in zip(args_cp, args)}
-
- lst = sorted(dic, key=lambda x: (dic[x], args.index(x)))
- return (lst[0],) if dic[lst[0]] != dic[lst[1]] else (lst[0], lst[1])
复制代码 |
评分
-
查看全部评分
|