-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunc_ret_func.py
71 lines (58 loc) · 2.38 KB
/
func_ret_func.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
'''
Created on Jan 27, 2015
Last modified on Feb 1, 2016
@author: Brian Borowski
CS115 - Functions returning functions
'''
from cs115 import map, reduce
from builtins import len
def div(k):
'''Checks whether 42 is evenly divisible by an integer k.'''
return 42 % k == 0
def divides(n): # What does this do?
def div(k):
return n % k == 0
return div
print(divides(100)(2))
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Exercise
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
def increment(n):
'''Returns a function that takes in k and adds it to n.'''
def add_n_to(k):
return n + k
return add_n_to
def inc_all(nums, n):
'''Add n to every number in a given list of numbers.'''
return map(increment(n), nums)
def test_inc_all():
'''Tests for inc_all. Correct tests print True.'''
print(inc_all([], 2) == [])
print(inc_all([1, 3, 5], 2) == [3, 5, 7])
print(inc_all([-2, -1, 0, 1, 2], 10) == [8, 9, 10, 11, 12])
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Another example involving functions that return functions.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
words = ['abate', 'abbey', 'abet', 'abhor', 'abide', 'able', 'ably',
'about', 'above', 'abundant', 'abuse', 'abyss', 'ac', 'ace',
'ache', 'achy', 'acid', 'acne', 'acorn', 'acre', 'acrid']
def make_len(n):
'''Assume n is a non-negative integer. Return a function.
That function applies to strings. It concatenates * characters
to the given string, to make its length at least n.'''
def pad_it(word):
return word + '*' * (n - len(word))
return pad_it
def pad(words):
'''Assume words is a non-empty list of strings. Let n be the
length of the longest. Return a list of the same strings except
with enough * characters appended to make each one length n.'''
return map(make_len(reduce(max, map(len, words))), words)
def test_pad():
'''Tests for pad. Correct tests print True.'''
print(pad(['abate', 'abbey']) == ['abate', 'abbey']) # no padding
print(pad(['a', 'cat']) == ['a**', 'cat'])
print(pad(['three', 'cats', 'asleep', 'now'])
== ['three*', 'cats**', 'asleep', 'now***'])
test_inc_all()
test_pad()