Eliminate numbers between 1 and 100 present in list - python

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

Related

How to ask the user to enter numbers and then sum the numbers which are divisible by 3?

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)

Replace Floating point numbers in a list with '0'

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

How to convert only the numbers to int in a list that has numbers and char in Python

I am learning Python and while practicing, I have this type of input:
1 2 3 4 S
3 4 5 6 N
3 4 1 8 S
It will always be a set of numbers separeted by space and end with a letter (char).
I am reading it with input() and making it a list like this
data = input()
myList = data.split()
What I want is to take the list and put only the numbers to a new list.
I tried this, but it only works if the list only has int values:
myList = [int(i) for i in myList]
How can I only take the int values and put them in a new list.
NOTE: My data input always ends with a letter but it will be nice if I someone gives a solution where there are letters at any random index of the list. Thanks in advance
You just need to add a filter to the comprehension.
msj = [int(i) for i in msg if i.isdigit()]
I would do it like this
new_list = []
for item in myList:
if item.isdigit():
new_list.append(int(item))
You can take advantage of the fact that the letter will always appear at the end of the string:
newList = [int(n) for n in myList[:-1]]

list index out of range in simple Python script

I just started learning Python and want to create a simple script that will read integer numbers from user input and print their sum.
The code that I wrote is
inflow = list(map(int, input().split(" ")))
result = 1
for i in inflow:
result += inflow[i]
print(result)
It gives me an error
IndexError: list index out of range
pointing to result += inflow[i] line. Can't see what am I doing wrong?
BTW, is there more elegant way to split input flow to the list of integers?
You can also avoid the loop altogether:
inflow = '1 2 34 5'
Then
sum(map(int, inflow.split()))
will give the expected value
42
EDIT:
As you initialize your result with 1 and not 0, you can then also simply do:
sum(map(int, input.split()), 1)
My answer assumes that the input is always valid. If you want to catch invalid inputs, check Anton vBR's answer.
Considering: I just started learning Python
I'd suggest something like this, which handle input errors:
inflow = raw_input("Type numbers (e.g. '1 3 5') ") #in py3 input()
#inflow = '1 2 34 5'
try:
nums = map(int, inflow.split())
result = sum(nums)
print(result)
except ValueError:
print("Not a valid input")
for i in list gives the values of the list, not the index.
inflow = list(map(int, input().split(" ")))
result = 1
for i in inflow:
result += i
print(result)
If you wanted the index and not the value:
inflow = list(map(int, input().split(" ")))
result = 1
for i in range(len(inflow)):
result += inflow[i]
print(result)
And finally, if you wanted both:
for index, value in enumerate(inflow):
script that will read integer numbers from user input and print their
sum.
try this :
inflow = list(map(int, input().split(" ")))
result = 0
for i in inflow:
result += i
print(result)
If you were going to index the list object you would do:
for i in range(len(inflow)):
result += inflow[i]
However, you are already mapping int and turning the map object into a list so thus you can just iterate over it and add up its elements:
for i in inflow:
result += i
As to your second question, since you arent doing any type testing upon cast (i.e. what happens if a user supplies 3.14159; in that case int() on a str that represents a float throws a ValueError), you can wrap it all up like so:
inflow = [int(x) for x in input().split(' ')] # input() returns `str` so just cast `int`
result = 1
for i in inflow:
result += i
print(result)
To be safe and ensure inputs are valid, I'd add a function to test type casting before building the list with the aforementioned list comprehension:
def typ(x):
try:
int(x)
return True # cast worked
except ValueError:
return False # invalid cast
inflow = [x for x in input().split(' ') in typ(x)]
result = 1
for i in inflow:
result += i
print(result)
So if a user supplies '1 2 3 4.5 5 6.3 7', inflow = [1, 2, 3, 5, 7].
What your code is doing, in chronological order, is this:
Gather user input, split per space and convert to integer, and lastly store in inflow
Initialize result to 1
Iterate over every item in inflow and set item to i
Add the current item, i to result and continue
After loop is done, print the result total.
The broken logic would be at step 4.
To answer your question, the problem is that you're not gathering the index from the list as expected-- you're iterating over each value in the list opposed to the index, so it's really undefined behavior based on what the user inputs. Though of course, it isn't what you want.
What you'd want to do is:
inflow = list(map(int, input().split(" ")))
result = 1
for i in range(len(inflow)):
result += inflow[i]
print(result)
And on your last regard; there are two real ways to do it, one being the way you're doing right now using list, map and:
inflow = [int(v) for v in input().split()]
IMO the latter looks better. Also a suggestion; you could call stdlib function sum(<iterable>) over a list of integers or floats and it'll add each number and return the summation, which would appear more clean over a for loop.
Note: if you're splitting per whitespace you can just call the str.split() function without any parameters, as it'll split at every whitespace regardless.
>>> "hello world!".split()
['hello', 'world!']
Note: also if you want extra verification you could add a bit more logic to the list comprehension:
inflow = [int(v) for v in input().split() if v.isdigit()]
Which checks whether the user inputted valid data, and if not, skip past the data and check the following.

using python to find length of list by recurssion

I have a function here and I want it to count the length of list like 1,2,3,4,5 =5
but the function only counts numbers 1234=4
how can i fix this
def mylen(alist):
if alist:
return 1 + mylen(alist[1:])
return 0
def main():
alist=input("Enter a list of number :")
print(mylen(alist))
main()
fyi i cannot use len
I'm assuming you want mylen('1234') to be = 1. Take your input and split up the numbers by the comma separator.
def mylen(alist):
if alist:
return 1 + mylen(alist[1:])
return 0
def main():
alist=input("Enter a number :")
print(mylen(alist.split(','))
main()
There is no need for the computer to do so much processing for something that is built into the language. This will work just fine:
alist=input("Enter a number :")
print(len(alist.split(','))
In Python 3:
alist=input("Enter a list of number :")
alist will now be a string. If you enter "1,2,3,4,5", a list will be the string "1,2,3,4,5", not a list of numbers [1,2,3,4,5].
A string is a sequence type, just like a list, so your code works with the string as well, and counts the number of elements (characters) in it.
You can use split to convert the input in a list:
userinput = input("Enter a list of number :")
alist = userinput.split(",")
(Note that this is still a list of strings, not numbers, but this doesn't matter for this exercise.)

Categories

Resources