Linked lists and patterns python

前端 未结 3 1799
花落未央
花落未央 2020-12-22 11:08

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 ma         


        
3条回答
  •  北荒
    北荒 (楼主)
    2020-12-22 11:44

    I'd suggest NOT using eval, for starters.

    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.

    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. Maybe this is what yourArrayToList() does, but this works as well.

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

    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)
    

提交回复
热议问题