-
Notifications
You must be signed in to change notification settings - Fork 0
/
unit2_lesson_04_understanding_functions_part1.py
233 lines (173 loc) · 6.39 KB
/
unit2_lesson_04_understanding_functions_part1.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
__author__ = 'Kalyan'
from placeholders import *
notes = '''
Functions are the basic unit of modularization in python. You use functions to group
together a meaningful action and use it when you need it.
The feature set of functions in python is richer than every major programming
language and makes it easy to expose elegant and usable apis.
This is a big topic, in this lesson we will cover the following:
- functions are first class objects in python! they can be created, assigned, and passed around as any other object
as part of regular program flow.
- function documentation
- function return values, parameters and defaults
- defining new functions
be sure to understand
https://docs.python.org/3/glossary.html#term-parameter
https://docs.python.org/3/glossary.html#term-argument
'''
# here's a simple function. returns nothing
def my_print(x):
"my_print documentation"
print(x)
# this is another function. Note the syntax. Returns a value
def my_increment(x):
return x + 1
# another function, it is common to return multiple values as a tuple.
def my_min_max(numbers):
return (min(numbers), max(numbers))
# functions are kinds of objects, they have a type too!
def test_function_type():
assert "function" == type(my_print).__name__
assert "function" == type(my_increment).__name__
assert "function" == type(test_function_type).__name__
# functions are objects which can be 'called'
def test_function_callable_type():
assert False == callable(1)
assert True == callable(my_increment)
assert False == callable(my_increment(10))
# functions can be held by references just like any other object
def test_function_assignment():
demo = my_increment
result = demo(20)
assert 21 == result
# every function returns an object, even when it does not!
def test_every_function_returns_something():
result = my_print(10)
assert None == result
result = my_increment(10)
assert 11 == result
result = my_min_max([20, 30, 5])
assert (5,30) == result
def demo1():
"""returns 10"""
return 10
def demo2():
return 20
#The documentation of every function, if the author wrote it, is available at runtime.
#This makes it easy to access help from console or build specialized help commands like help.
def test_function_documentation():
assert """returns 10""" == demo1.__doc__
assert None == demo2.__doc__
def my_callfunc(func):
return func()
# functions can be passed around.
def test_functions_can_be_passed_as_objects():
assert 10 == my_callfunc(demo1)
assert 20 == my_callfunc(demo2)
# an example of a default parameter
def my_greet(greeting, name="world"):
return "{0} {1}".format(greeting, name)
def test_default_parameters():
assert "Hello world" == my_greet("Hello")
assert "Hello john" == my_greet("Hello", "john")
def my_add_to_list1(sequence, target=[]):
"""
Uses a mutable default, usually leads to unexpected behavior
"""
target.extend(sequence)
return target
def my_add_to_list2(sequence, target=None):
"""
Uses None as default and creates a target list on demand.
"""
if target is None:
target = []
target.extend(sequence)
return target
def test_function_defaults_are_evaluated_at_definition_time():
assert ['h', 'i'] == my_add_to_list1("hi")
assert ['h', 'i', 'b', 'y', 'e'] == my_add_to_list1("bye")
assert ['h', 'i'] == my_add_to_list2("hi")
assert ['b', 'y', 'e'] == my_add_to_list2("bye")
reading_note = """
Walk through the visualizer to get a good idea of how functions are defined
and how arguments are passed.
Experiment with this code in visualizer (see output and the variable references, do it in full screen mode).
https://goo.gl/cwL54H
Do this before proceeding further.
"""
def demo_parameter_passing1(x):
x = x + 1
def demo_parameter_passing2(names):
names = []
def demo_parameter_passing3(names):
names.append("something")
def test_function_params_passed_by_object_reference():
x = 10
demo_parameter_passing1(x)
assert 10 == x
names = ["one", "two"]
demo_parameter_passing2(names)
assert ["one", "two"] == names
demo_parameter_passing3(names)
assert ["one", "two","something"] == names
notes_2 = """
Read this finally :): http://effbot.org/zone/call-by-object.htm
"""
# Most of the python api uses the ability to pass functions as arguments,
# the tests below make you exercise them.
# write your new functions here (use names that do not collide with other names)
# new functions end
VOWEL_SET = set("aeiou")
def get_consonents(input):
return set(set(input.lower())-VOWEL_SET)
def get_word_with_least_vowels(input):
"""
returns the word with least number of vowels.
"""
# replace this with right code. Use min builtin and define a new function to pass as key.
m=100
input=list(input)
for i in range(len(input)):
r=get_consonents(input[i])
s=abs(len(r)-len(set(input[i])))
if(m>s):
m=s
re=input[i]
return re
def test_get_word_with_least_vowels():
assert "fly" == get_word_with_least_vowels(["apple", "joy", "fly"])
assert "flow" == get_word_with_least_vowels(["apple", "hello", "flow"])
# same code works for any iterable!
assert "fly" == get_word_with_least_vowels({"apple", "joy", "fly"})
assert "flow" == get_word_with_least_vowels(("apple", "hello", "flow"))
def get_min_max_words(input):
"""
returns the words with the least and maximum length.
Use min and max and pass another function as argument
"""
input=list(input)
for i in range(len(input)):
l=len(input[i])
if(i==0):
min=l;
max=l;
mi = input[i];
ma=input[i]
else:
if(min>l):
min=l
mi = input[i];
if(max<l):
max = l
ma = input[i];
return (mi,ma)
def test_get_min_max_words():
assert ("fly", "engine") == get_min_max_words(["fork", "engine", "fly"])
assert ("fork", "fork") == get_min_max_words(["fork"])
assert ("fork", "automobile") == get_min_max_words({"fork", "automobile", "tester"})
three_things_i_learnt = """
-
-
-
"""