I need to make a function that returns the value corresponding to its positional value.
Example:
positional value
Ten in 1234 returns 3
hundred in 1234 returns 2
1 unit of thousand, 2 hundred, 3 ten, 4 unit
I'd tried this:
def positional_value(x):
x=str(x)
numbers=[]
numbers.extend(x)
numbers.reverse()
for index,i in enumerate(numbers):
if index==0:
print(i) #so where x is 1234, Here I can get 4.
With what I tried I just can get the numbers by index. I thought that using a list with the positional values names (unit, ten, hundred, unit of thousand, ...) will help to describe each query to the function.
output example: when you print the function:
1 unit of thousand
2 hundred
3 ten
4 unit
#and goes on when the number is bigger
def positional_value(x, pos):
return x // (10**(pos-1)) % 10
NAMES = ["", "unit", "ten", "hundred", "thousand"]
for pos in range(4,0,-1):
val = positional_value(1234,pos)
if val!=0:
print("%d %s" %(val, NAMES[pos]))
A way to do it if you want the digits is:
def positional_value(x):
numbers=[]
v = x
while v != 0:
numbers.append(v%10)
print(v%10)
v = v // 10
print(v)
return numbers
But if you want the index of a specific number in your big number:
def positional_value(x, n):
numbers=str(x)
return numbers.find(str(n))
print(positional_value(1234, 2))
1
print(positional_value(1234, 4))
3
But if you want to look it backwards, reverse is ok
def positional_value(x, n):
numbers=str(x)[::-1]
return numbers.find(str(n))
print(positional_value(1234, 2))
2
print(positional_value(1234, 4))
0
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