Linked lists and patterns python

前端 未结 3 1780
花落未央
花落未央 2020-12-22 11:08

Trying to write a function that will iterate over the linked list, sum up all of the odd numbers and then display the sum. Here is what I have so far:

def ma         


        
相关标签:
3条回答
  • 2020-12-22 11:44

    I'd suggest NOT using eval, for starters.

    If you just want input from the console just go for raw_input and prompt the user to enter commas or some other delimiting character.

    number_string = raw_input("Give me a string of numbers separated by commas, plz.")
    

    Once you have this you can use list comprehension to glean the actual list from the data. int() is pretty good about ignoring whitespace. Maybe this is what yourArrayToList() does, but this works as well.

    number_list = [int(x) for x in number_string.split(",")]
    

    Also, if you want to simply iterate over the list and print the received values, might I suggest a for loop instead of just hard-coding the first four items?

    for num in number_list:
        print num
    

    Additionally, the if (array == None) is a bit less pythonic than if not array:, and really the sum() function is smart enough to just return 0 if the list has no length anyway.

    def sum_the_odds(yourlist):
        return sum([x for x in yourlist if x % 2 == 1])
    

    So to put it in context:

    def sum_the_odds(yourlist):
        return sum([x for x in yourlist if x % 2 == 1])
    
    def main():
        number_string = raw_input("Give me a string of numbers separated by commas, plz.")
        number_list = [int(x) for x in number_string.split(",")]
        for num in number_list:
            print num
        print sum_the_odds(number_list)
    
    0 讨论(0)
  • 2020-12-22 12:06

    I would just implement a filter/reduce function from within the list and just pass a function into the filter_reduce(func) function to accumulate the sum of the filtered items.

    You can check out the live demo here: Python Fiddle

    def calc_product(a, b):
        return a * b
    
    def calc_summation(a, b):
        return a + b
    
    def is_odd(x):
        return x % 2 != 0   
    
    l = linked_list()
    l.insert_end(1)
    l.insert_end(2)
    l.insert_end(3)
    l.insert_end(5)
    l.insert_beginning(0)
    l.insert_after(4, 3)
    
    print 'List:', l
    print 'Size:', l.size()
    
    # Calculates the sum of all odd values in the list:
    print 'Summation:', l.filter_reduce(calc_summation, is_odd)
    
    # Calculates the product of all values with the accumulator
    # initialized at 10.
    print 'Product:', l.filter_reduce(calc_product, lambda x: True, 10)
    

    Output

    List: 0, 1, 2, 3, 4, 5
    Size: 6
    Summation: 9
    Product: 1200

    linked_list.py

    class linked_list():
        class node():
            def __init__(self, data=None):
                self.data = data
                self.next = None
    
            def __str__(self):
                return str(data)
    
        class list_iterator():
            def __init__(self, current_node=None):
                self.current_node = current_node
    
            def hasNext(self):
                return self.current_node.next is not None
    
            def next(self):
                if not self.hasNext():
                    return None
                self.current_node = self.current_node.next;
                return self.current_node.data;
    
        def __init__(self):
            self.head = None
            self._size = 0
    
        def iterator(self):
            return self.list_iterator(self.head)
    
        def is_empty(self):
            return self.head is None
    
        def size(self):
            return self._size
    
        def insert_after(self, data, index):
            new_node = self.node(data)
            curr_node = self.head
            i = 0
            while curr_node is not None and i < index:
                curr_node = curr_node.next
                i += 1
            new_node.next = curr_node.next
            curr_node.next = new_node
            self._size += 1
    
        def insert_beginning(self, data):
            new_node = self.node(data)
            if self.is_empty():
                self.head = new_node
            else:
                new_node.next = self.head
                self.head = new_node
            self._size += 1
    
        def insert_end(self, data):
            new_node = self.node(data)
            if self.is_empty():
                self.head = new_node
            else:
                curr_node = self.head
                while curr_node.next is not None:
                    curr_node = curr_node.next
                curr_node.next = new_node
            self._size += 1
    
        def filter_reduce(self, reduce_func, filter_func=None, initializer=None):
            it = self.iterator()
            if initializer is None:
                try:
                    initializer = it.next()
                except StopIteration:
                    raise TypeError('reduce() of empty sequence with no initial value')
            accum_value = initializer
            while it.hasNext():
                data = it.next()
                if filter_func is None or filter_func(data):
                    accum_value = reduce_func(accum_value, data)
            return accum_value
    
        def __str__(self):
            s, it = '', self.iterator()
            while it.hasNext():
                s += str(it.next())
                if it.hasNext():
                    s += ', '
            return s
    
    0 讨论(0)
  • 2020-12-22 12:08

    Your line ArrayToList(array) is suspicious. Because I don't know what it is suppose to do. I suspect it is suppose to convert your python list into a customly defined version of a list. If this is the case, I'm guessing it has a return value. So try changing your main function to do this:

    def main():
        user_input = eval(input("Give me an array of numbers: "))
        custom_list = ArrayToList(user_input) # convert user input to a custom list.
        print(sumOdds(custom_list))
    

    You could see if that works for you.

    The actual problem you are having is with the tail() function (or your understanding of what tail is suppose to return). As it is, tail is returning an int and you are expecting it to return a list. If you didn't write the tail function, try using just the tail function and observe its output to gain a good understanding of how it should be used. I suggest just running this code and seeing what it does:

    def main():
        print(tail([1, 2, 3, 4])) # Your code assumes tail returns [2, 3, 4]
    
    0 讨论(0)
提交回复
热议问题