0

This is a simple problem that for some reason I can't get to work.

The problem I created for myself was to use call a function from a function using *args and print out the question and solution. I want the output to vary as the *args can accept any number of paramters.

The basic function.

def sum_args(*args):
    return sum(args)

So the output that I would want is:

given a call like

run(sum_args, 1,2,3,4)

would be, but of course the user could put any number of entries in so I can't hard code it.

1+2+3+4 = 10

Attempt

def run(func,*args):
    for item in args:
        for item in args[0:-2]:
            print(item,end="")
            print('+',end="")
   ....:             

run(sum_args, 1,3,5,6,7,8,9)
1+3+5+6+7+1+3+5+6+7+1+3+5+6+7+1+3+5+6+7+1+3+5+6+7+1+3+5+6+7+1+3+5+6+7+

In this next attempt zip removes the last arg as it doesn't have a corresponding value, which goes against what I was trying to acheive.

def run(func,*args):
    plus = '+'
    calc = plus * (len(args)-1)
    plus_list = list(calc)
    items_list = list(args)
    print(list(zip(items_list,plus_list)))
   ....:     

run(sum_args, 1,3,5,6,7,8,9)
[(1, '+'), (3, '+'), (5, '+'), (6, '+'), (7, '+'), (8, '+')]

Honestly think I must be tired this should be easy.

2
Contributors
2
Replies
19
Views
3 Years
Discussion Span
Last Post by flebber
2

Don't print directly, use strings operations to create new strings with your data instead, for example

>>> args = (1,2,3,4)
>>> L = [str(n) for n in args]
>>> L
['1', '2', '3', '4']
>>> s = '+'.join(L)
>>> s
'1+2+3+4'
0

New there would be a simple solution to it.

def run(func,*args):
    argList = [str(n) for n in args]
    myOutput = '+'.join(argList)
    print(myOutput, '=', func(*args))
   ....:     

run(sum_args, 1,3,5,6,7,8,9)
1+3+5+6+7+8+9 = 39

Edited by flebber

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.