Is there a method to split a string of number in python such as "43","12" .How can we add 4+1 and 3+2
Code :
data = ["43","12"]
def foo(nums):
result = []
for vals in zip(*nums):
result.append(sum(list(map(int, vals))))
return result
print(foo(data))
Result :
[5, 5]
Works with other data as well, of course.
lastly, if you want to get the product of the list produced then you could do so by :
data = ["43","12"]
def foo(nums):
result = []
for vals in zip(*nums):
result.append(sum(list(map(int, vals))))
return result
def product(nums):
prod = 1
for each in nums:
prod *= each
return prod
print(product(foo(data)))
Result :
25
You could do math.prod
as well.
Assuming that the numbers are always 2-digits, you can use unpacking:
a,b = map(int,"43")
c,d = map(int,"12")
print((a+c)*(b+d)) #25
A 1-liner that generalizes to longer numbers is:
math.prod(x+y for x,y in zip(map(int,"43"),map(int,"12")))