Search code examples
pythonalgorithmdigits

Adding comma every 3 digit problem, in python, what's different using list or using format


I am practicing an algorithm on a website.

I want to add data(number) comma(,) every 3 digit.

But 'a', which variable I made, can't be the collect answer.

But 'b', which variable I searched, is the collect answer.

Can you tell me why 'a' is not the same as 'b'

length = 8
data = "12421421"

inv_result = []
for index in range(length):
    if index % 3 == 0:
        inv_result.append(',')
        inv_result.append(str(data[index]))
    else:
        inv_result.append(str(data[index]))

result = inv_result[::-1]

#first comma delete
result.pop()

a = ''.join(result)
b = format(int(datas),",")

print(a)
print(b)
print(a == b)

result is

12,412,421
12,421,421
False

Solution

  • Your problem is that you didn't reverse the data in the beginning. The following (slightly cleaned up) code works:

    length = 8
    data = "12421421"
    inv_data = data[::-1]
    inv_result = []
    for index in range(length):
        if index % 3 == 0:
            inv_result.append(',')
        inv_result.append(str(inv_data[index]))
    
    result = inv_result[::-1]
    
    #first comma delete
    result.pop()
    
    a = ''.join(result)
    b = format(int(data),",")
    
    print(a)
    print(b)
    print(a == b)