将链表转换为python中的单个数字时出错

时间:2014-03-16 15:50:57

标签: python list numbers

这是节点定义

class Node(object):
    def __init__(self,value=None):
       self.value = value
       self.next = None

这是将代码转换为链接列表的数字

def number_to_list(number):
    head,tail = None,None
    p = True
    for x in str(number):
        if x=='-':
            p = False
            continue
        else:
            if p:
                node = Node(int(x))
            else:
                node = Node(int("-"+x))
        if head:
            tail.next = node
        else:
            head = node
        tail = node
    return head
    pass

这是将链表转换为数字

的代码
 def list_to_number(head):
    neg = False
    num = ''
    for number in head:
        val = str(number)
        if (val.find('-')!= -1):
            neg = True
        num=num+val.replace('-','')
    if (neg==False):
        return int(num)
    else:
        return -1*int(num)
    pass

这里是测试用例

def test_number_to_list():
    import listutils

    head = number_to_list(120)
    assert [1,2,0] == listutils.from_linked_list(head)
    assert 120 == list_to_number(head)

    head = number_to_list(0)
    assert [0] == listutils.from_linked_list(head)
    assert 0 == list_to_number(head)

    head = number_to_list(-120)
    assert [-1, -2, 0] == listutils.from_linked_list(head)
    assert -120 == list_to_number(head)

此处from_linked_list表示

 # avoids infinite loops
 def from_linked_list(head):
    result = []
    counter = 0
    while head and counter < 100: # tests don't use more than 100 nodes, so bail if you loop 100 times.
        result.append(head.value)
        head = head.next
        counter += 1
    return result

最后在这个问题是将链表转换为单个数字时遇到错误,即节点对象不可迭代

请帮助我编写代码

def list_to_number(head):
    neg = False
    num = ''
   for number in  head:
        val = str(number)
       TypeError: 'Node' object is not iterable

这里是追溯

2 个答案:

答案 0 :(得分:2)

for number in head:

不是迭代列表的正确方法。

您需要从head开始,然后关注next引用链。

答案 1 :(得分:0)

请注意,如果__iter__上定义了Node,请执行以下操作:

class Node(object):

    def __init__(self,value=None):
       self.value = value
       self.next = None

    def __iter__(self):
        that = self
        while that is not None:
            yield that.value
            that = that.next

然后:

for number in head:

实际上会有效。