简体   繁体   English

递归地将数字添加到排序列表

[英]Add number to sorted list recursively

I want to add my_num to where it fits in the given list and I want to solve it by using this structure, however I'm not getting the right results.我想将 my_num 添加到给定列表中它适合的位置,我想通过使用此结构来解决它,但是我没有得到正确的结果。 What can I do?我能做什么?

my_lst   = [1, 3, 5]
my_num   = 4

def new_number(lst):
    return lst

def plus_number(n, lst):
    
    def add_number(n2, lst2):
        for i in range(len(lst)):
            if lst2[0] > n2:
                return [n2] + lst2
            else:
                return [lst[0]] + add_number(n2, lst2[1:])
    
    return new_number(add_number(n, lst))

result = plus_number(my_num, my_lst)

print(result)

>>> [1, 1, 4, 5]

Edit: changed [lst[0]] to [lst2[0]] and it works.编辑:将[lst[0]]更改为[lst2[0]]并且有效。 Thanks!谢谢!

There is already a stdlib method for this, no need to reinvent it:已经有一个 stdlib 方法,不需要重新发明它:

>>> from bisect import insort
>>> my_lst = [1, 3, 5]
>>> insort(my_lst, 4)
>>> my_lst
[1, 3, 4, 5]

I've two solutions:我有两个解决方案:

  1. Using a sentinel, enumerate and insert.使用哨兵,枚举和插入。
my_lst = [1, 3, 5]
my_num = 4
my_lst.append(my_num) # sentinel
for i, value in enumerate(my_lst):
    if my_num <= value:
        my_lst.insert(i, my_num)
        break
my_lst.pop() # remove sentinel
print(my_lst)
  1. Using enumerate, insert and else:使用枚举、插入和其他:
my_lst = [1, 3, 5]
my_num = 4
for i, value in enumerate(my_lst):
    if my_num <= value:
        my_lst.insert(i, my_num)
        break
else:
    my_lst.append(my_num)
print(my_lst)

If you can't use break, you can circumvent that with a function.如果你不能使用 break,你可以用一个函数来绕过它。 Note that this will be trickier for the first function.请注意,这对于第一个函数来说会比较棘手。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM