-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModule4.py
More file actions
861 lines (617 loc) · 17 KB
/
Copy pathModule4.py
File metadata and controls
861 lines (617 loc) · 17 KB
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 12 17:32:33 2021
@author: Wujian
"""
def message():
print("Enter a value: ")
message()
a = int(input())
message()
b = int(input())
message()
c = int(input())
# 4.2.1.2 How functions communicate with their environment
def message(number):
print("Enter a number:", number)
number = 1234
message(1)
print(number)
# 4.2.1.3 How functions communicate with their environment
def message(what, number):
print("Enter", what, "number", number)
# invoke the function
message("telephone", 11)
message("price", 5)
message("number", "number")
# 4.2.1.4 How functions communicate with their environment
def introduction(first_name, last_name):
print("Hello, my name is", first_name, last_name)
introduction("Skywalker", "Luke")
introduction("Quick", "Jesse")
introduction("Kent", "Clark")
# 4.2.1.5 Keyword argument passing
def introduction(first_name, last_name):
print("Hello, my name is", first_name, last_name)
introduction(first_name = "James", last_name = "Bond")
introduction(last_name = "Skywalker", first_name = "Luke")
# 4.2.1.7 How functions communicate with their environment
def introduction(first_name, last_name="Smith"):
print("Hello, my name is", first_name, last_name)
# Call the function here.
introduction("James", "Doe")
introduction("Henry")
introduction(first_name="William")
def introduction(first_name="John", last_name="Smith"):
print("Hello, my name is", first_name, last_name)
introduction()
# 4.3.1.1 Returning a result from a function
def happy_new_year(wishes = True):
print("Three...")
print("Two...")
print("One...")
if not wishes:
return
print("Happy New Year!")
happy_new_year()
happy_new_year(False)
def boring_function():
return 123
x = boring_function()
print("The boring_function has returned its result. It's:", x)
def boring_function():
print("'Boredom Mode' ON.")
return 123
print("This lesson is interesting!")
boring_function()
print("This lesson is boring...")
# 4.3.1.2 Returning a result from a function
value = None
if value is None:
print("Sorry, you don't carry any value")
# 4.3.1.3 Returning a result from a function
def strange_function(n):
if(n % 2 == 0):
return True
print(strange_function(2))
print(strange_function(1))
# 4.3.1.4 Returning a result from a function
def list_sum(lst):
s = 0
for elem in lst:
s += elem
return s
print(list_sum([5, 4, 3]))
# print(list_sum(5))
def strange_list_fun(n):
strange_list = []
for i in range(0, n):
strange_list.insert(0, i)
return strange_list
print(strange_list_fun(5))
# 4.3.1.6 LAB: A leap year: writing your own functions
def is_year_leap(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
# if (year % 4 == 0) and (year % 100) != 0:
# return True
#
# put your code here
#
test_data = [1900, 2000, 2016, 1987]
test_results = [False, True, True, False]
for i in range(len(test_data)):
yr = test_data[i]
print(yr,"->",end="")
result = is_year_leap(yr)
if result == test_results[i]:
print("OK")
else:
print("Failed")
# 4.3.1.7 LAB: How many days: writing and using your own functions
def is_year_leap(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
#
# Your code from LAB 4.3.1.6.
#
def days_in_month(year, month):
if month in [1, 3, 5, 7, 8, 10, 12]:
return 31
elif month==2:
if is_year_leap(year):
return 29
else:
return 28
elif month in [4,6,8,9,11]:
return 30
else:
return None
#
# Write your new code here.
#
test_years = [1900, 2000, 2016, 1987]
test_months = [2, 2, 1, 11]
test_results = [28, 29, 31, 30]
for i in range(len(test_years)):
yr = test_years[i]
mo = test_months[i]
print(yr, mo, "->", end="")
result = days_in_month(yr, mo)
if result == test_results[i]:
print("OK")
else:
print("Failed")
# 4.3.1.8 LAB: Day of the year: writing and using your own functions
def is_year_leap(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
#
# Your code from LAB 4.3.1.6.
#
def days_in_month(year, month):
if month in [1, 3, 5, 7, 8, 10, 12]:
return 31
elif month==2:
if is_year_leap(year):
return 29
else:
return 28
elif month in [4,6,8,9,11]:
return 30
else:
return None
#
# Your code from LAB 4.3.1.7.
#
def day_of_year(year, month, day):
# if is_year_leap(year) == True :return 366
# else: return 365
total = 0 # initializing the total variable to add results
# create loop to add only days in the months before the month in the input/test data
for i in range(1, month):
result = days_in_month(year, i)
total += result
day_num = total + day # add the value of the day argument to get day of the year
return day_num
#
# Write your new code here.
#
print(day_of_year(2000, 12, 31))
print(day_of_year(1999, 12, 31))
print(day_of_year(2021, 7, 29))
# 4.3.1.9 LAB: Prime numbers - how to find them
def is_prime(num):
# Write your code here.
if num < 2:
return False
elif num == 2:
return True
for n in range(2, num):
if num % n ==0:
return False
return True
for i in range(1, 30):
if is_prime(i + 1):
print(i + 1, end=" ")
print()
# 4.3.1.10 LAB: Converting fuel consumption
def liters_100km_to_miles_gallon(liters):
gallon = liters / 3.785411784
mile = 100/ 1.609344
return mile/gallon
#
# Write your code here.
#
def miles_gallon_to_liters_100km(miles):
km = miles * 1.609344
liters = 3.785411784
return 100 * liters/ km
#
# Write your code here
#
print(liters_100km_to_miles_gallon(3.9))
print(liters_100km_to_miles_gallon(7.5))
print(liters_100km_to_miles_gallon(10.))
print(miles_gallon_to_liters_100km(60.3))
print(miles_gallon_to_liters_100km(31.4))
print(miles_gallon_to_liters_100km(23.5))
# 4.3.1.11 SECTION SUMMARY
# Example 1
def wishes():
print("My Wishes")
return "Happy Birthday"
wishes() # outputs: My Wishes
# Example 2
def wishes():
print("My Wishes")
return "Happy Birthday"
print(wishes())
# outputs: My Wishes
# Happy Birthday
def hi_everybody(my_list):
for name in my_list:
print("Hi,", name)
hi_everybody(["Adam", "John", "Lucy"])
def create_list(n):
my_list = []
for i in range(n):
my_list.append(i)
return my_list
print(create_list(5))
# Exercise 1
def hi():
return
print("Hi!")
hi()
# Exercise 2
def is_int(data):
if type(data) == int:
return True
elif type(data) == float:
return False
print(is_int(5))
print(is_int(5.0))
print(is_int("5"))
# 4.4.1.2 Scopes in Python
def my_function():
print("Do I know that variable?", var)
var = 1
my_function()
print(var)
def my_function():
var = 2
print("Do I know that variable?", var)
var = 1
my_function()
print(var)
# 4.4.1.3 Scopes in Python | global
def my_function():
global var
var = 2
print("Do I know that variable?", var)
var = 1
my_function()
print(var)
# 4.5.1.2 Creating functions | two-parameter functions
def ft_and_inch_to_m(ft, inch = 0.0):
return ft * 0.3048 + inch * 0.0254
def lb_to_kg(lb):
return lb * 0.45359237
def bmi(weight, height):
if height < 1.0 or height > 2.5 or weight < 20 or weight > 200:
return None
return weight / height ** 2
print(bmi(weight = lb_to_kg(176), height = ft_and_inch_to_m(5, 7)))
# 4.5.1.3 Creating functions | three-parameter functions
def is_a_triangle(a, b, c):
return a + b > c and b + c > a and c + a > b
print(is_a_triangle(1, 1, 1))
print(is_a_triangle(1, 1, 3))
# 4.5.1.4 Creating functions | testing triangles
def is_a_triangle(a, b, c):
return a + b > c and b + c > a and c + a > b
a = float(input('Enter the first side\'s length: '))
b = float(input('Enter the second side\'s length: '))
c = float(input('Enter the third side\'s length: '))
if is_a_triangle(a, b, c):
print('Yes, it can be a triangle.')
else:
print('No, it can\'t be a triangle.')
def is_a_triangle(a, b, c):
return a + b > c and b + c > a and c + a > b
def is_a_right_triangle(a, b, c):
if not is_a_triangle(a, b, c):
return False
if c > a and c > b:
return c ** 2 == a ** 2 + b ** 2
if a > b and a > c:
return a ** 2 == b ** 2 + c ** 2
print(is_a_right_triangle(5, 3, 4))
print(is_a_right_triangle(1, 3, 4))
print(is_a_right_triangle(3, 5, 4))
# 4.5.1.5 Creating functions | right-angle triangles
def is_a_triangle(a, b, c):
return a + b > c and b + c > a and c + a > b
def heron(a, b, c):
p = (a + b + c) / 2
return (p * (p - a) * (p - b) * (p - c)) ** 0.5
def area_of_triangle(a, b, c):
if not is_a_triangle(a, b, c):
return None
return heron(a, b, c)
print(area_of_triangle(1., 1., 2. ** .5))
# 4.5.1.6 Creating functions | factorials
def factorial_function(n):
if n < 0:
return None
if n < 2:
return 1
product = 1
for i in range(2, n + 1):
product *= i
return product
for n in range(1, 10): # testing
print(n, factorial_function(n))
# 4.5.1.7 Creating functions | Fibonacci numbers
def fib(n):
if n < 1:
return None
if n < 3:
return 1
elem_1 = elem_2 = 1
the_sum = 0
for i in range(3, n + 1):
the_sum = elem_1 + elem_2
elem_1, elem_2 = elem_2, the_sum
return the_sum
for n in range(1, 10): # testing
print(n, "->", fib(n))
# 4.5.1.8 Creating functions | recursion
def fib(n):
if n < 1:
return None
if n < 3:
return 1
return fib(n - 1) + fib(n - 2)
def factorial_function(n):
if n < 0:
return None
if n < 2:
return 1
return n * factorial_function(n - 1)
def fib(n):
if n < 1:
return None
if n < 3:
return 1
elem_1 = elem_2 = 1
the_sum = 0
for i in range(3, n + 1):
the_sum = elem_1 + elem_2
elem_1, elem_2 = elem_2, the_sum
return the_sum
for n in range(1, 10):
print(n, "->", fib(n))
# 4.5.1.9 SECTION SUMMARY
# Recursive implementation of the factorial function.
def factorial(n):
if n == 1: # The base case (termination condition.)
return 1
else:
return n * factorial(n - 1)
print(factorial(4)) # 4 * 3 * 2 * 1 = 24
# 4.6.1.1 Tuples and dictionaries
one_element_tuple_1 = (1, )
one_element_tuple_2 = 1.,
# 4.6.1.2 Tuples and dictionaries
my_tuple = (1, 10, 100, 1000)
print(my_tuple[0])
print(my_tuple[-1])
print(my_tuple[1:])
print(my_tuple[:-2])
for elem in my_tuple:
print(elem)
# 4.6.1.3 Tuples and dictionaries
my_tuple = (1, 10, 100)
t1 = my_tuple + (1000, 10000)
t2 = my_tuple * 3
print(len(t2))
print(t1)
print(t2)
print(10 in my_tuple)
print(-10 not in my_tuple)
var = 123
t1 = (1, )
t2 = (2, )
t3 = (3, var)
t1, t2, t3 = t2, t3, t1
print(t1, t2, t3)
# 4.6.1.5 Tuples and dictionaries
dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"}
words = ['cat', 'lion', 'horse']
for word in words:
if word in dictionary:
print(word, "->", dictionary[word])
else:
print(word, "is not in dictionary")
# 4.6.1.6 Tuples and dictionaries | methods
dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"}
for key in sorted(dictionary.keys()):
print(key, "->", dictionary[key])
# 4.6.1.7 Tuples and dictionaries | methods
dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"}
for english, french in dictionary.items():
print(english, "->", french)
dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"}
for french in dictionary.values():
print(french)
# 4.6.1.8 Tuples and dictionaries
dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"}
dictionary['cat'] = 'minou'
print(dictionary)
dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"}
dictionary['swan'] = 'cygne'
print(dictionary)
dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"}
dictionary.update({"duck": "canard"})
print(dictionary)
dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"}
del dictionary['dog']
print(dictionary)
dictionary = {"cat": "chat", "dog": "chien", "horse": "cheval"}
dictionary.popitem()
print(dictionary) # outputs: {'cat': 'chat', 'dog': 'chien'}
# 4.6.1.9 Tuples and dictionaries
school_class = {}
while True:
name = input("Enter the student's name: ")
if name == '':
break
score = int(input("Enter the student's score (0-10): "))
if score not in range(0, 11):
break
if name in school_class:
school_class[name] += (score,)
else:
school_class[name] = (score,)
for name in sorted(school_class.keys()):
adding = 0
counter = 0
for score in school_class[name]:
adding += score
counter += 1
print(name, ":", adding / counter)
# 4.6.1.10 SECTION SUMMARY (1/3)
# Example 1
tuple_1 = (1, 2, 3)
for elem in tuple_1:
print(elem)
# Example 2
tuple_2 = (1, 2, 3, 4)
print(5 in tuple_2)
print(5 not in tuple_2)
# Example 3
tuple_3 = (1, 2, 3, 5)
print(len(tuple_3))
# Example 4
tuple_4 = tuple_1 + tuple_2
tuple_5 = tuple_3 * 2
print(tuple_4)
print(tuple_5)
my_tuple = tuple((1, 2, "string"))
print(my_tuple)
my_list = [2, 4, 6]
print(my_list) # outputs: [2, 4, 6]
print(type(my_list)) # outputs: <class 'list'>
tup = tuple(my_list)
print(tup) # outputs: (2, 4, 6)
print(type(tup)) # outputs: <class 'tuple'>
# 4.6.1.11 SECTION SUMMARY (2/3)
pol_eng_dictionary = {
"zamek": "castle",
"woda": "water",
"gleba": "soil"
}
for key, value in pol_eng_dictionary.items():
print("Pol/Eng ->", key, ":", value)
#Exercise 3
# Complete the code to correctly use the count() method to
# find the number of duplicates of 2 in the following tuple.
tup = 1, 2, 3, 2, 4, 5, 6, 2, 7, 2, 8, 9
tup
duplicates = tup.count(2)# Write your code here.
print(duplicates) # outputs: 4
#Exercise 4
# Write a program that will "glue" the two dictionaries (d1 and d2) together
# and create a new one (d3).
d1 = {'Adam Smith': 'A', 'Judy Paxton': 'B+'}
d2 = {'Mary Louis': 'A', 'Patrick White': 'C'}
d3 = {}
for item in (d1, d2):
# Write your code here.
d3.update(item)
print(d3)
# Exercise 5
# Write a program that will convert the my_list list to a tuple.
my_list = ["car", "Ford", "flower", "Tulip"]
t = tuple(my_list)
# Write your code here.
print(t)
# Exercise 6
# Write a program that will convert the colors tuple to a dictionary.
colors = (("green", "#008000"), ("blue", "#0000FF"))
# Write your code here.
colors_dictionary = dict(colors)
print(colors_dictionary)
# 4.7.1.5 Exceptions (two exceptions)
try:
value = int(input('Enter a natural number: '))
print('The reciprocal of', value, 'is', 1/value)
except ValueError:
print('I do not know what to do.')
except ZeroDivisionError:
print('Division by zero is not allowed in our Universe.')
import math
math.sqrt(9)
math.sqrt(-3)
short_list = [1]
short_list.append(2)
short_list.depend(3)
# 4.7.1.8 Testing and debugging
temperature = float(input('Enter current temperature:'))
if temperature > 0:
print("Above zero")
elif temperature < 0:
print("Below zero")
else:
print("Zero")
# 4.7.2.1 PROJECT: Tic-Tac-Toe
def display_board(board):
# The function accepts one parameter containing the board's current status
# and prints it out to the console.
def enter_move(board):
# The function accepts the board's current status, asks the user about their move,
# checks the input, and updates the board according to the user's decision.
def make_list_of_free_fields(board):
# The function browses the board and builds a list of all the free squares;
# the list consists of tuples, while each tuple is a pair of row and column numbers.
def victory_for(board, sign):
# The function analyzes the board's status in order to check if
# the player using 'O's or 'X's has won the game
def draw_move(board):
# The function draws the computer's move and updates the board.
# PE1 module 4 quiz
tup = (1,) + (1,)
tup = tup + tup
print(len(tup))
tup = (1,)
len(tup)
10/0
value = input("enter a value: ")
print(10/value)
# module 4 test
# Q3
def fun(x):
if x % 2 == 0:
return 1
else:
return
print(fun(fun(2))+1)
# Q6
tup = (1,2,4,8)
tup = tup[1:-1]
tup = tup[0]
print(tup)
# Q7
def any():
print(var + 1, end='')
var =1
a= any()
print(a)
print(var)
# Q8
my_list = ['Mary', 'had', 'a', 'little', 'lamb']
def my_list(my_list):
del my_list[3]
my_list[3] = 'ram'
print(my_list(my_list))
# Q11
try:
# value=int(input('enter a value: '))
value=input('enter a value: ')
print(value/value)
except ValueError:
print("Bad input...")
except ZeroDivisionError:
print("Very bad input...")
except TypeError:
print("Very very bad input...")
except:
print("Booo!")
# Q20
dictionary = {}
my_list = ['a', 'b', 'c', 'd']
for i in range(len(my_list) - 1):
dictionary[my_list[i]] = (my_list[i],)
for i in sorted(dictionary.keys()):
k = dictionary[i]
#print(k[0])
print(k)