Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Homework help
#1
Implement a function called sum_divisible_by_k(lst, k) which receives a list of numbers called lst and a positive number k, and returns the sum of all numbers in the list that are divisible by k.
• If there is no number divisible by k (for example when the list is empty), you will return 0. Example 1:
>>> result = sum_divisible_by_k([3, 6, 4, 10, 9], 3)
>>> print(result)
18
******************************************************\

def sum_divisible_by_k(lst, k):
    sum0=0
    for num in lst: # replace this with your implementation
        if num%k==0:
            sum0=sum0+num
        return sum0/k
result = (sum_divisible_by_k([3, 6, 4, 10, 9], 3))
print(result)
Reply
#2
Your return statement is indented too far. Currently it is part of the for loop code, so it executes each time through the loop. So it executes the first time through the loop, and that's the end of the function. Unindent the return statement one level.

Also you don't want to divide by k when you return. The assignment asks for just the sum of the numbers.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020