In: Computer Science
(Python)
Implement a function to compute a sum that can compute sum for an arbitrary number of input integers or float numbers. In other words, calls like this should all work:
flexible_sum(x1, x2) # sum of two integer or float numbers or strings x1 and x2
flexible_sum(x1, x2, x3) # sum of 3 input parameters
and can also handle a single input parameter, returning it unchanged and with the same type, i.e.:
flexible_sum(1)
returns 1
and can accept an arbitrary number of strings as input parameters and return their concatenation. In other words, the following call
flexible_sum('one ', 'two ', 'three ')
should give result string
'one two three '
And the function can also accept a single input parameter in the form of a list of an arbitrary length and return a sum for it.
If you can, try to implement your function without calls to any other external functions, including Python built-in functions.
def flexible_sum(*args):
s = ''
c = 0
l =[]
if len(args) == 1: #it the args has length 1 it is either a list or just a single value
for i in args:
l = i
if isinstance(l,list): #isinstance is used to check if the parameter is list
for i in l:
c += i
return c
else:
return l
elif isinstance(args[1], str): #isinstace is used to check if the parameter is string
for i in args:
s+=i
return s
else:
for i in args:
c+=i
return c
print(flexible_sum(1)) #taking one parameter
print(flexible_sum(2,3,4)) #taking three int as parameter
print(flexible_sum(1.2,4.6,7.9)) #taking three float as parameter
print(flexible_sum([1,2,3,4,5])) #taking a list as parameter
print(flexible_sum('one ','two ','three ')) #taking strings as parameter
output: