Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...