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.

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'

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
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.