-
Notifications
You must be signed in to change notification settings - Fork 0
/
exam_revision_20-2_trimmed.py
3615 lines (1783 loc) · 57.1 KB
/
exam_revision_20-2_trimmed.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
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
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# pylint: disable=all
# type: ignore
#region Code without hints
# List of all questions to be revised. Every question is a flavour of one I got wrong (out of over 600 in total), added here each time.
# One set of '*****' indicates I got the question wrong again a number of days after previously revising it. Additional stars (or dates), wrong again, and so on.
# All answers are corrected before this document is saved by me. If any are blank I deleted the answer as extra reminder to re-revise that question. No answers will be 'left incorrect' before I upload this file to github.
# Q10 Which of the following lines describe a true condition? 20-2
print('smith' > 'Smith')
print('Smiths' < 'Smith' )
print( 'Smith' > '1000' )
print( '11' < '8' )
print('!' < '5')
# Answer: ALL CORRECT
# Q12 A) What is the expected result of the following code? mmmmm mmmmm 25-1 19-2 26-2
s1 = '45.6'
i = int(s1)
s2 = str(i)
f = float(s2)
print(s1 == s2)
# Answer: NOT A FUCKING TYPE ERROR! ITS THE VALUE THATS WRONG! STRING IS NOT AN INVALID DATA TYPE FOR THE INT() FUNCTION!!!!!!!
# Q12 B) What if s1 was a float?
# Answer: False
# Q13 What is the expected value of the result variable after the following code is executed? 20-2
import math
result = math.e == math.exp(1)
# Answer: Technically false but would be True: rounding error.
# Q16 You want to prevent your module's user from running your code as an ordinary script. How will you achieve such an effect? 20-2
# Answer: place the main calls/usage in an if condition:
if not __name__ == '__main__':
# <some code>
''' mmmmm mmmmm 21-1 20-2
Q25:
A) What apt command removes installed software? And what pip command removes an installed package?
# Answer: sudo apt remove packagename pip uninstall packagename
B) What is the pip command to view all installed packages?
# Answer: pip list
C) What is the pip command to view a package's dependencies?
# Answer: pip show packagename
D) What is the pip command to search for packages?
# Answer: pip search packagename (no longer works)
E) What is the pip command to update a package?
# Answer: pip install -U packagename
F) In the command `pip --version`, is 'version' a command or an option?
# Answer: An option of the 'pip' command itself 'Version' is' a general option of the pip command itself. The typical usage is `pip <command> [options] <target>`. But here, pip is the only command, so the --version flag follows directly.
G) What is the pip command if you only wanted to install version 1.0.4 of a package for the current user?
# Answer: pip install --user 'packagename==1.0.4'
'''
''' Q26 mmmmm
# Explain how to:
1. Check pip version?
2. Install pip package?
3. Install pip package only for the current user ?
4. What is the small flag ('-u') used for?
'''
# Answer:
1. pip --version
2. pip install packagename
3. pip install --user packagename or pip install -u packagename
4. No such option. Will cause an error.
# b) What is the output of the following snippet? 21-1 REDO FOR WINDOWS FOR: platform.machine(), platform.processor(),
import platform
print(platform.machine(), platform.processor(), platform.system(), platform.platform(), platform.version())
# Answer:
"""
x86_64 or AMD64
x86_64 or Intel64 Family 6 Model 158 Stepping 9, GenuineIntel
Linux or Windows
Linux Kernel Build Info and CPU or Windows-10-10.0.19045-SP0
Linux Distribution + version or 10.0.19045
"""
""" Answers (for referece)
# x86 x86 linux Linux_Kernel_Build_Info_and_CPU linux_distro
# or x86 x86 windows 'windows 10 [build_info]' build_info
"""
# Q34 What is the result of: ***** ***** mmmmm mmmmm
s = '123456789'
for i in range(len(s)):
print(math.floor(int(s[i])) and math.ceil(int(s[i])))
''' Answer:
1
2
3
4
5
6
7
8
9
'''
# Q35 What is the output of print(math.radians(90))? 20-2
# Answer: 1.57
# Q44 a): Name four list methods that return a value and seven that don't. Also list the parameters for each.
'''
Answer:
l.pop([i])
l.count()
list.index(x[, start[, end]])
l.copy() 20-2
l.insert(i, x)
l.append(x)
l.extend(iterable)
l.reverse()
l.sort(*, key=None, reverse=False)
remove(x)
clear()
x = value
i = index
'''
# Q45: How many arguments does the string class's 'join' method take? And what data type does it take? ***** 20-2
# Answer:
1, iterable
''' Q48: A) Write three snippets to iterate through the dictionary. B) Also, if iterating over a dictionary directly without these methods, what is iterated? 20-2
i) its key-value pairs
ii) only its keys
iii) only its values
'''
dic = {1: 'one', 2: 'two', 3: 'three'}
''' Answer:
i) for i in dic.items()
ii) for i in dic.keys()
iii) for i in dic.values()
'''
# Answer (B): Only its keys. Using `for i in dic.keys()` is the same as just doing `for i in dic`.
# Q49: A) What is the ouput of this? B) And what if we removed the first two lines? mmmmm 20-2
lst_obj = (-1, 11, 0)
lst_obj[0] += 1
obj = range(1, 11, 0)
# Answer (A): TypeError
# Answer (B): ValueError
# Q55: What is the output? nnnnn 20-2
elements = {}
for character in 'Gandalf':
if character in 'Saruman':
elements[ord(character)] = character
else:
elements[ord('u')] = 'u'
for key in elements.keys():
print(elements[key], end=' ')
# Answer: a n u
# Q58 c): What are the rules for the 'import' keyword if used without 'from'? 21-1 20-2
# Answer: What's after 'import' can only be a module or a package. The full path of whats specified after the 'import' keyword is whats added to the namespace and must be used for accessing.
""" Q75: List 7 open() modes and their behaviour.
r: reads from beginning; file must exist or raises FileNotFoundError
w: creates or truncates; existing file not required.
r+: reads & update; reads or writes starting at the beginning; file must exist.
w+: write & update: writes or reads from the beginning; existing file not required.
x: creates a file for writing at the beginning; raises FileExistsError if file exists. Safer alternative to 'w'.
a: append opens or creates a file for writing at the end; existing file not required.
a+: opens (or creates) a file for appending at the end; existence not required; writes always move the position (back) to the end.
"""
# Q78: True or false for each of these? 21-2 (mix up)
print(bool(''), bool([]), bool(0,), bool({}), bool(None), end='')
print('', bool([[]]), bool((0,)))
# Answer:
"""
F, F, F, F, F, T, T
"""
# b) Which of the following is a true statement? (Select 2 Answers) 21-2
"""
Unicode is a standard
UTF-8 is an encoding
Unicode is an encoding
UTF-8 is a standard
UTF-8 is the only encoding apart from ASCII
"""
# Answer: Unicode is a standard. UTF-8 is an encoding.
# Q84: What are each of these constants? 22-1 Got all correct (26-1) 21-2
"""
errno.EACCES →
# Answer:
errno.EBADF →
# Answer:
errno.EEXIST →
# Answer:
errno.EFBIG → ??????????
# Answer:
errno.EISDIR →
# Answer:
errno.EMFILE →
# Answer:
errno.ENOENT →
# Answer:
errno.ENOSPC →
# Answer:
"""
# Q88: What is the expected output of the following code snippet? 21-2 (also see Q94)
class GalaxyError(Exception):
pass
try:
raise Exception("X", "Y")
except GalaxyError:
print("Greetings", end=" ")
finally:
print("Farewell")
# Answer: Farewell will be executed but the exception will not be caught.
# Q90:
# a) What is the expected output of the following code snippet? 8-2 21-2 23-2
creature_stats = {'goblin':1, 'troll':2}
try:
creature_stats[1]
except IndexError:
print('Cave', end=' ')
except Exception as exc:
print(exc.args, end=' ')
# Answer:
# b) What distinguishes KeyError's error argument handling, specifically when accessing a non-existent key in a dictionary, from that of other Python error types?
# Answer: The bad key is passed to the args tuple instead of a description of the error. The non-existent key itself is passed as an argument, instead of a description of the error.
# Q91: What is the expected output of the following code snippet? What if the variable was mutable? 8-2
string_sequence = "def"
for element in string_sequence:
element = 'y'
print(string_sequence)
# Answer: def (also, see extra info below): def; the loop variable is just assigned the value, typically temporarily as its incremented. It is not the element it represents or even a reference to it.
# Changing the value of the loop variable does not affect the items in the iterable itself, even for mutables.
"""
string_sequence = "def"
for element in string_sequence:
print(element) #extra print() for tracking
element = 'y'
print(element) #extra print() for tracking
print(string_sequence)
Console
d
y #
e
y #
f
y #
def
"""
# Q92: Given the following classes: 8-2 correct_but_MORE_PRACTICE_NEEDED__21-2
class Star:
pass
class Nebula(Star):
pass
class Galaxy(Nebula):
pass
class BlackHole(Star):
pass
# Which of the following are correct declarations of subclasses (r.e., MRO)? (Select 2 Answers)
class CosmicPhenomenon1(Star, Nebula): # a
pass
class CosmicPhenomenon2(Galaxy, BlackHole): # b
pass
class CosmicPhenomenon3(Star, BlackHole): # c
pass
class CosmicPhenomenon4(Nebula, Galaxy): # d
pass
class CosmicPhenomenon5(BlackHole, Galaxy): # e
pass
# Answer: b, e
# Q93: 9-2
"""
The file abc.txt contains the following 3 lines of text:
abc
def
ghi
The output of the below snippet is:
<_io.TextIOWrapper name='abc.txt' mode='r' encoding='cp1252'>
What would happen if we tried to iterate over the stream directly?
"""
file = open('abc.txt')
print(file)
# Answer: Acting as an iterator, io.TextIOWrapper calls __next__, printing the text up to the next new line character until StopIteration is raised when reaching EOF.
# Q94: What is the expected output of the following code snippet? 8-2
class ExampleException(Exception):
def __init__(self, msg):
super().__init__(msg)
def __str__(self):
return 'a'
try:
raise ExampleException('test')
except Exception as e: # see note (scroll right) This line does NOT alter the instance of the exception that was raised (see below**)!
print(e)
# Answer: a
# Q96: What is the output of the following snippet of code? 8-2 21-2
class A:
pass
class B:
pass
class C(B):
pass
c = C()
print(isinstance(c, (B,A)))
# Answer: True
# Q97: A)Which of the following snippets outputs 'abc' to the screen? (Select two answers). 21-2
# Option A
print(sorted("abc"))
# Option B
temporary_variable = "abc".sort()
print(str(temporary_variable))
# Option C
print(''.join(sorted("abc")))
# Option D
temporary_variable2 = list("abc")
temporary_variable2.sort()
print(''.join(temporary_variable2))
# Answer: c & d
# B) What data type does sorted() always return? And what can it not sort?
# Answer: sorted() always returns a list (and automatically converts other types to lists). However, it can't sort between different data types, i.e., between 'str' and 'int'.
# C) What would be the output if the 2 lines in option B were executed? 23-2
# Answer: AttributeError: 'str' object has no attribute 'sort'
# Q98: What is the output of the following snippet of code? 11-2
x = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
def func(data):
res = data[0][0]
for da in data:
for d in da:
if res < d:
res = d
return res
print(func(x[0]))
# Answer: 4
# Q99: What is the output of the 2 following snippets?
class E (Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return "it's nice to see you"
try:
print("I feel fine")
raise E("what a pity")
except Exception as e:
print(e)
else:
print("the show must go on")
"""Answer:
I feel fine"
it's nice to see you
"""
"""
Python exceptions are designed so that more general except branches are capable of catching a wider number of exceptions. This means a superclass in
the except branch can catch its subclass exceptions.
To catch a more concrete exception when both concrete and non-concrete branches exist, the subclasse(s) or 'more concrete' exception(s) should be placed first.
"""
class E (Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return "it's nice to see you"
try:
print("I feel fine")
raise Exception("what a pity")
except E as e:
print(e)
else:
print("the show must go on")
# Answer: Not caught.
"""
However, if the except branch is a subclass of the exception (i.e., the exception being RAISED is the parent), it can not catch the exception. This is similar
to how an instance of a superclass doesn't have the attributes of its subclasses.
If subclasses could catch superclass exceptions, it would lead to a scenario where very specific handlers are invoked for general problems they're not designed
to address directly, potentially leading to inappropriate error handling.
"""
# Q100: What is the output?
print('' in '', '' in ' a')
# Answer: True True
# Q101 - Error Handling
# Q: Which of the following is false?
#1 A try statement can have a finally clause without an except clause.
#2 A try statement can have one or more finally clauses.
#3 A try statement can have one or more except clauses.
#4 A try statement can have a finally clause and an except clause.
# Answer: 2
# Q102:
# A) Given the code below, complete the display() method body in a way that will ensure that the retrieve() method is properly invoked.
class Artifact:
def __init__(self):
self.collection = 1
def retrieve(self):
return self.collection
def display(self):
# Insert a method here
item = Artifact()
item.display()
# (Select two answers.)
print(Artifact.retrieve(self))
print(Artifact.retrieve())
print(retrieve())
print(self.retrieve())
# Answer: 1st, 4th.
# B) Comment out the incorrect lines, make two small corrections, then run the program to check it works. CORRECT_BUT_NEED_MORE_PRACTICE_21-2
class ScienceExperiment:
variable = 'Experiment Data'
def __init__(self):
experiment_note = 'Note Content'
print(self.experiment_note)
def record(self):
observation = 'Observation Details'
print(self.observation)
test = ScienceExperiment()
test.record()
ScienceExperiment.experiment_note
ScienceExperiment.record()
print(test.__dict__)
print(test.experiment_note)
# Answer (did it work)?: yes, you can't do class.instance_variable, as it'll look for a class variable that doesn't exist. You also can't 'only' do class.instance_method() because the method would be missing the 1 required positional arg: 'self'. # Hint: 'self'
# Q103:
# A) Is the result of the following line 0 or 0.0?
print(1 // 2 * 3)
# Answer: 0
# B) What's the result this time? Why?
print(9 // 3 // 1.0)
# Answer: 3.0 # The divide (/) operator always returns a float. The floor divide (aka int division) operator (//) truncates to an integer if all operands are ints. If at least one operand is a float, '//' returns a float.
#Q104: What is the output and why?
def t():
return 'Peter''Wellert'
print(t())
# Answer: PeterWellert: Python concatenates the strings.
#Q105: 21-2
# A) Provide a detailed list of all the output for this snippet (any order will do).
class MyClass:
"""docstring test"""
class_var = 1
def __init__(self):
self.instance_var = 1
def my_meth(self):
pass
object = MyClass()
for i in MyClass.__dict__:
print(i, '\t\t', MyClass.__dict__[i])
# Answer:
__module__ # type(MyClass.__dict__['__module__']) == type('string') output: True same as Class.__module__ in ...ntedProgramming/Introspection/..._miscellaneous_summary.py
__dict__
__doc__
__weakref__
__init__
my_meth
class_var
"""
__module__ __main__ 23-2
__dict__ <attribute '__dict__' of 'MyClass' objects>
__weakref__ <attribute '__weakref__' of 'MyClass' objects>
__doc__ docstring test
__init__ <function MyClass.__init__ at 0x...>
my_meth <function MyClass.my_meth at 0x...>
class_var 1
Note: The dictionary can be used to access these entities directly, i.e., they're not just strings. NB: Class.__module__ itself is actually just a string!
"""
# Q106: What is the output for each snippet? 21-2
lst = [1, 2]
lst += (1, 2, 3)
print(lst)
# Answer:
print([1, 2] * 2 + [3])
# Answer:
print([1, 2] + list((3, 4)))
# Answer:
print([1, 2] + (3, 4))
# Answer:
lst = [1, 2]
lst.append([3, 4])
print(lst)
# Answer:
lst = [1, 2, 3]
lst.append((1,))
print(lst)
# Answer:
lst = [1, 2, 3]
lst += (1,)
print(lst)
# Answer:
print([[]] * 3)
# Answer:
tup1 = (1, 2)
tup2 = (3, 4)
print([tup1] + [tup2])