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.)
Related
how to take list as a input in python in a single line.
enter image description hereI tried following thing but it didn't worked
You need to take input separated by space:
input_string = input("Enter a list element separated by space ")
lst = input_string.split()
You can also take input separated by any other character as well.
You can do so by accepting the numbers on a single line separated by spaces and then split it to get all the numbers as a list, then map it to an integer value to produce the required integer list.
numList = list(map(int, input("Enter a list of numbers separated by spaces: ").split()))
print(numList)
You can make use of eval function.
_list = eval(input("enter the list:"))
When prompted you pass the list as follow: [1, 2, 3]
Your _list variable will be a list structure containing 1, 2 and 3 as elements.
Edit: this, of course, does not guarantee that only lists will be accepted on the input, so have this in mind.
list1 = input("data with spaces: ").split(" ")
list2 = input("data with commas: ")split(",")
I try to extract numbers from a text file with regex. Afterward, I create the sum.
Here is the code:
import re
def main():
sum = 0
numbers = []
name = input("Enter file:")
if len(name) < 1 : name = "sample.txt"
handle = open(name)
for line in handle:
storage = line.split(" ")
for number in storage:
check = re.findall('([0-9]+)',number)
if check:
numbers.append(check)
print(numbers)
print(len(numbers))
for number in numbers:
x = ''.join(number)
num = int(x)
sum = sum + num
print(sum)
if __name__ == "__main__":
main()
The problem is, if this string "http://www.py4e.com/code3/"
I gets add as [4,3] into the list and later summed up as 43.
Any idea how I can fix that?
I think you just change numbers.append(check) into numbers.extend(check)because you want to add elements to an array. You have to use extend() function.
More, you do not need to use ( ) in your regex.
I also tried to check code on python.
import re
sum = 0;
strings = [
'http://www.py4e.com/code3/',
'http://www.py1e.com/code2/'
];
numbers = [];
for string in strings:
check = re.findall('[0-9]+', string);
if check:
numbers.extend(check)
for number in numbers:
x = ''.join(number)
num = int(x)
sum = sum + num
print(sum)
I am assuming instead of 43 you want to get 7
The number variable is an array of characters. So when you use join it becomes a string.
So instead of doing this you can either use a loop in to iterate through this array and covert elements of this array into int and then add to the sum.
Or
you can do this
import np
number np.array(number).astype('int').tolist()
This makes array of character into array on integers if conversion if possible for all the elements is possible.
When I add the string http://www.py4e.com/code3/" instead of calling a file which is not handled correctly in your code above fyi. The logic regex is running through two FOR loops and placing each value and it's own list[[4],[3]]. The output works when it is stepped through I think you issue is with methods of importing a file in the first statement. I replaced the file with the a string you asked about"http://www.py4e.com/code3/" you can find a running code here.
pyregx linkhttps://repl.it/join/cxercdju-shaunpritchard
I ran this method below calling a string with the number list and it worked fine?
#### Final conditional loop
``` for number in numbers:
x = ''.join(number)
num = int(x)
sum = sum + num
print(str(sum)) ```
You could also try using range or map:
for i in range(0, len(numbers)):
sum = sum + numbers
print(str(sum))
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)
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