<jupyter_start><jupyter_text>Exercise 9Related Notes:- Fundamentals_6_Data_Validation_And_Program_Testing  Exercise 9.1Consider the code in the code cell below.Clearly, there is a bug in this code. Identify the bug and then use a `try-except` statement to “fix” the code so that it works as intended. (Note that you may not utilise `else` or `finally` in the `try-except` statement.).<jupyter_code>numbers = [x for x in range(1000)]
i = 0
while True:
    print(str(numbers[i]))
    i += 1
numbers = [x for x in range(1000)]+[1001]
i = 0
try:
    while True:
        print(str(numbers[i]))
        i += 1
        
except IndexError as e:
    False
numbers = [x for x in range(1000)]+[1001]
i = 0
while True:
    try:
        print(str(numbers[i]))
        i += 1
    except IndexError:
        print("You're printing out of the index range, brudda.")
        break<jupyter_output>0
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
27[...]<jupyter_text>Exercise 9.2Consider the code in the code cell below.Once again, there is a problem with this code. Use the `try-except` statement to ensure the code does not cause a runtime error. (Note: you may not change the way name is generated or used.)<jupyter_code>from random import randint
name = ""
for i in range(100):
    name = name + str(randint(0, 9))
    name = name + ".txt"
    fileHandle = open(name)
    data = f.read()
    print(data)
    f.close()
#YOUR_CODE_HERE
for i in range(100):
    name = str(randint(0,9)) + ".txt"
    try:
        fileHandle = open(name)
        data = fileHandle.read()
        print(data)
        fileHandle.close()
    except FileNotFoundError:
        fileHandle = open(name, 'w')
        fileHandle.close()<jupyter_output><jupyter_text>Exercise 9.3Write code that continually asks for rational number input from the user (until the string `exit` is inputTED). For each value entered, (if it is not the string `exit`) utilise exception handling to verify that the inputs are indeed rational numbers before saving them to the file called `RATIONALS.TXT`. (Note that your code should open, write, and close the file with each entry. Also comment why this may be a more prudent course of action.)<jupyter_code>#YOUR_CODE_HERE
while True:
    a = input("input rational no.")
    if a == 'exit':
        break
    try:
        a = float(a)
        f = open('rationals.txt','a')
        f.write(str(a)+'\n')
        f.close()
    except ValueError:
        pass
        print('bullsh*t')<jupyter_output>input rational no.apple
bullsh*t
input rational no.asdf
bullsh*t
input rational no.math.pi
bullsh*t<jupyter_text>Exercise 9.4The file `WORDS.TXT` under the folder `resources` contains a list of single word computing terms used in a textbook.	Each entry has the following format:>```python>>>```One of the file entries (in both files) is:>```python>program	>52>```	This means that after a complete scan of the textbook the word `program` was found 52 times.	By utilising the `try-except` statement, write program code to find and output the term with the highest number of occurrences.<jupyter_code>#YOUR_CODE_HERE
def maxim():
    with open("resources/WORDS.TXT",'r') as f:
        x = [i.strip() for i in f.readlines()]
    y = []
    print(x)
    for j in x:
        try:
            y.append(int(j))
        except ValueError:
            None
    return  x[x.index(str(max(y))) - 1] # takes the one before the value itself.

maxim()<jupyter_output>['compiler', '12', 'interpreter', '9', 'procedure', '22', 'function', '29', 'statement', '24', 'program', '52', 'encapsulation', '12', 'compression', '4', 'field', '11', 'attribute', '17', 'entity', '18', 'magnetic', '9', 'optical', '14', 'barcode', '8', 'anti-virus', '7', 'boolean', '12', 'buffer', '9', 'star', '3', 'bridge', '2', 'router', '13', 'hub', '11', 'identifier', '23', 'system', '86', 'global', '19', 'local', '26', 'command', '28', 'translator', '7', 'lexical', '5', 'syntax', '29', 'infix', '14', 'postfix', '12', 'iteration', '19', 'iterative', '14', 'recursive', '19', 'infra-red', '15', 'communications', '27', 'handshaking', '11', 'protocol', '15', 'integer', '23', 'real', '19', 'string', '27', 'character', '24', 'loop', '23', 'selection', '21', 'interrupt', '15', 'Internet', '29', 'initialisation', '8', 'logic', '4', 'library', '2', 'declarative', '4', 'object-oriented', '9', 'encryption', '9', 'computer', '86', 'analysis', '6', 'design', '18', 'implementation', '6', 'test[...]<jupyter_text>Exercise 9.5 ISBN The International Standard Book Number (ISBN) is a numeric commercial book identifier which is intended to be unique. Publishers purchase ISBNs from an affiliate of the International ISBN Agency.Write a code that - takes in a string input,- return `True` if the string is either a valid ISBN-10 or ISBN-13 numbers.Each line in the text file, `ISBN_EXERCISE.TXT` under the folder `resources`, contain ISBN-10 or ISBN-13 which can be valid or invalid.Write a program to:- print out the valid ISBNs in the file.- print out the number of valid ISBNs in the file.<jupyter_code>import csv
def isValid(a):
  b = [10 if x == 'X' else int(x) for x in a if x not in '- ']
  if len(b) ==10:
    total = 0
    for i in range(len(b)):
        total+= (len(a)-i)*b[i]
    return (total/11).is_integer()
  elif len(b) == 13:
      total = 0
      for i in range(len(b)):
          if i%2 == 0:
              total += b[i]
          else:
              total +=b[i]*3

      return (total/10).is_integer()
  else:
      return 

with open('ISBN_EXERCISE.txt') as f:
  reader = csv.reader(f,delimiter = ':')
  count = 0
  for row in reader:
    if isValid(row[1]):
      count +=1
      print(row)
  print(f'{count} valid ISBN')
isbn_10_weight=list(range(10,0,-1))
print(isbn_10_weight)

def ISBN10_check(s):
    vec=[int(i) for i in list(s)]
    return (dot(isbn_10_weight,vec)%11)==0

def ISBN10_check(s):
    x=list(s)
    l=len(x)
    tot=0
    for i in range(l):
        tot=tot+int(x[i])*(l-i)
    return tot%11==0

def dot(vec1,vec2):
    return sum([vec1[i]*vec2[i] for i in range(13)])

isbn_13_weight=[1,3]*6+[1]

def ISBN13_check(s):
    vec=[int(i) for i in list(s)]
    return (dot(isbn_13_weight,vec)%10)==0

with open('ISBN_EXERCISE.txt') as f:
    data=f.readlines()

data=[x.split(':') for x in data]

data=[[x[0].strip(),x[1].strip().replace('-','')] for x in data]

isbn_10_count=0
isbn_13_count=0

for x in data:
    if x[0]=='ISBN-10':
        if len(x[1])==10 and ISBN10_check(x[1]):
            print(f'{x[1]} is a valid {x[0]} number')
            isbn_10_count +=1
        else:
            print(f'This {x[0]} number, {x[1]}, fails the length check or the check digit doesnt match.')
    if x[0]=='ISBN-13':
         if len(x[1])==13 and ISBN13_check(x[1]):
            print(f'{x[1]} is a valid {x[0]} number')
            isbn_13_count +=1
         else:
            print(f'This {x[0]} number, {x[1]}, fails the length check or the check digit doesnt match.')

print(f'There are {isbn_10_count} valid ISBN-10 numbers and {isbn_13_count} for ISBN-13 numbers. Thus, total is {isbn_10_count + isbn_13_count}')
def f(x):
    a=input()
    return 1/x<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13640848544647263, 'fraction_numerical': 0.12197829304390725, 'mean_word_length': 3.343331547937868, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '364599', 'license': 'MIT', 'n_tokens_mistral': 3606, 'n_tokens_neox': 3000, 'n_words': 1099, 'path': 'Exercises/Exercise-9-Program-Testing-and-Data-Validation.ipynb', 'repo_name': 'javkoh/Materials', 'size': '8108'}