I have a set set(1, 2, 3, 4, 5)
, list [1, 2, 3, 4]
, sorted set SortedSet(5, 2, 3)
.
I would like to write a function which works similar to all the types above, for example calculate average, or other stuff. I want my function to be safe. In Java there is Collection interface, common for all standard Java containers.
from sortedcontainers import SortedSet
def is_collection(some_collection):
return isinstance(some_collection, set) or isinstance(some_collection, list) or isinstance(some_collection, SortedSet)
def calculate_average(some_collection):
if is_collection(some_collection):
sum = 0
size = some_collection.__len__()
for item in some_collection:
sum = sum + item
return sum / size
return 0