How to accept input into array and sort it?
Good day, I am new to programming and new to Python Language.
I would like to try to code the user is asked to input 10 numbers and then display it in ascending order. I am not sure on how to make this work. Here is what I have:
print("Input 10 numbers:")
num = list(map(int, input().split()))
num.sort()
print("Element value in ascending order:")
print(*num)
But this code is list. I need to accept the input and then make it as an array and then sort it into ascending. Thanks in advance.
You can do so like this:
nums = input()
# say user inputs 1 2 3 4 ....10
nums = nums.split() # converts it to a list of strings
nums = [int(num) for num in nums] # convert them to ints
print(sorted(nums))
You can also test if the strings can be converted into ints or not to make you code more robust.
Related
The problem is:
we write down a code
x = int(input("enter the number here"))
then we loop that 5 times with range and we want python to tell us which number is the greatest of all for example
1,10,100,1000
the greatest number is 1000
how can we do that?
I just do not know how to do it
Here is an easy approach:
nums = (input().split(','))
print(max(list(map(int, nums))))
As the input is taken as a string, when converting it to a list, the elements will be strings. The function map will convert each string in the list to an integer.
I don't know if it's exactly what you want but here is an input combined with a for loop in a range :
answers = []
for i in range(5):
x = int(input("enter the number here : "))
answers.append(x)
greatest_number = max(answers)
print("The greatest number is {}".format(greatest_number))
You can do it by splitting the input with respect to ",". After splitting the str should be turn into int using for loop. Now use max function with the new integer list to get the maximum number.
so your final code should be:
x = input("enter the number here: ")
list = x.split(",")
int_list = []
for s in list:
int_list.append(int(s))
max_num = max(int_list)
This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 4 months ago.
I want to know how to take an input from the user as a list. For instance, there will be a message wanting input from the user and the user will input [1,2,3]. Then, the program will create a new variable with a type list and assign the input to that variable. (I've tried to use the enter code function but I couldn't figure it out since It's my first time asking a question so, that's why I explained my code instead of writing it)
You can use list comprehension for this. It provides a concise way to create lists. The code in the square brackets asks the user for input, splits the input into a text based list, and then converts the values in the list to integers. Unfortunately, you can't create variables unless they are explicitly written in the code.
Code
x = [int(val) for val in input("Enter your numbers: ").split()]
print(x)
Input:
Enter your numbers: 1 2 3 4 5
Output:
[1, 2, 3, 4, 5]
Additional link:
https://www.geeksforgeeks.org/python-get-a-list-as-input-from-user/
do you mean something:
inp = input("Type something")
l = [inp.split(" ")]
As far as I have understood your question, you want to make a list from the set of inputs of numbers having comma or space.
a = list(input("Enter your number: "))
b = [int(elements) for elements in a if elements not in (" ",",",'[',']')]
# Remove int if you are doing for strings
print(b)
Output:
Enter your number: [1,2,3]
[1 ,2 ,3]
This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 5 years ago.
I am trying to create a piece of code that allows me to ask the user to enter 5 numbers at once that will be stored into a list. For instance the code would would be ran and something like this would appear in the shell
Please enter five numbers separated by a single space only:
To which the user could reply like this
1 2 3 4 5
And then the numbers 1 2 3 4 5 would be stored into a list as integer values that could be called on later in the program.
Your best way of doing this, is probably going to be a list comprehension.
user_input = raw_input("Please enter five numbers separated by a single space only: ")
input_numbers = [int(i) for i in user_input.split(' ') if i.isdigit()]
This will split the user's input at the spaces, and create an integer list.
You can use something like this:
my_list = input("Please enter five numbers separated by a single space only")
my_list = my_list.split(' ')
This could be achieved very easily by using the raw_input() function and then convert them to a list of string using split() and map()
num = map(int,raw_input("enter five numbers separated by a single space only" ).split())
[1, 2, 3, 4, 5]
You'll need to use regular expressions as the user may also enter non-integer values as well:
nums = [int(a) for a in re.findall(r'\d+', raw_input('Enter five integers: '))]
nums = nums if len(nums) <= 5 else nums[:5] # cut off the numbers to hold five
Here is a subtle way to take user input into a list:
l=list()
while len(l) < 5: # any range
test=input()
i=int(test)
l.append(i)
print(l)
It should be easy enough to understand. Any range range can be applied to the while loop, and simply request a number, one at a time.
Basically all I'm trying to do is get the list to sort and display in different ways. But it seems after I do the first print it will get "TypeError: 'int' object is not callable". I'm assuming that's because I'm at the end of the list and need to restart at the beginning? Not sure how to do that or if that's the reason.
##vars
Index = 0
NumSize = 0
NumInput = 0
ManNum = 0
##Asking for list size
NumSize = int(input("How many numbers would you like to enter?:\n====>"))
##Declaring list
Numbers = [0] * NumSize
##Collecting data
for Index in range(NumSize):
NumInput = int(input("Please enter a number:\n====>"))
Numbers[Index] = NumInput
##Getting highest number
MaxNum = max(Numbers)
##Printing list
print("::::The numbers you entered were::::")
for Numbers in Numbers:
print(Numbers)
##Sorting list small to large
Numbers.sort()
print("::::The numbers while sorted::::")
for Numbers in Numbers:
print(Numbers)
##Sorting list large to small
Numbers.reverse()
print("::::The numbers reversed::::")
for Numbers in Numbers:
print(Numbers)
##Printing largest number
print("::::Largest number::::\n",
MaxNum)
You use
for Numbers in Numbers:
print(Numbers)
You should not name your iterating variable the same name as your collection
try this
for number in Numbers:
print(number)
do not call the iterator with the same name as the collection, as you overwrite the later
for Numbers in Numbers:
this destroys "Numbers" array and after the loop "Numbers" is the last element of "Numbers" instead. Change all loops to
for number in Numbers:
Use anything instead of Numbers in your for loop,
so that
for i in Numbers:`
dosomething
If you print Numbers then you will see that it just carry last number you inserted in the list.
print Numbers
>>> #last Number of List
Use a different variable than Numbers in your loops. You can also use sorted(Numbers) and reversed(Numbers) to reduce the amount of variable assignments you have to do. If you don't plan to reuse MaxNum, you can do that directly in the print as well.
Here is the fully updated program:
##vars
Index = 0
NumSize = 0
NumInput = 0
##Asking for list size
NumSize = int(input("How many numbers would you like to enter?:\n====>"))
##Declaring list
Numbers = [0] * NumSize
##Collecting data
for Index in range(NumSize):
NumInput = int(input("Please enter a number:\n====>"))
Numbers[Index] = NumInput
##Printing list
print("::::The numbers you entered were::::")
for number in Numbers:
print(number)
##Sorting list small to large
print("::::The numbers while sorted::::")
for number in sorted(Numbers):
print(number)
##Sorting list large to small
print("::::The numbers reversed::::")
for number in reversed(Numbers):
print(number)
##Printing largest number
print("::::Largest number::::")
print max(Numbers)
The answer is already given above. But for the explanation purpose here is what is going wrong.
>>> Numbers = [1, 4 , 10, 8] #This is creating a list.
>>> for Numbers in Numbers: #Now when you are iterating it definately gives the result
... print(Numbers)
...
1
4
10
8
>>> Numbers #But now check what is in Numbers
8
>>>
You didn't wanted the above.
Note: >>> is the python interpretor prompt
As mentioned in the comment, please start writing code in pythonic way.
Which is:
You do not need to initialize variables like you did. You just need to assign them before you use them.
When you ask for the inputs. you do need to go do list[index] instead you could use append method.
i know i can use the input function in conjunction with the eval function to input a list of numbers:
numbers = eval(input("enter a list of numbers enclosed in brackets: "))
Also, given a list named items, i can get the list of all the elements of items, except the first one, with
the expression:
items[1:]
im just not sure how to go about getting the program to do what i want it to do
If you have a list and you want to know if the first value appears again later in the list, you can use:
items[0] in items[1:]
That will return True or False depending on whether the first element in items appears again later in items.
Don't use eval, ast.literal_eval is safer
import ast
numbers = ast.literal_eval(raw_input("enter a list of numbers enclosed in brackets: "))
An easier solution will be
x = l[0]
l[0] = None
print x in l
l[0] = x
The advantage is that you don't need to recreate the list
There are two parts to your problem:
get a list of numbers from the user
check if the first number is repeated in this list
There are several ways to get a list of numbers from a user. Since you seem to be new to python, I will show you the easiest way to program this:
n = raw_input("How many numbers in your list?: ")
n = int(n) # assuming the user typed in a valid integer
numbers = []
for i in range(n):
num = raw_input("enter a number: ")
num = int(num)
numbers.append(num)
# now you have a list of numbers that the user inputted. Step 1 is complete
# on to step 2
first_num = numbers[0]
for n in numbers[1:]:
if n == first_num:
print "found duplicate of the first number"
Now, there are more elegant ways to accomplish step 1. For example, you could use a list comprehension:
numbers = [int(n) for n in raw_input("Enter a bunch of space-separated numbers: ").split()]
Further, step 2 can be simplified as follows:
if numbers[0] in numbers[1:]:
print "found duplicates of the first number"
Hope this helps