In [1]:
import math
def euclidean_distance(x1, y1, x2, y2):
return math.sqrt((x1 - x2) ** 2 + (y1-y2) ** 2)
In [2]:
euclidean_distance(0,0,1,1)
Out[2]:
We can unpack a list or tuple into positional arguments using a star *
:
In [3]:
values_list = [0,0,1,1]
euclidean_distance(*values_list)
Out[3]:
In [4]:
values_tuple = (0,0,1,1)
euclidean_distance(*values_tuple)
Out[4]:
Similarly, we can use double star **
to unpack a dictionary into keyword arguments.
In [11]:
values_dict = { 'x1': 0, 'y1': 0, 'x2': 1, 'y2': 1 }
euclidean_distance(**values_dict)
Out[11]:
In [13]:
list(zip([1,2,3,4,5,6]))
Out[13]:
With comprehensions, we can build a sequence based on another iterable.
In [6]:
# List comprehension
[num ** 2 for num in range(-10, 11)]
Out[6]:
In [7]:
[num ** 2 for num in range(-10, 11) if num > 0]
Out[7]:
In [8]:
# Set comprehension
names = [ 'Bob', 'JOHN', 'alice', 'bob', 'ALICE', 'J', 'Bob' ]
{ name[0].upper() + name[1:].lower() for name in names if len(name) > 1 }
Out[8]:
In [9]:
s = "Action Is Eloquence"
counts = dict()
for char in s:
counts[char] = counts.get(char, 0) + 1
counts
Out[9]:
In [10]:
freq = {
k.lower() : counts.get(k.lower(), 0) + counts.get(k.upper(), 0)
for k in counts.keys() if k.isalpha()
}
freq
Out[10]: