Home > Software engineering >  Is there a method to split a string of number in python such as "43","12" .How c
Is there a method to split a string of number in python such as "43","12" .How c

Time:01-13

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 I hve to perform (4 1)*(3 2) and all the numbers are given in the form of strings

CodePudding user response:

Code :

data = ["43","12"]

def foo(iter):
    result = []
    for vals in zip(*iter):
        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(iter):
    result = []
    for vals in zip(*iter):
        result.append(sum(list(map(int, vals))))
    return result

def product(iter):
    prod = 1
    for each in iter:
        prod *= each
    return prod

print(product(foo(data)))

Result :

25

You could do math.prod as well.

CodePudding user response:

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

CodePudding user response:

There is no built in method for that specific use case, but you could define one yourself, using something along the lines of:

a = ["43", "12"]

first_digits = []
second_digits = []

for item in a:
    first_digits.append(int(item[0]))
    second_digits.append(int(item[1]))

print(sum(first_digits) * sum(second_digits))
  •  Tags:  
  • Related