Henrique Jesus
Henrique Jesus

Reputation: 85

Divide digits from a number into array

I want to put all the digits of a number into an array. Per example I have 2017 and I want a vector V = [2, 0, 1, 7]. Here is the code:

import array
    n = 2017
    sizeN = 4 
    m = n
    i = 1
    V = []
    while m!=0:
        V.insert((sizeN-i), (m%10))
        m = m // 10
        i+=1
    
    print(V)

But the problem is that V = [2, 7, 0, 1]. What am I doing wrong?

Upvotes: 0

Views: 36

Answers (3)

Pynchia
Pynchia

Reputation: 11590

This is another solution, more pythonic

n = 2017
v = [int(d) for d in str(n)]
print(v)

Alternatively we can do

n = 2017
zero = ord('0')
v = [ord(d)-zero for d in str(n)]
print(v)

Both produce

[2, 0, 1, 7]

Nota Bene: v is a list, not an array.

Please name your variables in lowercase, respecting PEP 8

Upvotes: 0

bigbounty
bigbounty

Reputation: 17368

Use map function

In [21]: y = 2017

In [22]: list(map(int, str(y)))
Out[22]: [2, 0, 1, 7]

To modify your code Method 1:

n = 2017
m = n

V = []
while m:
    V.append(m%10)
    m = m // 10

V.reverse()
print(V)

Method 2:

n = 2020
m = n

V = []
while m:
    V.insert(0,m%10)
    m = m // 10

print(V)

Upvotes: 0

Enrigle Robota
Enrigle Robota

Reputation: 21

The index of location to insert is wrong.

In line 8: V.insert((sizeN-i), (m%10)), the first arg index should always be 0, which means you should always insert the new digit to the front.

Changing this line to V.insert(0, (m % 10)) will solve your problem.

To get a deeper view, we can take it step by step:

  • m % 10 = 7, V = [7]
  • m % 10 = 1, V = [1, 7]
  • m % 10 = 0, V = [0, 1, 7]
  • m % 10 = 2, V = [2, 0, 1, 7]

Upvotes: 1

Related Questions