Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

Using Linked lists and patterns in 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:

from List import *

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In Python you iterate through a list like this:

list_of_numbers = [1,4,3,7,5,8,3,7,24,23,76]
sum_of_odds = 0
for number in list_of_numbers:
    # now you check for odds
    if isOdd(number):
        sum_of_odds = sum_of_odds + number

print(sum_of_odds)

List is also a module only on your computer. I do not know what is inside. Therefore, I can not help you after ArrayToList(array).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...