I am working on python and I'm stuck on this issue.
Input (there is a tuple):
a = (0, 1)
Output:
a = 0.1
Single digits and only two elements
>>> a = (0, 1)
>>> a[0] + a[1] * 0.1
0.1
Multiple single digits
>>> from itertools import count
>>> a = (0, 1)
>>> sum(n * 10 ** i for i, n in zip(count(0, -1), a))
0.1
>>> a = (0, 1, 5, 3, 2)
>>> sum(n * 10 ** i for i, n in zip(count(0, -1), a))
0.15320000000000003
Using reduce
(for Py 3.0+ you will need: from functools import reduce
)
>>> a = (0, 1, 5, 3, 2)
>>> reduce(lambda acc, x: acc * 0.1 + x, reversed(a))
0.1532
Using the decimal
module
>>> from decimal import Decimal
>>> a = (0, 1, 5, 3, 2)
>>> Decimal((0, a, -len(a) + 1))
Decimal('0.1532')
Any two numbers
>>> a = (0, 1)
>>> float('{0}.{1}'.format(*a))
0.1
Any numbers
>>> a = (0, 1, 5, 3, 2)
>>> float('{0}.{1}'.format(a[0], ''.join(str(n) for n in a[1:])))
0.1532
There may be some floating point inaccuracies, which you could fix by using Decimal
s eg.
>>> sum(Decimal(n) * Decimal(10) ** Decimal(i) for i, n in zip(count(0, -1), a))
Decimal('0.1532')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With