-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctional_programming.py
77 lines (56 loc) · 1.83 KB
/
functional_programming.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
states = ["Kansas", "Nebraska", "North Dakota", "South Dakota"]
def urlify(string):
"""Converts a string into a URL-friendly string."""
return string.lower().replace(" ", "-")
#urls: imperative version
def imperatitve_urls(states):
urls = []
for state in states:
urls.append(urlify(state))
return urls
print(imperatitve_urls(states))
#urls: functional version, list comprehension
def functional_urls(states):
return [urlify(state) for state in states]
print(functional_urls(states))
#singles: imperative version
def imperatitve_singles(states):
singles = []
for state in states:
if len(state.split()) == 1:
singles.append(state)
return singles
print(imperatitve_singles(states))
#list comprehension to print only even numbers
print([n for n in range(10) if n % 2 == 0])
#singles: funcationl version
def functional_singles(states):
return [state for state in states if len(state.split()) == 1]
print(functional_singles(states))
#lengths: imperative version
def imperative_lengths(states):
lengths = {}
for state in states:
lengths[state] = len(state)
return lengths
print(imperative_lengths(states))
#lengths: functional version
def functional_lengths(states):
return{state: len(state) for state in states}
print(functional_lengths(states))
#genertor comprehension
squares = (n**2 for n in range(10**8 + 1))
#set comprehension with intersection
print({n for n in range(5,21)} & {n for n in range(10) if n % 2 ==0})
#set comprehension with union
print({n for n in range(5,21)} | {n for n in range(10) if n % 2 ==0})
numbers = range(0, 101)
#sum: imperative solution
def imperative_sum(numbers):
total = 0
for n in numbers:
total += n
return total
print(imperative_sum(numbers))
#sum: functional (and built in) solution
print(sum(numbers))