1. def assert_list_conditions(data, condition_check):
  2. """
  3. Asserts a condition on a list.
  4. Args:
  5. data (list): The list to check.
  6. condition_check (callable): A function that takes a list as input and
  7. returns True if the condition is met, False otherwise.
  8. Raises:
  9. AssertionError: If the condition is not met.
  10. """
  11. assert condition_check(data), f"List does not satisfy the required condition: {condition_check.__name__}"
  12. if __name__ == '__main__':
  13. # Example Usage
  14. def check_positive(lst):
  15. """Checks if all elements in the list are positive."""
  16. return all(x > 0 for x in lst)
  17. my_list = [1, 2, 3, 4, 5]
  18. assert_list_conditions(my_list, check_positive)
  19. my_list = [-1, 2, 3]
  20. try:
  21. assert_list_conditions(my_list, check_positive)
  22. except AssertionError as e:
  23. print(e)
  24. def check_even_length(lst):
  25. """Checks if the list has an even number of elements."""
  26. return len(lst) % 2 == 0
  27. my_list = [1, 2, 3, 4]
  28. assert_list_conditions(my_list, check_even_length)
  29. my_list = [1, 2, 3]
  30. try:
  31. assert_list_conditions(my_list, check_even_length)
  32. except AssertionError as e:
  33. print(e)

Add your comment