Home > front end >  Program to read 2 lists and print numbers from lists combined in reverse order
Program to read 2 lists and print numbers from lists combined in reverse order

Time:05-10

Hi I've been writing a program where the user enters numbers for two different lists and the the program prints the lists combined and sorts the numbers in reverse order (highest - lowest).

I have managed to write a program but I need a way to change it so the user enters the list in one line instead of multiple lines and then my end result isn't printing in (highest - lowest) it currently only prints (low-high)

see bellow my code

a=[]
c=[]
n1=int(input("Enter number of elements:"))
for i in range(1,n1 1):
    b=int(input("Enter element:"))
    a.append(b)
n2=int(input("Enter number of elements:"))
for i in range(1,n2 1):
    d=int(input("Enter element:"))
    c.append(d)
new=a c
new.sort()
print("Sorted list is:",new)

Output

Enter number of elements:4
Enter element:1
Enter element:3
Enter element:3
Enter element:6
Enter number of elements:3
Enter element:1
Enter element:4
Enter element:5
Sorted list is: [1, 1, 3, 3, 4, 5, 6]

how am I able to change my code so it looks like this :

list 1 : 1 2 3 4
list 2 : 5 6 7 8
output :[ 8,7,6,5,4,3,2,1]

CodePudding user response:

This would work. You could also ask for comma separated input instead.

Example input would look like this for each list: 1 2 3 4 5

lst1 = input("Enter list of space separated numbers:") # input = `2 1 4 7 5 9`
lst2 = input("Enter list of space separated numbers:")
a = [int(i) for i in lst1.split(' ') if i.isdigit()]
c = [int(i) for i in lst2.split(' ') if i.isdigit()]

new= a   c
new.sort(reverse=True)
print("Sorted list is:",new)

CodePudding user response:

To enter the list in one line do something like

a = [int(i) for i in input("list 1: ").split(" ")]

and as Albin Paul pointed out in the comments, use

new.sort(reverse=True)

to sort from highest to lowest

CodePudding user response:

1.if you want to reverse a sorted array you can use below:

new.sort(reverse=True)
  1. if you just want to reverse a list you can use:
new[::-1]#will give you a reverse list

#or else you can use predefined method 
new.reverse()

CodePudding user response:

You can get the two list in a single line and split them with spaces. And covert them to int, merge them and order in descending order.

list1 = input('Enter List 1:  ')
list2 = input('Enter List 2:  ')
list_1 = list1.split()
list_2 = list2.split()
# print list

list_1 = list(map(int, list_1))
list_2 = list(map(int, list_2))

final_list = list_1   list_2


# 1
print(sorted(final_list, reverse=True))

# 2
final_list.sort(reverse=True)
print(final_list)```
  • Related