4

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
Y4RD13
  • 937
  • 1
  • 16
  • 42

3 Answers3

4
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]))
Boris Lipschitz
  • 1,514
  • 8
  • 12
  • This will work adding the corresponding word to the `print(positional_value(1234,1))` – Y4RD13 Jul 21 '19 at 23:30
  • 2
    Edited to a more complete example. Obviously, you need to know your supported maximum, so you could extend it to have those words. Also, add sanity checks for wrong types, negative numbers, etc. – Boris Lipschitz Jul 21 '19 at 23:31
3

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
developer_hatch
  • 15,898
  • 3
  • 42
  • 75
3

Similar to accepted answer, but using the value as a string, rather than integer division.

def positional_values(x):
    positions = ['unit', 'ten', 'hundred', 'unit of thousand', 'ten-thousand',
                 'hundred-thousand', 'unit of million', ]
    for i, c in enumerate(str(x)):
        print(f"{int(c)}: {positions[len(str(x)) - i - 1]}")

positional_values(1234)

1: unit of thousand
2: hundred
3: ten
4: unit
Deepstop
  • 3,627
  • 2
  • 8
  • 21