How to convert a number into a linked list of its digits in python
python
Solution
You can do this with by converting the number to a string and using list comprehension.
In [1]: foo = 12345
In [2]: [int(digit) for digit in str(foo)]
Out[2]: [1, 2, 3, 4, 5]
Or a shorter version suggested:
map(int, list(str(foo)))
But it seems like you're using a custom list class. The key is still to convert the number to a string.
def number_to_list(number):
head = tail = None #you can chain assignments if they have the same value
for x in str(number):
if not x.isdigit():
continue # skip leading `-`
node = Node(x)
if head is not None: #more pythonic than `if head`
tail.next = node
else:
head = node
tail = node
return head # don't forget your return code
Problem
I was asked to convert a number into a linked list of its digits: ex:`head = number_to_list(120)` number_to_list is the function I should write and it should return a list of its digits `listutils.from_linked_list(head) == [1,2,0]` without using datastructures like list and dicts.I tried to write inthis way: ``` def number_to_list(number): head,tail = None,None for x in number: node = Node(x) if head: tail.next = node else: head = node tail = node second = head.next third = second.next fourth = third.next ``` But I know that I'm totally wrong because in the for loop I should write the code in such a way that it goes to the first digit of the number and create a node of it.I'm blocked here.Please help me with this.