<ipython-input-95-7d1e398e65a2> in get_sum_of_numbers(alist)
1 import numbers
2 def get_sum_of_numbers(alist):
----> 3 assert len(alist) > 0, "List is empty"
4 assert all([isinstance(element, numbers.Number) for element in alist]), "Not all elements are Numbers"
5 tmp = None
AssertionError: List is empty
%% Cell type:markdown id: tags:
# Preconditions, postconditions and invariants
Assertions can be grouped into:
* Preconditions, which should be true the computional part of a function
* Postconditions, which should be true afterwards
* (Invariants, which should be true anywhere)
%% Cell type:code id: tags:
``` python
importnumbers
defget_sum_of_numbers(alist):
# Preconditions
assertlen(alist)>0,"List is empty"
assertall([isinstance(element,numbers.Number)forelementinalist]),"Not all elements are Numbers"
tmp=None
forelementinalist:
iftmp==None:
tmp=element
else:
tmp=tmp+element
return(tmp)
returntmp
```
%% Cell type:code id: tags:
``` python
get_sum_of_numbers([1,2,3,4,5])
```
%% Cell type:code id: tags:
``` python
defget_sum_of_numbers(alist):
# Preconditions
assertlen(alist)>0,"Cannot compute the mean of nothing"
assertall([isinstance(element,int)forelementinalist]),"Not all elements of your list are integer"
tmp=None
forelementinalist:
iftmp==None:
tmp=element
else:
tmp=tmp+element
tmp='Your code has been visited by an evil spirit!'
return(tmp)
returntmp
```
%% Cell type:code id: tags:
``` python
get_sum_of_numbers([1,2,3])
```
%% Cell type:code id: tags:
``` python
importnumbers
defget_sum_of_numbers(alist):
# Preconditions
assertlen(alist)>0,"List is empty"
assertall([isinstance(element,numbers.Number)forelementinalist]),"Not all elements are Numbers"
tmp=alist[0]
forelementinalist[1:]:
tmp=tmp+element
tmp='Your code has been visited by an evil spirit!'
# Postcondition
assertisinstance(tmp,numbers.Number),"Your sum isn't numerical..."
return(tmp)
returntmp
```
%% Cell type:code id: tags:
``` python
get_sum_of_numbers([1,2,3])
```
%% Cell type:markdown id: tags:
# Test-Driven Development
Some programmers write code and then test that code somehow to be confident enough that it's bug free.
Other programms create tests and then write code that has to pass these tests in an iterative manner. This approach is called test-driven development.
%% Cell type:markdown id: tags:
We want to write a function that calculates the largest overlap between numerical ranges. Each numerical range is a two-element tuple specifying the upper and lower boundaries.