Piszę funkcję, która powinna przyjmować string jako argument. Funkcja ma liczyć sumę wszystkich liczb w stringu. Tak więc dla sum_of_digits("123") powinnam dostać: 6
Dla sum_of_digits("1aw3") powinnam mieć
The sum of digits operation performs 1+3
The extracted non-digits are: [’a’, ’w’]
4
Dla sum_of_digits("") powinno być:
Empty string entered
0
A dla sum_of_digits("united"):
The sum of digits operation could not detect a digit!
The returned input letters are: ['u', 'n', 'i', 't', 'e', 'd']
0
Mój program wyswietla odpowiedzi, ale nie takie jak powinny być. Oto kod:
def sum_of_digits(s):
letters = []
numbers = []
sum = 0
for i in s:
if i.isdigit():
sum += int(i)
print(sum)
for i in s:
if i.isalpha() and i.isdigit():
letters.append(i)
numbers.append(i)
print("The sum of digits operation performs ", "+".join(numbers))
print("The extracted non-digits are: {} ".format(letters), end="\n")
elif len(s) == 0:
print('Empty string entered!')
return 0
elif s == 'united':
print('The sum of digits operation could not detect a digit!')
print('The returned input letters are: ', end = '')
print([char for char in s])
return 0
sum_of_digits("123")
sum_of_digits("1aw3")
sum_of_digits("")
sum_of_digits("united")
A to output:
1
3
6
1
4
The sum of digits operation could not detect a digit!
The returned input letters are: ['u', 'n', 'i', 't', 'e', 'd']
0