2021年5月5日星期三

Creating a function that removes odd multiples in a list

One of the revision questions involves modifying the original list by removing all integers in a list that are both odd and a multiple of x.

def remove_odd_multiples(numbers_list, multiple_of):      for ele in numbers_list:          if (ele%2) != 0 and (ele % multiple_of) == 0:              numbers_list.remove(ele)            return numbers_list  

Output:

numbers_list = [1, 5, 23, 3, 6, 17, 9, 18]  print("Before:", numbers_list)  remove_odd_multiples(numbers_list, 3)  print("After:", numbers_list)    Before: [1, 5, 23, 3, 6, 17, 9, 18]  After: [1, 5, 23, 6, 17, 18]  

It does work, however inputting the code into coderunner, my code failed a few hidden checks which are not shown. Am I going about solving this problem wrong? Should I be using pop instead of .remove?

https://stackoverflow.com/questions/67410902/creating-a-function-that-removes-odd-multiples-in-a-list May 06, 2021 at 10:02AM

没有评论:

发表评论