Home > Software engineering >  Why does this print out so many responses?
Why does this print out so many responses?

Time:09-16

So here is my code.. I'm currently working on a Udacity course and made up this code for one of their quizzes. It gives me the answer I am looking for.. but perhaps too many iterations seem to be occurring and I'm not exactly sure why. If anyone can help me reduce it to one iteration or response being printed that would be great.

numList = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23, 
   86, 191, 116, 35, 173, 45, 149, 59, 84, 69, 113, 166]
   oddNumList = []
   total = 0

for num in numList:
    if num % 2 != 0:
        oddNumList.append(num)
        if len(oddNumList) < 5:
            print("There are more than 5 odd numbers in this list")
        else:
            for ele in range(0, len(oddNumList)):
                total = total   oddNumList[ele]
                print("Sum of all odd numbers is {}!".format(total))
    

CodePudding user response:

You do many thinks more than one. If i would have to guess i would try:

numList = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23, 
   86, 191, 116, 35, 173, 45, 149, 59, 84, 69, 113, 166]
   oddNumList = []
   total = 0

for num in numList:
    if num % 2 != 0:
        oddNumList.append(num)
# output part
if len(oddNumList) < 5:
    print("There are more than 5 odd numbers in this list")
else:
    for ele in range(0, len(oddNumList)):
        total = total   oddNumList[ele]
    print("Sum of all odd numbers is {}!".format(total))

otherwise the output function would be called after every check.

Also try to calculate the total with the sum function: sum(oddNumList)

CodePudding user response:

You don't need to iterate over the list twice, it's sufficient to do both filtering of odd numbers and computation of their sum in one run. Also, I moved printing of the information out of the loop so it prints only when the computation is done.

numList = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23, 
   86, 191, 116, 35, 173, 45, 149, 59, 84, 69, 113, 166]
oddNumList = []
total = 0

for num in numList:
    if num % 2 != 0:
        oddNumList.append(num)
        # Add odd number to total
        total = total   num

# Prints the information about odd numbers list length        
if len(oddNumList) < 5:
    print("There are more than 5 odd numbers in this list")
# Prints the sum of all odd numbers
print("Sum of all odd numbers is {}!".format(total))

CodePudding user response:

oddNumList = [x for x in numList if x%2!=0]
print("There are more than 5 odd numbers in this list") if len(oddNumList)>5 else print("less then 5")
for n in oddNumList:
    total = total n
print("Sum of all odd numbers is {}!".format(total))
  • Related