So my programming assignment wants me to take a user inputted list of numbers, ints and floating, and then order them in descending order and replace any of the floating with "0". I have got the reorder part done but the replace is getting me lost.
Reading Numbers
Write a program that shall ask the user to enter several integer numbers on
the same line, separated by vertical bars surrounded by zero or more spaces
(e.g., “|” or “ |” or “| ” or “ | ”). The program then shall display the entered
numbers in the descending sorted order (from the largest to the smallest),
all on the same line, separated by vertical bars and spaces (“ | ”). If
any entry on the command line is not an integer number, the program shall
replace it with a 0. Use only “for” loop(s) or list comprehensions. Use exception
handling.
# takes input and split them to get a list
numbers = input("Please enter numbers separated by vertical bars '|' :
").split("|")
# replace the floating numbers with "0"
for number in numbers:
print(type(number))
if number.isdigit() == False:
numbers.replace(number,'0')
# takes the list and reverse order sort and prints it with a "|" in between
numbers.sort(key = float , reverse = True)
[print(number,end = ' | ') for number in numbers]
One change I made was switching all of the for number in numbers to for i in range(len(numbers)). This allows you to access the actual variable by index, while for number in numbers just gets the value.
Here is my solution. I tried to add comments to explain why I did what I did, but if you have any questions, leave a comment:
# takes input and split them to get a list
numbers = input("Please enter numbers separated by vertical bars '|'\n").split(
"|")
# strip any extra spaces off the numbers
for i in range(len(numbers)):
numbers[i] = numbers[i].strip(" ")
# replace the floating numbers and strings with "0"
for i in range(len(numbers)):
try:
# check if the number is an int and changes it if it is
numbers[i] = int(numbers[i])
except:
# set the item to 0 if it can't be converted to a number
numbers[i] = 0
# takes the list and reverse order sort and prints it with a "|" in between
numbers.sort(reverse = True)
# changes the numbers back into strings
numbers = [str(numbers[i]) for i in range(len(numbers))]
# makes sure that there are more than one numbers before trying
# to join the list back together
if len(numbers) > 1:
print(" | ".join(numbers))
else:
print(numbers[0])
the instructions permit you to use exceptions. the following should get you most of the way there.
>>> numbers = ['1', '1.5', 'dog', '2', '2.0']
>>> for number in numbers:
>>> try:
>>> x = int(number)
>>> except:
>>> x = 0
>>> print(x)
1
0
0
2
0
Related
I have written a code that should input numbers from the user and report back the numbers from 1 to 100 that are missing from their input.
My code is below which doesn't work:
num_list = []
number = input('Enter numbers (remember a space): ')
number.split()
num_list.append(number)
for i in range(1, 101):
if i in num_list:
continue
else:
print(i, end =', ')
The code outputs all the numbers from 1 to 100 but doesn't exclude the numbers.
Note: The code has to exclude all the numbers entered not only one number.
E.g. if the user inputted 1 2 3 4 the output should start from 5 and list the numbers through to 100.
There are three of problems
1) your are not saving the returned list from split method
result = number.split()
2) Use extend instead of append
num_list.extend(result)
3) By default input will read everything as string, you need to convert them into int from string after splitting, below is example using List Comprehensions
result = [int(x) for x in number.split()]
append : Will just add an item to the end of the list
So in you case after appending user input your list will be
num_list.append(number) #[[1,2,3,4,5]] so use extend
extend : Extend the list by appending all the items from the iterable.
num_list.append(number) #[1,2,3,4,5]
Note : If the num_list empty you can directly use result from split method, no need of extend
I want to make a Python script which has the user enter 7 numbers and then check which numbers can be divided by 3, then sum those numbers, and show it to the user as "sum=xx".
I tried:
input_string = input("Enter a list element separated by space ")
list = input_string.split()
Here is using list comprehension,
input_string = input("Enter a list element separated by space ")
numbers = [int(num) for num in input_string.split(',') if int(num) % 3 == 0]
print('Sum = {}'.format(sum(numbers)))
This is based on your question above.
But, you also said that you would want user to input 7 numbers and find sum for numbers which are divisible by 3.
Here is other simple example, where we ask user to input 7 numbers, one number at a time and print sum at the end.
all_numbers = []
for i in range(7):
num = int(input(f'Enter number {i + 1}:\n1'))
all_numbers.append(num)
sum_of_numbers = sum([num for num in all_numbers if num % 3 == 0])
print(f'Sum = {sum_of_numbers}')
You can get a list of integers from the input using the int function which gives you an integer object from a string, since the split function only gives you a list of separated strings.
input_string = input("Enter a list element separated by space ")
my_list = input_string.split()
numbers = []
for n in my_list:
numbers.append(int(n))
However, this will throw a ValueError if n is not a valid number (e.g. "a"), which you can catch with a try-exceptstatement.
Notice how I changed the name of your variable to my_list because the name list already has a meaning in Python and it's a good practice to not assign it to a variable.
If you want to do it in a single step, you can use the useful map function to apply the int function to all of the elements in list. You can check the documentation for this function, as well as any other on the python documentation, or using the help built-in function. (e.g. help(map))
numbers = map(int, my_list)
You can then check if there are 7 numbers in the list by using the len function, and if there aren't 7 you can prompt the user to input the numbers again if that is what you want to do.
>>> my_list = [1, 2, 3]
>>> len(my_list) == 3
True
If you want to keep prompting the user until there are seven numbers on your list, you can put the prompt inside a while block, like shown:
numbers = [] # We create an empty list
while len(numbers) != 7:
input_string = input("Enter a list element separated by space ")
my_list = input_string.split()
numbers = list(map(int, my_list)) # Get the numbers
After getting the numbers, you can see which ones are divisible by 3 by using the modulo operator, which gives you the rest of dividing a number by another (3 in your case). Some examples:
>>> 7%3 # 7 = 3*2 + 1
1
>>> 19%5 # 14 = 5*3 + 4
4
>>> 8%4 # 8 = 4*2 + 0
0
Since you want to check which numbers of your list are divisible by 3 you can check whether this module is 0 or not inside of a loop through the list.
If the numbers are divisible by 3, you can add them to a counting variable, you could initialize to 0 before the loop. That way, after the loop you'd get the sum you want in this variable.
Another, more elegant way of doing so is using a list comprehension instead of a loop, which would only retain the numbers divisible by 3, and then sum its elements using the sum function.
new_list = [x for x in numbers if x%3 == 0]
sum = sum(new_list)
The code I'm working on takes an input, and is meant to return a "staircase" of hashes and spaces. For instance, if the input was 5, the result should be:
#
##
###
####
#####
I've turned the input into a list of spaces and hashes, and then converted that to a string form, in order to insert \n in every space corresponding to the length of the input (e.g. every 5 characters above). However, my code prints the result in one line. Where am I going wrong??
x = input()
list = []
a = x-1
while a > -1:
for i in range(0, a):
list.append(" ")
for i in range(0, (x-a)):
list.append("#")
a = a - 1
continue
z = str("".join(list))
t = 0
while t<x:
z = z[t:] + "\n" + z[:t]
t = t + x
continue
print str(z)
Start with pseudocode, carefully laying out in clear English what you want the program to do.
Get a number from the user.
Go through each number from 1 until the user's number, inclusive.
On each line, print a certain number of spaces, starting from one fewer than the user's number and going down to zero, inclusive.
On each line, also print a certain number of hash symbols, starting from one and going up to the user's number, inclusive.
Now you can turn that into Python.
First, get a number from the user. It looks like you're using Python 2, so you could use input() or try the safer raw_input() and cast that to int().
num = input()
Going through each number from one until the user's number, inclusive, means a for loop over a range. On Python 2, using xrange() is better practice.
for i in xrange(1, num+1):
This next part will combine steps 3 and 4, using string multiplication and concatenation. For the spaces, we need a number equal to the max number of lines minus the current line number. For the hash symbols, we just need the current line number. You can multiply a string to repeat it, such as 'hi' * 2 for 'hihi'. Finally, the newline is taken care of automatically as the default end character in a Python 2 print statement.
print ' ' * (num-i) + '#' * i
Put it all together and it looks like this:
num = input()
for i in xrange(1, num+1):
print ' ' * (num-i) + '#' * i
As you discovered, achieving the same effect with an intricate structure of counters, nested loops, list operations, and slicing is more difficult to debug. The problems don't stop when you get it working properly, either - such code is difficult to maintain as well, which is a pain if you ever want to modify the program. Take a look at the official Python tutorial for some great examples of clear, concise Python code.
Try this
x = input()
list1 = []
a = x-1
while a > -1:
for i in range(0, a):
list1.append(" ")
for i in range(0, (x-a)):
list1.append("#")
a = a - 1
list1.append("\n")
continue
z = str("".join(list1))
print z
Hi im trying to write a program which uses a repetition statement to allow users to enter 5 numbers and stores them in a list.Then allow the user to search the list for a number entered by the user and indicate whether the number has been found or not. Im quite stuck on this one, I've made as much of an effort as i can
data =raw_input('Please input 5 numbers: ')
print data
search =raw_input('Search for the numer: ')
for sublist in data:
if sublist[1] == search:
print "Found it!", sublist
break
data is a string, the for loop will loop over every character in this string. That's probably not what you want.
If you want to find an integer in a list of integers, split the input on whitespace and convert each to an integer using int.
ints = [int(x) for x in data.split()]
if int(search) in ints:
print "Found it"
You might try something like this
numbers = []
while len(numbers) < 5:
number = raw_input('Please input 5 numbers: ')
if number.isdigit():
numbers.append(int(number)) #may want to use float here instead of int
else:
print "You entered something that isn't a number"
search = raw_input('Search for the numer: ')
if int(search) in numbers:
print "Found it!"
your code indicates that you may be using sublists but it is unclear how you are creating them.
Issue 1: This line stores the input as a string in the variable data.
data =raw_input('Please input 5 numbers: ')
At this point it is necessary to split the string into a list, and converting the elements to integers.
If the user inputs numbers separated by a space, you can do:
data_list = data.split() # if the numbers are comma-separated do .split(',') instead
int_list = [int(element) for element in data_list]
Issue 2: The users search input should be converted to an integer
search =raw_input('Search for the numer: ')
search_int = int(search)
Issue 3: There is no need for indexing the sublist as you've attempted sublist[1].
The for-loop should then be:
for sublist in int_list:
if sublist == search_int:
print "Found it!", sublist
break
I am trying to take two long input integers (up to 10 digits) separated by space and display there sum.
I took the input into a string which are separated by space and then split them. After that I type caste them to int.
print "Enter two numbers"
a = raw_input()
a.split(" ")
sum = int(a[0]) + int(a[2])
print "\r", sum
Here I am not able to print the sum if the numbers are of even two digits.
You ignored the return value of str.split():
a.split(" ")
Assign that back to a:
a = a.split(" ")
Python strings are immutable, you cannot split the value of a in-place (let alone replace the type, splitting returns a list object rather than a new string).