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))
Related
I have a list of numbers of varying lengths stored in a file, like this...
98
132145
132324848
4435012341
1254545221
2314565447
I need a function that looks through the list and counts every number that is 10 digits in length and begins with the number 1. I have stored the list in both a .txt and a .csv with no luck. I think a big part of the problem is that the numbers are integers, not strings.
`import regex
with open(r"C:\Desktop\file.csv") as file:
data = file.read()
x = regex.findall('\d+', data)
def filterNumberOne(n):
if(len(n)==10:
for i in n:
if(i.startswith(1)):
return True
else:
return False
one = list(filter(filterNumberOne, x))
print(len(one))`
You could simply do like this :
# Get your file content as a string.
with open(r"C:\Desktop\file.csv") as f:
s = " ".join([l.rstrip("\n").strip() for l in f])
# Look for the 10 digits number starting with a one.
nb = [n for n in s.split(' ') if len(n)==10 and n[0]=='1']
In your case, the output will be:
['1254545221']
So I ended up using the following, seems to work great..
def filterNumberOne(n):
if (len(n)==10:
if str(n)[0] == '1':
return True
else:
return False
one = list(filter(filterNumberOne, x ))
print(len(one))
Basically, I wish to sum the elements of the array provided in stdin. Why is it saying that list index is out of range? Is there anything special about the python input() function?
length = int(input())
li = []
for i in range(0, length):
li[i] = int(input())
sum = 0
for item in li:
sum = sum + item
Input
first line : length of array
second line : elements of the array.
EDIT : second line is a single string, not space separated integers.
3
1 2 3
Output:
Traceback (most recent call last):
File "./prog.py", line 6, in <module>
IndexError: list assignment index out of range
your question pretty much got answered, I just wanna show you a couple of tricks to make your program more simple and pythonic.
Instead of the for-loop try:
li = [int(i) for i in input().split(" ")]
And instead of the way you're calculating sum, try:
sum(li)
or even better:
sumOfItems = sum(int(i) for i in input().split(" "))
The thing with python lists is that you cannot assign a particular value to a position when that position originally does not exist, that is, the length of the list is less than the position that you want to change.
What you are trying to do is assign the value to a particular position in the list (called index) but since the list is empty, it's length is 0 and hence the index is out of range( that is it is not available for modifiying. That is why python is raising Index out of range error.
What you can try is:
l=[]
length=int(input())
for i in length:
l.append(int(input())
sum=0
for num in l:
sum=sum+num
You can solve this in a single line without even taking in the length. But you have to enter space separated values in a single line:
s = 0
for item in list(map(int, input ().split())):
s += item
If you want to input one integer per line, then you'll need the length(or a sentinel value):
s = 0
len = int(input())
li = [int(input ()) for _ in range(len)]
for item in li:
s = s + item
The second line of input turned out to be a single string and not space separated integers.
So I had to split the string, then convert the strings to integers to calculate their sum. Some of the methods mentioned above didn't work.
The list comprehension method will work in the space separated case, and is perfectly fine.
length = int(input())
l = input().split() # List of strings of integers.
S = 0
for item in l:
S += int(item) # Converting string to int
print(S)
You can't assign values to locations of a list that doesn't exist
try this:
length = int(input())
li = list(range(length))
for i in range(0, length):
li[i] = int(input())
sum = 0
for item in li:
sum = sum + item
you can also do something like this:
length = int(input())
li = []
for i in range(0, length):
li.append(int(input()))
total = sum(li)
print(total)
I have a array of integers which are space separated like this small example:
ar = 1000000001 1000000002 1000000003 1000000004 1000000005
I want to sum up the numbers character by character. for example the output for the small example would be:
5000000015
in fact the sum of the 1st elements from all numbers is 5, and this is the case for all elements.
to get such results I have made the following code:
def sum(ar):
for i in ar.split():
sum = 0
for j in range(len(i)):
sum += i[j]
return sum
but it does not return what I want as output. do you know how to fix it?
Try this. It should work
ar = "1000000001 1000000002 1000000003 1000000004 1000000005"
total=0
nums=ar.split(" ")
for num in nums:
total+=int(num)
print(total)
Capture all the digits first using regex, then pass it to the sum function by parsing it first.
import re
ar = "1000000001 1000000002 1000000003 1000000004 1000000005"
pattern = r'([0-9]+)'
matches = re.findall(pattern, ar)
digit_sum = sum((int(match) for match in matches))
print (digit_sum)
Outputting:
5000000015
It appears that your initial "array" is a string, so when you split the array you are still dealing with a list of strings that you can't add to your starting zero value. Also, it is not clear why you are attempting to sum "character by character" when your expected output is just the sum of all the integers. You really just need to convert each integer string to integer and then sum.
s = '1000000001 1000000002 1000000003 1000000004 1000000005'
total = sum(int(x) for x in s.split())
print(total)
# 5000000015
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.)
This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 6 years ago.
I am new to Python and want to read keyboard input into an array. The python doc does not describe arrays well. Also I think I have some hiccups with the for loop in Python.
I am giving the C code snippet which I want in python:
C code:
int i;
printf("Enter how many elements you want: ");
scanf("%d", &n);
printf("Enter the numbers in the array: ");
for (i = 0; i < n; i++)
scanf("%d", &arr[i]);
You want this - enter N and then take N number of elements.I am considering your input case is just like this
5
2 3 6 6 5
have this in this way in python 3.x (for python 2.x use raw_input() instead if input())
Python 3
n = int(input())
arr = input() # takes the whole line of n numbers
l = list(map(int,arr.split(' '))) # split those numbers with space( becomes ['2','3','6','6','5']) and then map every element into int (becomes [2,3,6,6,5])
Python 2
n = int(raw_input())
arr = raw_input() # takes the whole line of n numbers
l = list(map(int,arr.split(' '))) # split those numbers with space( becomes ['2','3','6','6','5']) and then map every element into int (becomes [2,3,6,6,5])
raw_input is your helper here. From documentation -
If the prompt argument is present, it is written to standard output
without a trailing newline. The function then reads a line from input,
converts it to a string (stripping a trailing newline), and returns
that. When EOF is read, EOFError is raised.
So your code will basically look like this.
num_array = list()
num = raw_input("Enter how many elements you want:")
print 'Enter numbers in array: '
for i in range(int(num)):
n = raw_input("num :")
num_array.append(int(n))
print 'ARRAY: ',num_array
P.S: I have typed all this free hand. Syntax might be wrong but the methodology is correct. Also one thing to note is that, raw_input does not do any type checking, so you need to be careful...
If the number of elements in the array is not given, you can alternatively make use of list comprehension like:
str_arr = raw_input().split(' ') //will take in a string of numbers separated by a space
arr = [int(num) for num in str_arr]
data = []
n = int(raw_input('Enter how many elements you want: '))
for i in range(0, n):
x = raw_input('Enter the numbers into the array: ')
data.append(x)
print(data)
Now this doesn't do any error checking and it stores data as a string.
arr = []
elem = int(raw_input("insert how many elements you want:"))
for i in range(0, elem):
arr.append(int(raw_input("Enter next no :")))
print arr