Square list of numbers user input Python - python

i'm trying to write a function where user can input a list of numbers, and then each number gets squared, example [1,2,3] to [1,4,9]. so far my code is this:
def squarenumber():
num = raw_input('Enter numbers, eg 1,2,3: ').split(',')
print [int(n) for n in num if n.isdigit()] ##display user input
list = []
for n in num:
list += int(n)*int(n)
print list;
x = squarenumber()
but i get this error saying 'int' object is not iterable. I tried different ways, but still no clue so if anyone can help me i'd be greatly appreciated.

First of all do not use list as a variable, use lst. Also you are incrementing a value not appending to a list in your original code. To create the list, then use lst.append(). You also need to return the list
def squarenumber():
num = raw_input('Enter numbers, eg 1,2,3: ').split(',')
print [int(n) for n in num if n.isdigit()] ##display user input
lst = []
for n in num:
if n.isdigit():
nn = int(n)
lst.append(nn*nn)
print lst
return lst
x = squarenumber()

With lists, you should use append() instead of +=. Here is the corrected code:
def squarenumber():
num = raw_input('Enter numbers, eg 1,2,3: ').split(',')
print [int(n) for n in num if n.isdigit()] ##display user input
lst = []
for n in num:
lst.append(int(n)*int(n))
print lst
x = squarenumber()
[Running the code]
Enter numbers, eg 1,2,3: 1,2,3
[1, 2, 3]
[1, 4, 9]

def squarenumber(inp):
result = [i**2 for i in inp]
return result
>>>inp = [1,2,3,4,5]
>>>squarenumber(inp)
[1, 4, 9, 16, 25]

You can get the desired output using list comprehension instead another loop to append the square of a number to list. Dont use list as a variable name
def squarenumber():
num = raw_input('Enter numbers, eg 1,2,3: ').split(',')
print num # display user input
lst= [int(n)* int(n) for n in num if n.isdigit()]
print lst # display output
x = squarenumber()

Since you're using the list comprehension to print the input, I thought you might like a solution that uses another one:
def squarenumber():
num = raw_input('Enter numbers, e.g., 1,2,3: ').split(',')
print [int(n) for n in num if n.isdigit()]
print [int(n)**2 for n in num if n.isdigit()]
x = squarenumber()

Related

Problem with sorted phone numbers from hackerrank

I know my attempt is very basic, so is my knowledge of python.
the problem asks for getting multiple numbers from user and remove possible 0, +91, or 91 from their left side to make them 10 digit and then sort and print them.
I tried num_list[1] = num_list[1][len(num_list[1])-10:]. It works, so I tried to put it in list comprehension format I'm just studying, but it is not working then. I need help with how to do it hopefully to get a better understanding of when the comprehension format is supposed to be employed.
n = int(input()) # get number of phone numbers from user
num_list = [] # an empty list to store phone numbers in
num_list = [input() for _ in range(n)] # store phone numbers in num_list
##################################
num_list = [num_list[num] = num_list[num][len(num_list[num])-10:] for num in num_list] #remove possible 0, +91, 91 from beginning of numbers
########################################
num_list = sorted(num_list)
num_list = ["+91 "+num[:5]+" "+num[5:] for num in num_list]
print(*num_list , sep="\n")
You shouldn't assign directly within a list comprehension.
The syntax that you're looking for is:
num_list = [num[-10:] for num in num_list]
which is logically equivalent to:
cleaned_list = []
for num in num_list:
cleaned_list.append(num[-10:])
num_list = cleaned_list

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)

how can i compare string within a list to an integer number?

my task today is to create a function which takes a list of string and an integer number. If the string within the list is larger then the integer value it is then discarded and deleted from the list. This is what i have so far:
def main(L,n):
i=0
while i<(len(L)):
if L[i]>n:
L.pop(i)
else:
i=i+1
return L
#MAIN PROGRAM
L = ["bob", "dave", "buddy", "tujour"]
n = int (input("enter an integer value)
main(L,n)
So really what im trying to do here is to let the user enter a number to then be compared to the list of string values. For example, if the user enters in the number 3 then dave, buddy, and tujour will then be deleted from the list leaving only bob to be printed at the end.
Thanks a million!
Looks like you are doing to much here. Just return a list comprehension that makes use of the appropriate conditional.
def main(L,n):
return([x for x in L if len(x) <= n])
Just use the built-in filter method, where n is the cut off length:
newList = filter(lambda i:len(i) <= n, oldList)
You should not remove elements from a list you are iterating over, you need to copy or use reversed:
L = ["bob", "dave", "buddy", "tujour"]
n = int(input("enter an integer value"))
for name in reversed(L):
# compare length of name vs n
if len(name) > n:
# remove name if length is > n
L.remove(ele)
print(L)
Making a copy using [:] syntax:
for name in l[:]:
# compare length of name vs n
if len(name) > n:
# remove name if length is > n
L.remove(ele)
print(L)
This is a simple solution where you can print L after calling the main function. Hope this helps.
def main(L,n):
l=len(L)
x=0
while x<l:
#if length is greater than n, remove the element and decrease the list size by 1
if len(L[x])>n:
L.remove(L[x])
l=l-1
#else move to the next element in the list
else:
x=x+1

How to write a program that returns a count of strings longer than 10 characters in a list of strings

Write a program that returns a count of strings longer than 10 characters in a list of strings.
My program:
def count(List):
if len(List) > 10:
x = "".count(List)
if len(List) <= 10:
x = "None"
return x
def main():
Listy = input("Please enter a list of strings: ")
s = []
for i in Listy:
Split = i.replace("[","").replace('"','').replace("]","").split(",")
s += Split
y = count(s)
print(y)
main()
I wrote this program, but seems like there is a problem with the count() function. I am not sure why.
You can try the following code:
def check_long(lst):
return len([item for item in lst if len(item) > 10])
This creates a filtered list with only the items that have longer than 10 characters, then returns the length of the aforementioned list.
This will give you how many words in the list have more than 10 characters:
Note: I used raw_input because I use Python 2.7 use input in Python 3 also the user will have to enter the words divided by comma and white space
strings = raw_input("Please enter words divided by comma and white space: ")
x = strings.split()
y = []
for i in x:
if len(i) > 10:
y.append(i)
print len(y)
You can try with this code, This will return list of counts for given lists of strings.
def count(strings):
if len(strings) > 10:
x = len(strings)
if len(strings) <= 10:
x = "None"
return x
def main():
List = input("Please enter a list of strings: ")
y = []
for i in List:
y.append(count(i))
print(y)
main()
Output : [16, 20, 'None', 15]
Hope this will help you.
Maybe this helps you
UPDATED
def count(List):
if len(List) > 10:
x = len(List)
else:
x = "None"
return x
def main():
Listy = input("Please enter a list of strings: ").split(",")
for index in Listy:
y = count(index)
print(y)
main()
if input is:
lol, llllllllllllllllllll, rfssfsfsdf
The output should be:
None
21
11

Python: Adding numbers in a list

The question is to iterate through the list and calculate and return the sum of any numeric values in the list.
That's all I've written so far...
def main():
my_list = input("Enter a list: ")
total(my_list)
def total(my_list1):
list_sum = 0
try:
for number in my_list1:
list_sum += number
except ValueError:
#don't know what to do here
print list_sum
main()
If you check to see whether the list item is an int, you can use a generator:
>>> a = [1, 2, 3, 'a']
>>> sum(x for x in a if isinstance(x, int))
6
You can use a generator expression such that:
from numbers import Number
a = [1,2,3,'sss']
sum(x for x in a if isinstance(x,Number)) # 6
This will iterate over the list and check whether each element is int/float using isinstance()
Maybe try and catch numerical
this seams to work:
data = [1,2,3,4,5, "hfhf", 6, 4]
result= []
for d in data:
try:
if float(d):
result.append(d)
except:
pass
print sum(result) #25, it is equal to 1+2+3+4+5+6+4
Using the generator removes the need for the below line but as a side note, when you do something like this for this:
try:
for number in my_list1:
list_sum += number
except ValueError:
#don't know what to do here
You need to call float() on the number to force a ValueError when a string is evaluated. Also, something needs to follow your except which could simply be pass or a print statement. This way of doing it will only escape the current loop and not continue counting. As mentioned previously, using generators is the way to go if you just want to ignore the strings.
def main():
my_list = input("Enter a list: ")
total(my_list)
return
def total(my_list1):
list_sum = 0
try:
for number in my_list1:
list_sum += float(number)
except ValueError:
print "Error"
return list_sum
if __name__ == "__main__":
main()

Categories

Resources