Python has a built in function sum
, which is effectively equivalent to:
def sum2[iterable, start=0]:
return start + reduce[operator.add, iterable]
for all types of parameters except strings. It works for numbers and lists, for example:
sum[[1,2,3], 0] = sum2[[1,2,3],0] = 6 #Note: 0 is the default value for start, but I include it for clarity
sum[{888:1}, 0] = sum2[{888:1},0] = 888
Why were strings specially left out?
sum[ ['foo','bar'], ''] # TypeError: sum[] can't sum strings [use ''.join[seq] instead]
sum2[['foo','bar'], ''] = 'foobar'
I seem to remember discussions in the Python list for the reason, so an explanation or a link to a thread explaining it would be fine.
Edit: I am aware that the standard way is to do "".join
. My question is why
the option of using sum for strings was banned, and no banning was there for, say, lists.
Edit 2: Although I believe this is not needed given all the good answers I got, the question is: Why does sum work on an iterable containing numbers or an iterable containing lists but not an iterable containing strings?
Use type[] and isdigit[] functions in Python to achieve a sum list of strings in Python. This function will check If the element is int, then add it to the total by checking two conditions.
Simple example code adds all numbers from the list. Where given list may contain numbers in string or integer format.
lst = [1, '10', 'Hello', '2020', '[email protected]', 2021]
total = 0
# iterating over the list
for element in lst:
# checking whether its a number or not
if isinstance[element, int] or element.isdigit[]:
# adding the element to the total
total += int[element]
print[total]
Output:
Or use List comprehension
total = sum[[int[i] for i in lst if type[i]== int or i.isdigit[]]]
How to sum a list of string objects in Python?
Answer: Prints only the first letter of each word in order to make one new word.
if words are separated by space, then split in words using space and for each word [“map” function], take the first character [x[0]]. Last join the result using void.
s = "this is my sentence"
res = "".join[map[lambda x: x[0], s.split[" "]]]
print[res]
Or simple use
res = "".join[x[0] for x in s.split[]]
Output: tims
Do comment if you have any doubts or suggestions on this Python sum topic.
Note: IDE: PyCharm 2021.3.3 [Community Edition]
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.
The challenge
Create a function that takes 2 nonnegative integers in form of a string as an input, and outputs the sum [also as a string]:
Example: [Input1, Input2 –>Output]
Code language: Python [python]
"4", "5" --> "9" "34", "5" --> "39"
Notes:
- If either input is an empty string, consider it as zero.
- Inputs and the expected output will never exceed the signed 32-bit integer limit [
2^31 - 1
]
The solution in Python code
Option 1:
Code language: Python [python]
def sum_str[a, b]: return str[int[a or ] + int[b or ]]
Option 2:
Code language: Python [python]
def sum_str[*values]: return str[sum[int[s or '0'] for s in values]]
Option 3:
Code language: Python [python]
def sum_str[*args]: return str[sum[map[lambda x: int[x] if x else , args]]]
Test cases to validate our solution
Code language: Python [python]
import test from solution import sum_str @test.describe["Fixed Tests"] def basic_tests[]: @test.it["Sample Tests"] def sample_tests[]: test.assert_equals[sum_str["4","5"], "9"] test.assert_equals[sum_str["34","5"], "39"] @test.it["Tests with empty strings"] def empty_string[]: test.assert_equals[sum_str["9",""], "9", "x + empty = x"] test.assert_equals[sum_str["","9"], "9", "empty + x = x"] test.assert_equals[sum_str["",""] , "0", "empty + empty = 0"]