Finding the sum of numbers from x to y and the program prints the answer as "x+(x+1)....+y= (sum of # from x to y)"

2.3k Views Asked by At

For example, the sum of numbers from 1 to 3 would be printed as 1+2+3=6; the program prints the answer along with the numbers being added together. How would one do this? Any help is greatly appreciated as nothing I've tried has worked. I have been trying to use the sum formula to get the answer and a loop to get the numbers being added together... but with no success. Although the hint is to use for loops, but I'm not sure how to incorporate that into the program. The practice prompt also says that I can't use sum or .join functions :(, I know that would make things so much easier. Omg I'm so sorry for forgetting to mention it.

6

There are 6 best solutions below

0
Astik Gabani On BEST ANSWER

Try using this

x = 3
y = 6

for i in range(x, y+1):
    opt_str += str(i) + "+"
    sum += i

print(opt_str[:-1] + "=" + str(sum))

Output:

3+4+5+6=18
0
NAGA RAJ S On

you can try this

def problem1_3(n):
   return n + problem1_3(n-1) if n > 1 else 1

or try below

n = 0
sum = 10
for num in range(0, n+1, 1):
   sum = sum+num
print("SUM of first ", n, "numbers is: ", sum )

output

SUM of first  10 numbers is:  55
2
LevB On

You can use join and list comprehension to assemble the string.

n1 = 1
n2 = 3

li = str(n1)+"".join(["+"+str(i) for i in range(n1+1,n2+1)])+"="+str(sum(range(n1,n2+1)))
print (li)

Output:

1+2+3=6 
0
Ruzihm On

An interesting way to do this is to print a little bit at a time. Use end='' in your prints to avoid newlines:

num = 3
sum = 0

for i in range(1,num+1):
    sum += i
    if i>1:
        print ("+", end='')
    print(i, end='')
print("=%d" % sum)

1+2+3=6

0
Ish On

The simplest way would be using for loops and print() function

def func(x,y):
    sum = 0

    #Loop for adding
    for i in range(x,y+1):
        sum+=i

    #Loop for printing
    for i in range(x,y+1):
        if i == y:
            print(i,end = '')
        else: print(i," + ",end = '')
    print(" = ",sum)

The end argument to the print() function specifies what your printed string is going to terminate with, instead of the default newline character.

So for your example here, func(1,3) Will output : 1 + 2 + 3 = 6

0
Peyman Majidi On

Here is the code:

print("Finding the sum of numbers from x to y")
print("Please specify x & y(x<=y):")
x = int(input(" x:"))
y = int(input(" y:"))
numbers = [x]
result = f"Sum: {x}"

for i in range(1,y-x+1):
    numbers.append(x+i)
    result += f"+({x}+{i})"
    
print(f"{result} = {sum(numbers)}")

output:

Finding the sum of numbers from x to y
Please specify x & y(x<=y):
 x:1
 y:10
Sum: 1+(1+1)+(1+2)+(1+3)+(1+4)+(1+5)+(1+6)+(1+7)+(1+8)+(1+9) = 55

output2:

Finding the sum of numbers from x to y
Please specify x & y(x<=y):
 x:2
 y:6
Sum: 2+(2+1)+(2+2)+(2+3)+(2+4) = 20