0

I'm trying to combine multiple numbers together in python 3.7 but I'm having no luck.

I want it to be like such:

1 + 4 + 5 = 145 

I know this is simple but I'm getting nowhere!

martineau
  • 119,623
  • 25
  • 170
  • 301
August
  • 73
  • 2
  • 9

5 Answers5

4

You can use reduce to do this in a mathematical way

>>> l = [1, 4, 5]
>>> 
>>> from functools import reduce
>>> reduce(lambda x,y: 10*x+y, l)
145

Alternatively, you can use string concat

>>> int(''.join(map(str, l)))
145
Sunitha
  • 11,777
  • 2
  • 20
  • 23
2

If you want to do this numerically, consider what base-10 numerals means:

145 = 1 * 10**2 + 4 * 10**1 + 5 * 10**0

So, you need to get N numbers that range from N-1 to 0, in lockstep with the digits. One way to do this is with enumerate plus a bit of extra arithmetic:

def add_digits(*digits):
    total = 0
    for i, digit in enumerate(digits):
        total += digit * 10**(len(digits)-i-1)
    return total

Now:

>>> add_digits(1, 4, 5)
145

Of course this only works with sequences of digits—where you know how many digits you have in advance. What if you wanted to work with any iterable of digits, even an iterator coming for a generator expression or something? Then you can rethink the problem:

1456 = ((1 * 10 + 4) * 10 + 5) * 10 + 6

So:

def add_digits(digits):
    total = 0
    for digit in digits:
        total = total * 10 + digit
    return total

>>> add_digits((1, 3, 5, 6))
1356
>>> add_digits(n for n in range(10) if n%2)
13579

Notice that you can easily extend either version to other bases:

def add_digits(*digits, base=10):
    total = 0
    for i, digit in enumerate(digits):
        total += digit * base**(len(digits)-i-1)
    return total

>>> hex(add_digits(1, 0xF, 2, 0xA, base=16))
'0x1f2a'

… which isn't quite as easy to do with the stringy version; you can't just do int(''.join(map(str, digits)), base), but instead need to replace that str with a function that converts to a string in a given base. Which there are plenty of solutions for, but no obvious and readable one-liner.

abarnert
  • 354,177
  • 51
  • 601
  • 671
1

You should try casting the numbers as strings! When you do something like this

str(1)+str(4)+str(5)

You will get 145, but it will be a string. If you want it to be a number afterwards, then you can cast the whole thing as an integer.

int(str(1)+str(4)+str(5))

or just set the answer to a new variable and cast that as an integer.

C Haworth
  • 659
  • 3
  • 12
0

The easiest way to do this is to concat them as strings, and then parse it back into a number.

x = str(1) + str(4) + str(5)
print(int(x))

or

int(str(1) + str(4) + str(5))
gkgkgkgk
  • 707
  • 2
  • 7
  • 26
0

You could just write a function that concatenates numbers or any other object/datatype as a string

concatenate = lambda *args : ''.join([str(arg) for arg in args])

a = 1

print(concatenate(4, 5, 6))

print(concatenate(a, MagicNumber(1), "3"))

But also in python you can make a class and write magic functions that control the way that objects of your class are added, subtracted etc. You could make a class to store a number and add it like you want to. You could save this code in a file and import it or paste it into your own script.

class MagicNumber():
    value = 0

    def __init__(self, value):
        self.value = int(value)

    def __str__(self):
        return str(self.value)

    def __int__(self):
        return self.value

    def __repr__(self):
        return self.value

    def __add__(self, b):
        return MagicNumber(str(self)+str(b))

if __name__ == "__main__":
    a = MagicNumber(4)
    b = MagicNumber(5)
    c = MagicNumber(6)

    print(a+b+c)

    #You could even do this but I strongly advise against it
    print(a+5+6)

And heres a link to the documentation about these "magic methods" https://docs.python.org/3/reference/datamodel.html

West
  • 70
  • 11
  • Approach is overkill IMO. – martineau Jul 30 '18 at 18:23
  • I made the second solution more simplified. Thanks for the feedback @martineau – West Jul 30 '18 at 18:27
  • West: I meant wrt creating a custom `class` to do this. Python has tons of built-in text processing features which, if used properly, would likely result in less code being needed and would also run significantly faster. – martineau Jul 30 '18 at 18:33
  • This is the best way I can think of to make a line execute as similar as possible to the way the question's author wants it to. Also if the question's author wants to do similar things with subtract or other operators this would be a solution that covers that as well. @martineau – West Jul 30 '18 at 18:45
  • @West What's the string-concatenation equivalent of subtraction? I can imagine that `1 + 3 + 5 - 5` would be `13`, but should `1 + 3 + 5 - 3` be `15` or 135` or an error, and what about `1 + 3 + 5 - 2`? Multiplication might be a better example—`3 * 5` giving you `33333` is pretty unambiguous, even if it's hard to imagine when you'd want it. – abarnert Jul 30 '18 at 19:00
  • I'm not sure ¯\_(ツ)_/¯, it was just an example. I like the multiplication example. It seems like the only operators that are reasonable are those that can already be used on strings. @abarnert – West Jul 30 '18 at 19:13
  • West & @abarnert: Who said anything about multiplication? The OP certainly didn't. West: Anyway, [Sunitha's answer](https://stackoverflow.com/a/51599607/355230) is an example of what I meant about using Python's (generally relatively very fast) built-in abilities. – martineau Jul 30 '18 at 20:15
  • @martineau West brought up "if the question's author wants to do similar things with subtract"; I was just saying that multiplication might be a better example of that, because string multiplication is a defined operation, unlike subtraction. I don't see any problem with him suggesting, especially in a comment, how his solution could be extended in ways that other solutions can't. – abarnert Jul 30 '18 at 20:18
  • @abarnert: Like I said originally, overkill, not to mention pure speculation and likely way over the head of the OP. – martineau Jul 30 '18 at 22:59
  • 1
    Thank you very much – August Aug 06 '18 at 14:19