簡體   English   中英

鏈表和模式python

[英]Linked lists and patterns python

嘗試編寫一個將遍歷鏈表的函數,對所有奇數求和,然后顯示總和。 這是我到目前為止的內容:

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()

我不能讓它實際打印總和。 有人可以幫我嗎?

這是我運行程序時的輸出:

$ 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

我建議初學者不要使用eval。

如果您只想從控制台輸入,則輸入raw_input並提示用戶輸入逗號或其他分隔字符。

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

一旦有了這個,您就可以使用列表推導從數據中收集實際的列表。 int()對於忽略空格非常有用。 也許這就是您的ArrayToList()所做的,但這也可以正常工作。

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

另外,如果您只是想遍歷列表並打印接收到的值,我是否可以建議使用for循環而不是僅對前四個項目進行硬編碼?

for num in number_list:
    print num

另外, 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])

因此,將其放在上下文中:

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)

您的ArrayToList(array)行可疑。 因為我不知道該怎么辦。 我懷疑應該將您的python列表轉換為列表的自定義版本。 如果是這種情況,我猜它有一個返回值。 因此,請嘗試更改您的主要功能來做到這一點:

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))

您可以查看是否適合您。

您遇到的實際問題是tail()函數(或您對應該返回的尾巴的理解)。 實際上,tail是返回一個int,並且您期望它返回一個列表。 如果您未編寫tail函數,請嘗試僅使用tail函數並觀察其輸出,以更好地了解應如何使用它。 我建議只運行這段代碼,看看它的作用:

def main():
    print(tail([1, 2, 3, 4])) # Your code assumes tail returns [2, 3, 4]

我只是從列表中實現一個filter / reduce函數,然后將一個函數傳遞給filter_reduce(func)函數以累積已過濾項的總和。

您可以在此處查看現場演示: 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)

輸出量

清單:0、1、2、3、4、5
大小:6
總結:9
產品: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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM