#!/usr/bin/env python # coding: utf-8 # # Python 3 # ## Functions # 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) # 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) # In[4]: values_tuple = (0,0,1,1) euclidean_distance(*values_tuple) # 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) # In[13]: list(zip([1,2,3,4,5,6])) # ## Comprehensions # With comprehensions, we can build a sequence based on another iterable. # In[6]: # List comprehension [num ** 2 for num in range(-10, 11)] # In[7]: [num ** 2 for num in range(-10, 11) if num > 0] # 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 } # ### Dictionary comprehension # In[9]: s = "Action Is Eloquence" counts = dict() for char in s: counts[char] = counts.get(char, 0) + 1 counts # In[10]: freq = { k.lower() : counts.get(k.lower(), 0) + counts.get(k.upper(), 0) for k in counts.keys() if k.isalpha() } freq