How do I do selection sort? - python

numbers = list (input("Please enter your numbers: "))
print (numbers)
This is all I have when I start the code it only shows single digit numbers but when I put 12, I get '1' '2' how do I make it stay 12 and sort the numbers smallest to biggest?

input("Please enter your numbers: ") - this returns string
list(string) - will separate string on every character and make list of them
I think this will do what you want:
numbers = [int(x) for x in input("Please enter your numbers: ").split(' ')]
print (numbers)
I used split() function, and when i say string.split(' ') it will separate string on every ' ' and return the list.
For sorting the list you can use the built-in function sort(), or you can make your own. This page will help you to make your sorting function with selection sort.

Related

two types of input from one string

i am asking the user to input a number as well as if they think their number plus a random integer will be odd or even in the same line but cant get it to work.
I wrote
user, num = input('Enter a number 1-10: ' and '\n odd or even?').split()
Only the 2nd string is asked (odd or even?) when i run the program.
i want it to be formatted as
Enter a number 1-10: \n
odd or even?
How do I take two different types of inputs using one line of code. i want the input from
'Enter a number: '
to be an int and i want the input from
'odd or even' to be a str
Well, you can simply use two lines of input. something like this:
num = int(input('Enter your number: '))
state = input('Odd or Even?')
Remove and it will work
>>> user, num = input('Enter a number 1-10: odd or even? ').split()
Enter a number 1-10: odd or even?10 3
>>> user
'10'
>>> num
'3'
>>>
input() outputs strings. You may have to convert it to int using int(num).
try this line:
user, num = input('Enter a number 1-10:' + '\nodd or even?\n').split()

Sequence of numbers - python

i create a program that reads a sequence of numbers, determines how many different numbers there are (we count the repetitions once), and writes the result to the standard output.
my first code:
f=int(input("String of numbers: "))
l=[]
for x in range(f):
string_numbers = int(input(f'Enter {x+1} string of numbers: '))
l.append(string_numbers)
mylist = list(dict.fromkeys(l))
print(len(mylist))
I wanted to take into account if the user entered a string too short or too long than declared. I wanted the user to type everything on one line. When I enter an incorrect string number, I get duplicated "incorrect string lengthincorrect string length"
f=int(input("String of numbers: "))
my_list = input('Enter numbers in the string, separated by spaces: ').split()
list_of_integers=[]
l=len(str(list_of_integers))
for i in my_list:
list_of_integers.append((i))
mylist = list(dict.fromkeys(list_of_integers))
for i in range(f):
if i < l:
print("incorrect string length", end='')
elif i > l:
print("incorrect string length", end='')
else:
It seems like you're mixing up your different variables -- f is what you want the length to be, l is just the number 2, and the way you're comparing those two has nothing to do with the actual input entered by the user, which is my_list.
Using variable names that indicate their meaning might make it easier to keep it all straight:
num_count = int(input("Length of string of numbers: "))
num_list = input('Enter numbers in the string, separated by spaces: ').split()
if len(num_list) == num_count:
print(f"there are {len(set(num_list))} different numbers")
else:
print("incorrect string length")
In the above code, num_count is the count of how many (non-unique) numbers you expect them to input, and num_list is the actual list. To figure out if the list is the expected length, compare num_count to len(num_list).
Note that since all you're doing is looking for unique values, converting the strings in num_list to int is not necessary (whether or not you use a set as I've done here).
You will most likely be better off using another function that ultimately has a while loop. This will make sure that when the user is giving the input that if anything is malformed you can then parse it checking and finally making sure to prompt the user again.
For example:
f=int(input("String of numbers: "))
my_list = input('Enter numbers in the string, separated by spaces: ').split()
list_of_integers=[]
l=len(str(list_of_integers))
for i in my_list:
list_of_integers.append((i))
mylist = list(dict.fromkeys(list_of_integers))
for i in range(f):
# XXX Here call your "input-function"
get_user_input(i, l)
def get_user_input(user_len, len):
while True user_len != len:
print('Incorrect Input')
user_len = int(input("String of numbers: "))
return
This is not exactly a working example but with what you have you get the idea that you want to do a while loop until your inputs match.

How to get input numbers from the user and sort it before printing it in python

I want to get input numbers from the user and sort it then print it. But it gives attribute error:
AttributeError: 'str' object has no attribute 'sort'
-- with the code--
lucky_numbers = input("Write your favourite numbers: ")
ans = (lucky_numbers)
ans.sort()
print(ans)
Using split():
lucky_numbers = input("Write your favourite numbers with a space: ")
numberList = lucky_numbers.split()
numberList.sort()
print(numberList)
OUTPUT:
Write your favourite numbers with a space: 50 40 -10
['-10', '40', '50']
EDIT:
If you want to have the values in int:
numberList = [int(x) for x in numberList]
This can be possible answer. You also need to convert str values to int
lucky_numbers = input("Write your favourite numbers: ")
ans = lucky_numbers.split()
ans_int = [int(i) for i in ans]
ans_int.sort()
print(ans_int)
You can't sort it because the input function returns the string that has been typed by the user so it will be a string not a list and you can't sort it. Your approach must change and you must store user input and numbers in a list.
Something like this may work:
lucky_numbers = []
while True:
user_input = input('enter your favourite number or to exit enter Q:')
if user_input == 'Q':
break
else:
lucky_numbers.append(int(user_input))
lucky_numbers.sort()
print(lucky_numbers)
This only works for integers and there is more stuff you can do for type checking and making sure that user input is a number or no or the list is empty or not. It was just a simple example to show the overall process.

How do I separate the numbers from an input in order to add them?

I am trying to have the user input a series of numbers (separated by commas) to receive the total of them.
I have tried (with no luck):
values = input("Input some comma seprated numbers: ")
numbersSum = sum(values)
print ("sum of list element is : ", numbersSum)
values = input("Input some comma seprated numbers: ")
list = values.split(",")
sum(list)
print ("The total sum is: ", sum)
If the user inputs 5.5,6,5.5 the expected output will be 17.
You're almost there.
After splitting, the values will still be strings, so you have to map them to float.
values = "5.5,6,5.5" # input("Input some comma seprated numbers: ")
L = list(map(float, values.split(",")))
print ("The total sum is: ", sum(L))
Output:
The total sum is: 17.0
Side note: Please don't name your variables list or sum, otherwise you will shadow the python built-ins!
After you split the values by comma into a list, you need to convert them from strings to numbers. You can do that with
values = input("Input some comma seprated numbers: ")
lst = values.split(",")
lst = [float(x) for x in lst]
total = sum(lst)
print("The total sum is: ", total)
For reference, see List Comprehensions in Python.
(Also, you shouldn't use list as a variable name, since that's a function in Python.)
You have to convert the inputs to float:
numbers = input("Input some comma seprated numbers: ")
result = sum([float(n) for n in numbers.split(',')])
print(result)
You have to convert to numbers before adding them together.
For example, you could convert them all into floats:
input_str = input("Input some comma seprated numbers: ")
# Option1: without error checking
number_list = [float(s) for s in input_str.split(',')]
# Option2: with error checking, if you are not sure if the user will input only valid numbers
number_list = []
for s in input_str.split(','):
try:
n = float(s)
number_list.append(n)
except ValueError:
pass
print("The list of valid numbers is:", number_list)
print("The sum of the list is:", sum(number_list))
# empty list to store the user inputs
lst = []
# a loop that will keep taking input until the user wants
while True:
# ask for the input
value = input("Input a number: ")
# append the value to the list
lst.append(value)
# if the user wants to exit
IsExit = input("enter exit to exit")
if 'exit' in IsExit:
break
# take the sum of each element (casted to float) in the lst
print("The sum of the list: {} ".format(sum([float(x) for x in lst])))
OUTPUT:
Input a number: 5.5
enter exit to exitno
Input a number: 6
enter exit to exitno
Input a number: 5.5
enter exit to exitexit
The sum of the list: 17.0
It's hard to know what went wrong w\o a sample of the error\output code.
I think the issue is in getting the sum of list (very bad name btw) when it's a list of strings.
please try the following
values = input("Input some comma seprated numbers: ")
lst = values.split(",")
lst = [int(curr) for curr in lst]
sum(lst)
print ("The total sum is: ", sum)
This code will work when expecting integers, if you want floats then change the list comprehension.
Try not to name objects with the same name of standard objects such as list,int,str,float etc...
use below
print('sum of input is :',sum(list(map(float,input('Input some comma separated numbers: ').split(',')))))

Python checking for number in input

I need to write a program that will check the numbers that a user enters. If the user enters a number more than once then it will skip over it and print out only numbers that the user entered once.
I was playing around with this:
def single_element():
numbers = []
numbers = input("Enter some numbers: ").split()
for i in numbers:
if i in numbers:
i + 1 #I was trying to find a way to skip over the number here.
print(numbers)
You can build a set to just print unique numbers:
numbers = input("Enter some numbers: ").split()
print set(numbers)
Use a set. They are iterables, like lists, and can easily be converted back and forth. However, sets do not contain duplicate values.
def single_element():
numbers = list(set(input("Enter some numbers: ").split()))
print(numbers)
In this function, you get the input numbers as a list and convert them to a set, which will remove duplicates, and then convert back to a list.
Note: sets are not guaranteed to keep the same order like lists.

Categories

Resources