Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tuple digits to number conversion

Tags:

python

tuples

I am working on python and I'm stuck on this issue.

Input (there is a tuple):

a = (0, 1)

Output:

a = 0.1
like image 363
sam Avatar asked Dec 20 '22 18:12

sam


1 Answers

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 Decimals eg.

>>> sum(Decimal(n) * Decimal(10) ** Decimal(i) for i, n in zip(count(0, -1), a))
Decimal('0.1532')
like image 105
EnTm Avatar answered Jan 01 '23 15:01

EnTm