功能签名:
def rank3(x,y,z, ascending=True)
给出三个整数,按顺序将它们返回到一个元组中 三个长度。可选的第四个参数(升序)说明输出是按升序排序(参数为True)还是降序(参数为False)。
示例:
§ rank3(5, 3, 4) → (3,4,5)
§ rank3(5, 3, 4, False) → (5,4,3)
§ rank3(6, 8, 6) → (6,6,8)
到目前为止,这是我的代码:
x = num1 #your first input
y = num2 #your second input
z = num3 #your third input
a = [x, y, z] #your list of inputs
b = [] #your sorted list
def rank3(x,y,z, ascending=True):
while a: # your sort function
o = a[0]
for i in a:
if i < o:
o = i
b.append(o)
a.remove(o)
return b #return your final answer
答案 0 :(得分:2)
尝试
import bisect
def rank3(x,y,z, ascending=True):
if x <= y:
ret = [x, y]
else:
ret = [y, x]
pz = bisect.bisect(ret, z)
ret.insert(pz, z)
if not ascending:
ret = ret[::-1] # or use ret.reverse()
return tuple(ret)
如果您甚至不想使用bisect
,请稍稍循环,直到找到ret
中大于z
的元素(提示,使用{{1 }})
然而,这是更短更多的pythonic
enumerate
答案 1 :(得分:0)
首先 - 尝试在内置的python函数中找到答案。 毕竟写自己的。 对于你的例子,python有一个很好的方法sorted()。你可以通过reverse()方法反转你的列表/元组。