Insert an item into sorted list in Python

前端 未结 7 956
野趣味
野趣味 2020-11-29 01:06

I\'m creating a class where one of the methods inserts a new item into the sorted list. The item is inserted in the corrected (sorted) position in the sorted list. I\'m not

7条回答
  •  醉酒成梦
    2020-11-29 01:36

    # function to insert a number in an sorted list
    
    
    def pstatement(value_returned):
        return print('new sorted list =', value_returned)
    
    
    def insert(input, n):
        print('input list = ', input)
        print('number to insert = ', n)
        print('range to iterate is =', len(input))
    
        first = input[0]
        print('first element =', first)
        last = input[-1]
        print('last element =', last)
    
        if first > n:
            list = [n] + input[:]
            return pstatement(list)
        elif last < n:
            list = input[:] + [n]
            return pstatement(list)
        else:
            for i in range(len(input)):
                if input[i] > n:
                    break
        list = input[:i] + [n] + input[i:]
        return pstatement(list)
    
    # Input values
    listq = [2, 4, 5]
    n = 1
    
    insert(listq, n)
    

提交回复
热议问题