0

how do I print the string line without preparing from advance the {} places. Because now my function needed only 6 places, but if I'll change the input (n,m) I'll need different number of {}. How to define it?

def all_pairs_sum(m,n):
    sum = 0
    mult = []
    for m in range(1,m+1):
        for n in range(1,n+1):
            l = m*n
            mult.append(l)
            sum = sum + m*n
            print(m," * ", n, " = ", l)
    print("{}+{}+{}+{}+{}+{} =".format(*mult))
    return sum

print (all_pairs_sum(2,3))
1
  • '+'.join(mult)? Commented Feb 17, 2019 at 8:06

4 Answers 4

1

You can use f-string feature added in Python 3.6. Also notice that sum is a function from Python standard library. It's better not to name your variables that name. As you can see in my example I called it total

def all_pairs_sum(m,n):
    total = 0
    mult = []
    for m in range(1, m + 1):
      for n in range(1 , n + 1):
          l = m * n
          mult.append(l)
          total += l
          print(f"{m} * {n} = {l:>2d}")
    print(f"{' + '.join(map(str, mult))} = {sum(mult)}")
    return total

print(all_pairs_sum(2, 5))

Output:

1 * 1 =  1
1 * 2 =  2
1 * 3 =  3
1 * 4 =  4
1 * 5 =  5
2 * 1 =  2
2 * 2 =  4
2 * 3 =  6
2 * 4 =  8
2 * 5 = 10
1 + 2 + 3 + 4 + 5 + 2 + 4 + 6 + 8 + 10 = 45
45
Sign up to request clarification or add additional context in comments.

Comments

1

If you use the method format() you have a definite number of replacement fields {}. You can use this solution:

l = list(range(5))
print(' + '.join(str(i) for i in l), ' = ', sum(l))
# 0 + 1 + 2 + 3 + 4  =  10

Comments

0

How about:

def get_msg_template(n):
    tmp =  '{}+' * n
    return tmp[:-1]

print(get_msg_template(4))

Output:

 {}+{}+{}+{}

2 Comments

You also can use join here: ' + '.join(['{}'] * n)
also helps. I used for my code print(' + '.join(['{}'] * n*m).format(*mult))
0

If you are looking for printing out the string representation of summed values, you can use something like this:

print("+".join(str(x) for x in mult))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.