Home > Software engineering >  I want to Remove the addition symbol from in-between the numbers using python and please find the be
I want to Remove the addition symbol from in-between the numbers using python and please find the be

Time:11-21

limit = int(input("Limit: "))
allvalue = ""
count = 0
number = 0


while count < limit:
    number  = 1
    count  = number 
    allvalue  = str(number)   "   "

print(allvalue)

This is my output 1 2 3 4 5 6 7 8 9

I want the symbol only in between the numbers.Not to be in the last or the first.

CodePudding user response:

A likely solution is using " ".join(), which uses the string method on the " " to collect the values together

>>> values = "1 2 3 4 5".split()
>>> "   ".join(values)
'1   2   3   4   5'

CodePudding user response:

limit = int(input("Limit: "))
allvalue = ""
count = 0
number = 0
while count < limit:
    number  = 1
    count  = number
    if count != limit:
        allvalue  = str(number)   "   "  
    else:
        allvalue  = str(number)

print(allvalue)

Hope this help.

CodePudding user response:

I would like to share with you a sure shot mathematical solution to this problem.

This problem is a typical variation of Sum of n numbers problem, where the sum depicting limit here is already given as input, instead of n.

import math

limit = int(input("Limit: "))                          # n * (n   1) / 2 >= limit
n = math.ceil( ((1   4*2*limit)**0.5 - 1) / 2 )        # ((b^2 - 4ac)^(1/2) - b) / 2a where a = b = 1, c = 2*limit

allValue = "   ".join([str(i) for i in range(1, n 1)])
print(allValue)

CodePudding user response:

You don't need both the number and count variables, and by starting from initial value you can add the before the number.

limit = int(input("Limit: "))
count = 1
allvalue = str(count)
while count < limit:
    count  = 1
    allvalue  =  "   "   str(count)
    
print(allvalue)

CodePudding user response:

You could also try using a for loop.

limit = int(input("Limit: "))
allvalue = ""

for i in range(0, limit):
   if i 1 == limit:
       allvalue  = str(i 1)
   else:
       allvalue  = str(i 1)   " "

print(allvalue)

CodePudding user response:

Here is simple and easy approach, you can try slice in the result string

print(allvalue[:-2])

code:

limit = int(input("Limit: "))
allvalue = ""
count = 0
number = 0


while count < limit:
    number  = 1
    count  = number 
    allvalue  = str(number)   "   "

print(allvalue)
print(allvalue[:-2])

output: result shared : https://onlinegdb.com/HFC2Hv4wq

Limit: 9
1   2   3   4   
1   2   3   4 
  • Related