-
Notifications
You must be signed in to change notification settings - Fork 0
/
Functions
249 lines (180 loc) · 6.3 KB
/
Functions
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
def function_one():
print("Question one is the best question.")
function_one()
Exercise 2
Complete the following steps for this exercise:
Create a function named function_one that takes two string arguments named one and two
Create a function named function_two that takes three arguments named three, four and five
The first function should return both arguments separated by a space
The second function should multiply the arguments named three and five then add argument four and return the result.
def function_one(one, two):
return one + " " + two
def function_two(three, four, five):
return three * five + four
Exercise 3
Complete the following steps for this exercise:
The following functions must accept an unlimited number of arguments.
Create a function named test_odd that returns all the odd numbers
Create a function named test_even that returns all the even numbers
Create a function named find_max that returns the largest number
Create a function named find_min that returns the smallest number
Create a function named find_sum that returns the sum of all the numbers
The functions are only expected to work with integers.
hints,
The remainder after division by 2 can be used to find if an integer is odd or even. This can be computed using the modulo operator %
A Python max and min function will work over any numeric sequence.
def test_odd(*args):
odd = []
for i in args:
if i%2 != 0:
odd.append(i)
return odd
def test_even(*args):
even = []
for i in args:
if i%2 == 0:
even.append(i)
return even
def find_max(*args):
return max(args)
def find_min(*args):
return min(args)
def find_sum(*args):
tote = 0
for i in args:
tote += i
return tote
Exercise 4 Python Counter
In a the last tutorial there was an exercise called Lookup Table. Modify your answer to Lookup Table (or the provided solution) to read of any given Python file and count the reserve words occurring anywhere in that file.
There is no need to filter out reserve words in comments or quotes.
Scaffold code is provided to read the file.
There is no marker for this exercise. To test you code run it on the command line Feel free to experiment have a peek at the solution code if you get stuck.
#!/usr/bin/python3
import sys
import re
def verify_argv() :
if len(sys.argv) != 2 :
print("Expecting a file name")
exit(1)
#end if
def assign_prep_dict() :
#Our reserve word list.They are bit out of order.
word_list=["if","and","as","assert","async","break","False","None","True",
"class","continue","return","or","elif","else","except","finally",
"for","from","global","await","import","in","lambda","nonlocal",
"try","while","with","is","not","pass","raise","yield","def","del"
]
#We create a dict type called word_dict with keys from word_list
#and values 0
return dict.fromkeys(word_list,0)
#End def
def update_dict(code_line_list,word_dict):
#print("in update ",code_line_list)
i=0
while i < len(code_line_list) :
word_from_code = code_line_list[i]
#To see a word print(word_from_user)
if (word_from_code in word_dict) :
#We increament the word's data
word_dict[word_from_code]+=1
#print('found')
#End if
i+=1 #We must increment our loop to get the next word.
#print(i)
#End while
#End def
def read_file_data(file_name_text, word_dict):
file_data = open(file_name_text, "r")
text_line = file_data.readline()
while text_line :
tidy_text = text_line.strip()
line_list = re.split(' ',tidy_text)
#print(line_list)
update_dict(line_list,word_dict)
text_line = file_data.readline()
#End while
file_data.close()
#We loop over the input arguments from 1
def report_word_tote(word_dict):
#We loop over the sorted list.
for keys_item in sorted(word_dict.keys()) :
#We obtain the number of hits for a word
tote_hits_this_item = word_dict[keys_item]
#We only show the items with a non zero
#tote_hits_this_item.
if tote_hits_this_item > 0:
#Show the user our data
print(keys_item, tote_hits_this_item)
#End if
#End for
#End def
#The main code.
#Test for correct input
verify_argv()
file_name = sys.argv[1]
#Create a dict type with word list
word_dict=assign_prep_dict()
#print(word_dict)
#Read each line in the file and add to dict as needed.
read_file_data(file_name,word_dict)
#Show our result.
report_word_tote(word_dict)
import math
# 1. Factorial Calculation
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
# 2. Palindrome Check
def is_palindrome(string):
return string == string[::-1]
# 3. Fibonacci Series
def fibonacci(n):
fib_series = [0, 1]
while len(fib_series) < n:
fib_series.append(fib_series[-1] + fib_series[-2])
return fib_series
# 4. Prime Number Check
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
return False
return True
# 5. List Manipulation
sample_list = [4, 2, 8, 1, 5]
sorted_list = sorted(sample_list)
reversed_list = list(reversed(sample_list))
max_element = max(sample_list)
min_element = min(sample_list)
# 6. Dictionary Operations
sample_dict = {'a': 1, 'b': 2, 'c': 3}
sample_dict['d'] = 4 # Add a new key-value pair
sample_dict['b'] = 5 # Update the value of an existing key
# 7. File Handling
# Assume there's a file named 'sample.txt' with some content
with open('sample.txt', 'r') as file:
num_lines = len(file.readlines())
file.seek(0) # Reset file pointer
content = file.read()
# 8. String Manipulation
sample_string = "python programming"
substring_count = sample_string.count("pro")
split_string = sample_string.split()
reversed_string = sample_string[::-1]
# 9. Exception Handling
try:
result = 10 / 0
except ZeroDivisionError:
result = "Error: Division by zero!"
# 10. Class and Object Creation
class MyClass:
def __init__(self, x, y):
self.x = x
self.y = y
def add(self):
return self.x + self.y
obj = MyClass(3, 5)
sum_of_attributes = obj.add()