mardi 1 août 2017

python ternary if statement does not catch None

I am implementing the algorithm that adds two numbers from two linked lists in python. (From cracking the coding interview 2-5)

For example,

first: 7 -> 1 -> 6      617
second: 5 -> 9 -> 2    +295
                       -----
                        912
output: 2 -> 1 -> 9 ( which indicates 912 )

This is my code,

class Node:
    def __init__(self, val=None):
        self.data = val
        self.Next = None

class LinkedList:
    def __init__(self):
        self.head = None
        self.size = 0

    def __repr__(self):
        temp = self.head
        alist = []
        while temp:
            alist.append(temp.data)
            temp = temp.Next
        return str(alist)

    def add(self, val):
        cur = self.head
        prev = None
        if cur is None:
            self.head = Node(val)
        else:
            while cur:
                prev = cur
                cur = cur.Next
            prev.Next = Node(val)
        self.size += 1

def adding(p1,p2):
    pointer1 = p1.head
    pointer2 = p2.head
    remainder = 0
    sum_list = LinkedList()

    while pointer1 is not None or pointer2 is not None:
        first = 0 if pointer1.data is None else pointer1.data
        second = 0 if pointer2.data is None else pointer2.data
        sum_ = first + second + remainder

        remainder = 1 if sum_ >= 10 else 0

        sum_ %= 10

        sum_list.add(sum_)

        if pointer1 is not None:
            pointer1 = pointer1.Next
        if pointer2 is not None:
            pointer2 = pointer2.Next
    if remainder > 0:
        sum_list.add(remainder)
    return sum_list

My problem is first = 0 if pointer1.data is None else pointer1.data. It is working when the size of both linked lists are same, however, if one is shorter than others, the shorter one becomes None. So I expect my if statement catches this and makes variable(first) as 0. However it throws AttributeError: NoneType object has no attribute 'data'.

It is working if I write normally, not ternary operator

if pointer1 is None:
    first = 0
else:
    first = pointer1.data
if pointer2 is None:
    second = 0
else:
    second = pointer2.data

Did I miss anything when I use ternary operator? Thanks!

Aucun commentaire:

Enregistrer un commentaire