I am trying to add the digits from a string and multiply it by 2.
ex) "123" would be (1+2+3)*2
I have tried this but I can't seem to get it working.
def add_digits_in_string(dig):
initial = 0
strinitial = str(initial)
for i in dig:
t = str(i)
if t.isdigit():
strinitial += int(t)
strinitial*2
return strinitial
your code
def adddigitsinstring(dig): # dig is string "123"
initial = 0 # initial is of type int
strinitial = str(initial) # converting initial to string type into new varibale strinitial
for i in dig: # looping through each digit in the dig
t = str(i) # converting existing string to string , not required
if t.isdigit(): # check if digit char is digit
strinitial += int(t) # adding the int type with the str type wrong "2 +"2" == error
strinitial*2 # multiple value with the 2, so in every loop it got multiple each time , not required
return strinitial # return int value as str type ie "123"
this is what you should do, you need to keep checking the if each character in the input is a digit or not. if it is a digit then you need to keep adding the digits to a intial value of type int beacuse 1+1=2 and '1'+'1' ='11', once you add all the digits then multiply them by 2 and return the result in str format
def adddigitsinstring(dig:str):
intial = 0
for digit in dig:
if digit.isdigit():
intial += int(digit)
final_result = intial * 2
return str(final_result)
def add_digits_in_string(dig:str):
digit = [int(digi) for digi in list(dig) if digi.isdigit()]
return str(sum(digit) * 2)
print(adddigitsinstring("12345"))
print(add_digits_in_string("12345"))
output
30
30
You can use built-in function sum
, list expansion and int
to convert a digit to a string. You can iterate over consecutive characters easily.
In [8]: s = "123"
In [9]: 2*sum([int(ss) for ss in s])
Out[9]: 12
You don't need that strinitial
variable, only an int
where to store the partial sum:
def adddigitsinstring(dig):
sum=0
for i in dig:
if i.isdigit():
sum=sum + int(i)
return sum * 2
Try this using list comprehension
:
num = '123'
print(sum(int(x) for x in num)*2)
and here you are if you really need that in a function:
def adddigitsinstring(dig):
return sum(int(x) for x in dig)*2
num = '123'
print(adddigitsinstring(num))
You can sum a list comprehension the return the result multiplied by 2
def adddigitsinstring(dig):
return sum([int(i) for i in dig if i.isdigit()]) * 2
print(adddigitsinstring("123"))
The most simple I could come up with:
def adddigitsinstring(dig):
return 2*sum(map(lambda x:int(x), dig))
Sample tests:
>>> adddigitsinstring("1234")
20
>>> adddigitsinstring("9")
18
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.