user12354454
user12354454

Reputation:

Python list merge and ascending without sort or sorted

def list_merge():
    list_1 = [x for x in input("Type list 1: ").split(", ")]
    list_2 = [y for y in input("Type list 2: ").split(", ")]
    result = list_1 + list_2
    new_list = []
    while result:
        minimum = result[0]
        for x in result: 
            if x < minimum:
                minimum = x
        new_list.append(minimum)
        result.remove(minimum) 
    print(new_list)

I don't know why keep output like list. type list 1: 1, 4, 7, 10 type list 2: 4, 6, 8, 20

Output: [1, 10, 20, 4, 4, 6, 7, 8]

I want to output like this [1, 4, 4, 6, 7, 8, 10, 20]

without sort or sorted

Upvotes: 0

Views: 128

Answers (3)

Buddy Bob
Buddy Bob

Reputation: 5889

You have a list of strings as elements. So comparing will not work as intended. You can use map() to change all the elements in your list to an integer.

def list_merge():
    list_1 = [x for x in input("Type list 1: ").split(", ")]
    list_2 = [y for y in input("Type list 2: ").split(", ")]
    result = list_1 + list_2
    #here
    result = list(map(int,result))
    new_list = []
    while result:
        minimum = result[0]
        for x in result: 
            if x < minimum:
                minimum = x
        new_list.append(minimum)
        result.remove(minimum) 
    print(new_list)
list_merge()

output

Type list 1: 1, 4, 7, 10
Type list 2: 4, 6, 8, 20
[1, 4, 4, 6, 7, 8, 10, 20]

Upvotes: 0

shree.pat18
shree.pat18

Reputation: 21757

You need to cast the input elements to integers. Right now they are being treated as strings, so the sorting is being done in alphabetical order. Fix by changing like so:

list_1 = [int(x) for x in input("Type list 1: ").split(", ")]
list_2 = [int(y) for y in input("Type list 2: ").split(", ")]

Upvotes: 0

Paras Gupta
Paras Gupta

Reputation: 294

You need to convert list elements to integer type, this is only reason you are getting wrong output.

list_1 = [int(x) for x in input("Type list 1: ").split(", ")]
list_2 = [int(y) for y in input("Type list 2: ").split(", ")]

Upvotes: 1

Related Questions