summation of all elements from an array in python3 - python

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

Related

Unable to extract numbers and sum them using regex and re.findall()

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))

Python: Search a string for a number, decrement that number and replace in the string

If I have a string such as:
string = 'Output1[10].mystruct.MyArray[4].mybool'
what I want to do is search the string for the number in the array, decrement by 1 and then replace the found number with my decremented number.
What I have tried:
import string
import re
string = 'Output1[10].mystruct.MyArray[4].mybool'
pattern = r'\[(\d+)\]'
num = re.findall(pattern, string)
So, I can get a list of the numbers, convert to integers but I don't know how to use re.sub to search the string to replace, it should be considered that there might be multiple arrays. If anyone is expert enough to do that, help much appreciated.
Cheers
I don't undestand a thing... If there is more than 1 array, do you want to decrease the number in all arrays? or just in 1 of them?
If you want to decrease in all arrays, you can do this:
import re
string = 'Output1[10].mystruct.MyArray[4].mybool'
pattern = r'\[(\d+)\]'
num = re.findall(pattern, string)
num = [int(elem) for elem in num]
num.sort()
for elem in num:
aux = elem - 1
string = string.replace(str(elem), str(aux))
If you want to decrease just the first array, you can do this
import string
import re
string = 'Output1[10].mystruct.MyArray[4].mybool'
pattern = r'\[(\d+)\]'
num = re.findall(pattern, string)
new_num = int(num[0]) - 1
string = string.replace(num[0], str(new_num), 1)
Thanks to #João Castilho for his answer, based on this I changed it slightly to work exactly how I want:
import string
import re
string = 'Output1[2].mystruct.MyArray[2].mybool'
pattern = r'\[(\d+)\]'
num = re.findall(pattern, string)
num = [int(elem) for elem in set(num)]
num.sort()
for elem in num:
aux = elem - 1
string = string.replace('[%d]'% elem, '[%d]'% aux)
print(string)
This will now replace any number between brackets with the decremented value in all of the conditions that the numbers may occur.
Cheers
ice.

Count all the occurrences of the prefix string

Find the alphabet present at that location and determine the no of occurrences of the same alphabet preceding that location n.
Input:
length = 9
string = "abababbsa"
n = 9
Output:
3
Explanation:
Find the alphabet at nth position 9 i.e a. Count all the occurrences before that index which is 3.
Code:
length = int(input())
string = list(input())
n = int(input())
str1 = string[n-1]
print(string[0:n-1].count(str1))
The above code gives TLE. How can I optimize this?
Well It becomes easy if you use re ( regex )
import re
length = int(input())
my_string = input('Enter your string')
n = int(input())
print(len(re.findall(my_string[n-1],my_string[:n-1])))
So what is happening is we are finding all occurences of the character before n by slicing the string at n-1 and just getting the length of the list ( all occurences ).
One way to optimize is to use string as usual in spite of converting it into a list:
string = input()
The complexity would now be O(n) where n is the input position, whereas, in your
case, because the string was explicitly converted to list, the complexity was
O(length of the string).

Why is my index printing when I try to print the contents of the list?

I am trying to square the every digit in a number provided by the user. I am getting the correct output but I get an additional index at the end I'm not really sure why. I've put comments in my code to explain what I'm trying to do at every step. How do I get rid of that index on the end?
def square_digits(num):
print(num)
string_num =(str(num)) #convert the num to a string
for word in string_num: #iterate through every digit
word = int(word) #convert each digit to an int so we can square it
square_num = word * word
str_sq_num = list(str(square_num)) #create a list of those nums
for count in str_sq_num: #iterate through list to make it one number
print(count, end = "")
print(str_sq_num)
return str_sq_num
So an example number is being given 3212. I should output 9414, instead my output is 9414['4']. Another example is a number 6791, the output should be 3649811, but my output is 3649811['1'].
The problem is the way for loops work in python. The variable str_square_num is left over from the last iteration of for word in string_num.
For example, assuming your number is 12, in the first iteration str_square_num will be [1], or 1 squared. But this value is overriden in the second iteration, when it is set to [4], or 2 squared. Thus the array will always contain only the square of the last digit.
If your goal is to get the array of all indicies, try this:
def square_digits(num):
print(num)
string_num =(str(num)) #convert the num to a string
str_sq_num = []
for word in string_num: #iterate through every digit
word = int(word) #convert each digit to an int so we can square it
square_num = word * word
str_sq_num.extend(str(square_num)) #create a list of those nums
for count in str_sq_num: #iterate through list to make it one number
print(count, end = "")
print(str_sq_num)
return str_sq_num
I'm not sure exactly what you're trying to achieve here, but looking at your examples I suppose this should work:
def square_digits(num):
print(num)
string_num = (str(num))
str_sq_num = []
for word in string_num:
word = int(word)
square_num = word * word
str_sq_num.append(square_num)
for count in str_sq_num:
print(count, end = "")
return str_sq_num
Couldn't test it, but this should do it:
def square_digits(string_num):
return "".join([str(int(num)**2) for num in string_num])

Convert an integer into a string of its ascii values

Given a number number such that its digits are grouped into parts of length n (default value of n is 3) where each group represents some ascii value, I want to convert number into a string of those ascii characters. For example:
n number Output
==================================
3 70 F
3 65066066065 ABBA
4 65006600660065 ABBA
Note that there is no leading 0 in number, so the first ascii value will not necessarily be represented with n digits.
My current code looks like this:
def number_to_string(number, n=3):
number = str(number)
segment = []
while number:
segment.append(number[:n])
number = number[n:]
return str(''.join('{:0>{}}'.format(chr(segment), n) for segment in number))
Expected outputs:
number_to_string(70)
'F'
number_to_string(65066066065)
'ABBA'
number_to_string(65006600660065, n=4)
'ABBA'
My current code however returns an empty string. For example, instead of 'F' it returns ' '. Any reason why this is? Thank you!
P.S.:
I'm wanting to reverse the process of this question, i.e. turn an integer into a string based on the ascii values of each character (number) in the string. But reading that question is not a requirement to answer this one.
Try this:
import re
def number_to_string(num, n=3):
num_str = str(num)
if len(num_str) < n:
num_str = '0' * (n-len(num_str)) + num_str
elif len(num_str) % n != 0:
num_str = '0'*(n-len(num_str)%n) + num_str
print(num_str)
chars = re.findall('.'*n, num_str)
l = [chr(int(i)) for i in chars]
return ''.join(l)
First pad the given number (converted into string) with required number of zeros, so that it can be evenly split into equal number of characters each. Then using re split the string into segments of size n. Finally convert each chunk into character using chr, and then join them using join.
def numToStr(inp):
"""Take a number and make a sequence of bytes in a string"""
out=""
while inp!=0:
out=chr(inp & 255)+out
inp=inp>>8
print "num2string:", out
return out
does this help?
Is this what you want?
def num_to_string(num, leng):
string = ""
for i in range(0,len(str(num)),leng):
n = str(num)[i:i+2]
string += chr(int(n))
print string
Output:
>>> ================================ RESTART ================================
>>>
>>> num_to_string(650065006600,4)
AAB
>>> num_to_string(650650660,3)
AAB
>>> num_to_string(656566,2)
AAB
>>>
You can just append \x to number as this prints 'p':
print '\x70'

Categories

Resources