Joining integer numbers together to make new number

TrustyTony 0 Tallied Votes 295 Views Share

Sometimes we want to tackle some problem specifying properties of sequence of numbers consisting the integer. Then it is usefull to have function to join many integers to make a long integer. Most efficient way for tight loops is to stay in integers domain and not go through the string representation. Inspired by C++ question and my answer to it: http://www.daniweb.com/software-development/cpp/threads/425472/how-concatenate-number-in-c#post1819908

def together(*numbers):
    b = numbers[-1]
    for a in reversed(numbers[:-1]):
        magnitude = 1
        while b >= magnitude:
            magnitude *= 10
        b = magnitude * a + b
    return b

print together(123, 456, 100, 789, 10, 999, 1000, 99)
TrustyTony 888 pyMod Team Colleague Featured Poster

Code snippet updated to handle also zero values:

def together(*numbers):
    b = numbers[-1]
    previous_zeroes = 1
    for a in reversed(numbers[:-1]):
        if not a:
            previous_zeroes *= 10
        else:
            magnitude = 10
            while b >= magnitude:
                magnitude *= 10
            b = previous_zeroes * magnitude * a + b
            previous_zeroes = 1            

    return b

if __name__ == '__main__':
    print together(123, 456, 0, 0, 789, 10, 123, 1000, 99, 0)
Lucaci Andrew 140 Za s|n

you could also do it like this

def nr(*nrs):
    nr = ""
    for i in range (0, len(nrs)):
        a = str(nrs[i])
        nr = nr + a
    return int(nr)
print nr(1, 2, 3, 4, 5, 6) + 100000000

since Python works with strings alot.

and if you want to put a 0 in front, the program should ignore it.

def nr(*nrs):
    nr = ""
    for i in range (0, len(nrs)):
        if nrs[i] == '0': continue
        else :
            a = str(nrs[i])
            nr = nr + a
    return int(nr)
print nr(0, 2, 3, 4, 5, 0, 6)

thow, the int(nr) will do that, I put this to evidentiate if so the need.

TrustyTony 888 pyMod Team Colleague Featured Poster

As I mentioned, keeping in numbers is likely to be most efficient, but doing with strings is super simple:

def nr(*nrs):
    return int(''.join(str(n) for n in nrs))

print(nr(1, 2, 3, 4, 5, 6) + 100000000)
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.