简体   繁体   English

链表和模式python

[英]Linked lists and patterns python

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 main():
   array = eval(input("Give me an array of numbers: "))
   ArrayToList(array)
   print(array[0])
   print(array[1])
   print(array[2])
   print(array[3])
   print(sumOdds(array))


def isOdd(x):
    return x % 2 != 0

def sumOdds(array):
    if (array == None):
        return 0
    elif (isOdd(head(array))):
        return head(array) + sumOdds(tail(array))
    else:
        return sumOdds(tail(array))
main()

I can't get it to actually print the sum though. 我不能让它实际打印总和。 Can anybody help me out with that? 有人可以帮我吗?

Here is the output of the program when I run it: 这是我运行程序时的输出:

$ python3 1.py
Give me an array of numbers: [11, 5, 3, 51]
Traceback (most recent call last):
  File "1.py", line 22, in <module>
    main()
  File "1.py", line 10, in main
    print(sumOdds(array))
  File "1.py", line 19, in sumOdds
    return head(array) + sumOdds(tail(array))
  File "1.py", line 18, in sumOdds
    elif (isOdd(head(array))):
  File "/Users/~/cs150/practice3/friday/List.py", line 34, in head
    return NodeValue(items)
  File "/Users/~/cs150/practice3/friday/List.py", line 12, in NodeValue
    def NodeValue(n): return n[0]
  TypeError: 'int' object is not subscriptable

I'd suggest NOT using eval, for starters. 我建议初学者不要使用eval。

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. 如果您只想从控制台输入,则输入raw_input并提示用户输入逗号或其他分隔字符。

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. int()对于忽略空格非常有用。 Maybe this is what your ArrayToList() does, but this works as well. 也许这就是您的ArrayToList()所做的,但这也可以正常工作。

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循环而不是仅对前四个项目进行硬编码?

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. 另外, if (array == None)if not array:少了pythonic,并且sum()函数确实很聪明,只要列表没有长度就返回0。

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)

Your line ArrayToList(array) is suspicious. 您的ArrayToList(array)行可疑。 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. 我怀疑应该将您的python列表转换为列表的自定义版本。 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). 您遇到的实际问题是tail()函数(或您对应该返回的尾巴的理解)。 As it is, tail is returning an int and you are expecting it to return a list. 实际上,tail是返回一个int,并且您期望它返回一个列表。 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. 如果您未编写tail函数,请尝试仅使用tail函数并观察其输出,以更好地了解应如何使用它。 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]

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. 我只是从列表中实现一个filter / reduce函数,然后将一个函数传递给filter_reduce(func)函数以累积已过滤项的总和。

You can check out the live demo here: Python Fiddle 您可以在此处查看现场演示: 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 清单:0、1、2、3、4、5
Size: 6 大小:6
Summation: 9 总结:9
Product: 1200 产品:1200

linked_list.py 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM