Skip to content

Practice: Collections

Theo Chupp edited this page Nov 17, 2017 · 1 revision

Collection practice

Python contains three simple types of collections: Tuples, Lists, and Sets.
These data structures are very powerful by themselves, but understanding their uses requires practice.
Over time, we will implement all of the operations below to help us "unleash the power" of collections.

Each of these operations should be applicable to collections with any type of element.
Each operation will have a description, a template, and a sample input and output for test cases.

All operations will input a collection and a function that defines behavior.

Aggregate operations

Aggregate operations are operations that take a collection as input, and output a single value.
Most aggregate operations take a collection and a predicate as input.
A predicate is a function that takes one input and outputs a Boolean.
To borrow from Kotlin's function syntax, predicates have the signature (T) -> Boolean where T can be any type.

Any

Any will return True if at least one element matches the predicate

def any(list, predicate):
  # fill in this code

def is_even(x):
  return x % 2 == 0

print any([1, 3, 5, 6], is_even) == True
print any([5, 7, 1], is_even) == False


is_str = lambda s: type(s) is str

print any(["True", False], is_str) == True
print any([9, 1.8], is_str) == False

All

All will return True if all elements matches the predicate

def all(list, predicate):
   # fill in this code

is_even = lambda x: x % 2 == 0

print all([2, 6, 8, 10], is_even) == True
print all([1, 2, 3], is_even) == False


is_str = lambda s: type(s) is str

print all(["Hello", "World!"], is_str) == True
print all(["Python", 7], is_str) == False

None

None will return True if no elements match the predicate

def none(list, predicate):
   # fill in this code

is_even = lambda x: x % 2 == 0

print all([1, 3, 5, 7], is_even) == True
print all([2, 3, 4, 5], is_even) == False


is_str = lambda s: type(s) is str

print all([5, 9.0, False], is_str) == True
print all(["Functions!", 9], is_str) == False

Count

Count will return the number of elements that match the predicate

def count(list, predicate):
   # fill in this code

is_even = lambda x: x % 2 == 0

print all([4, 5, 6, 7, 8], is_even) == 3
print all([1, 3, 5, 8], is_even) == 1


is_str = lambda s: type(s) is str

print all([5, 9.0, False], is_str) == 0
print all(["Functions!", 9], is_str) == 1

Reduce

Max

Max will return the element that produces the largest value from the given function

def max(list, func):
   # fill in this code

eval_int = lambda x: x

Min

Filtering operations

Take

Drop

Filter

Transforming operations

Map

Flat Map

Group By

Element operations

Contains

Element At

Element At or Else

Element At or None

First

Last

Index Of

Generation operations

Partition

Plus

Zip

Ordering operations

Reverse

Sort