Python 链表和模式
尝试编写一个函数来迭代链表,将所有奇数相加,然后显示总和。以下是我到目前为止的情况:Python 链表和模式,python,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):
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
$python3 1.py
给我一组数字:[11,5,3,51]
回溯(最近一次呼叫最后一次):
文件“1.py”,第22行,在
main()
文件“1.py”,第10行,主
打印(萨姆比数(数组))
文件“1.py”,第19行,在Sumforks中
返回头(阵列)+尾(阵列))
文件“1.py”,第18行,在sumforks中
elif(isOdd(头部(阵列)):
文件“/Users/~/cs150/practice3/friday/List.py”,第34行,头部
返回节点值(项目)
文件“/Users/~/cs150/practice3/friday/List.py”,第12行,在NodeValue中
def NodeValue(n):返回n[0]
TypeError:“int”对象不可下标
首先,我建议不要使用eval
如果您只想从控制台输入,只需转到raw\u 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)
您的行数组列表(数组)可疑。因为我不知道该怎么办。我怀疑应该将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应该返回什么的理解)。实际上,tail返回一个int,您希望它返回一个列表。如果您没有编写tail函数,请尝试仅使用tail函数并观察其输出,以便更好地理解如何使用它。我建议运行此代码并查看它的功能:
def main():
print(tail([1, 2, 3, 4])) # Your code assumes tail returns [2, 3, 4]
我只需要在列表中实现一个filter/reduce函数,然后将一个函数传递到
filter\u reduce(func)
函数中,以累加过滤项的总和
您可以在此处查看实况演示:
输出
列表:0、1、2、3、4、5尺寸:6
总和:9
邮品:1200 链接列表.py
类链接列表():
类节点():
def uuu init uuuu(self,data=None):
self.data=数据
self.next=无
定义(自我):
返回str(数据)
类列表\迭代器():
def uuu init uuuu(self,current_node=None):
self.current\u node=当前\u节点
下一步(自我):
返回self.current_node.next不是None
def next(自我):
如果不是self.hasNext():
一无所获
self.current\u node=self.current\u node.next;
返回self.current_node.data;
定义初始化(自):
self.head=无
自身大小=0
def迭代器(self):
返回self.list_迭代器(self.head)
def为空(自身):
返回自我。头是空的
def大小(自身):
返回自我。\u大小
def插入_后(自身、数据、索引):
新节点=自节点(数据)
curr_node=self.head
i=0
而curr_节点不是None且i
“但我无法让它实际打印总数”-你能让它做什么?会发生什么?错误(提供完整的回溯)?意外输出(提供输入以及预期和实际输出)?哪里是ArrayToList
definition?何时调用sum*函数?re:edit。是的。这就是你要求它做的一切。有什么问题吗?那么,print(sumforbits(array))
不是按您的要求进行打印,还是…?我应该使用eval。这是我的CS课程,我们被告知使用eval。你被告知使用StackOverflow来完成作业吗?:)对不起,但是
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)
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