From 62ac181ce856d058a0c3850190d2058bfedd7b04 Mon Sep 17 00:00:00 2001 From: mahdavis2024 Date: Fri, 19 Apr 2024 19:20:38 +0330 Subject: [PATCH 01/16] first try this exercise of the book --- # Chapter 4 Try this 1 | 30 ++++++++++++++++++ .../# Chapter 4 Try this 1cpython-312.pyc | Bin 0 -> 422 bytes 2 files changed, 30 insertions(+) create mode 100644 # Chapter 4 Try this 1 create mode 100644 __pycache__/# Chapter 4 Try this 1cpython-312.pyc diff --git a/# Chapter 4 Try this 1 b/# Chapter 4 Try this 1 new file mode 100644 index 0000000..3b44726 --- /dev/null +++ b/# Chapter 4 Try this 1 @@ -0,0 +1,30 @@ +# Chapter 4 Try this 1 +# TRY THIS: VARIABLES AND EXPRESSIONS 1 + +x = 5 +y = 'is' +-y = 7 +4g = 0 +@hh = 100 +print(x) + ll = 2 + +expression = x + y +print(expression) + +test 0 +test1 = 5 + 9 * 4 / 5 +print(test1) +test2 = 5 + (9 * 4) / 5 +print(test2) + +print(3 / 5) +print(3 // 5) + +mm = x = 2 + 4 * 5 – 6 / 3 +mm = x = 2 + 4 * 5 - 6 / 3 +print(mm) + +nn = x = 2 + 4 * (5 - 6) / 3 +print(nn) + diff --git a/__pycache__/# Chapter 4 Try this 1cpython-312.pyc b/__pycache__/# Chapter 4 Try this 1cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1e7d84a5492ec9cc68472c0be26495cc052919d GIT binary patch literal 422 zcmY+9u}i~16vp4X21yOLTbnE0LD&lu=_xs*=_a66bng&R{-)%Mn1b9u%uaqB{dlDYN0UI2& zkpLqMp5*OB2n-nBNV1hQQT`H#*lJo+|J5j?2wAxtWq`J31Je*3RdPmh1|g;e?Ssme zg1BL;nQFV-O2z?{%B_o9qPN47f-Z0%Fc!2IxLza-Hs}Q`3|-$7G-6>?{62OC>2?M2 zyhoTPJr+C1d-aNSRpY09sO^SUaiQ;beW!oT z4uTc=I{A5cDYuz|h%+6i#&N9b96xnHjW>q+)Lg#L-PX7<0m`plAUD$>yUJ-|*>GvB hucbT%ItEQ<#>NQNIpNg_kZCqQf_!2Gkie94z5wvjXLtYr literal 0 HcmV?d00001 From d379ed5713c41315b5247013ca81480e6d3aa8f6 Mon Sep 17 00:00:00 2001 From: mahdavis2024 Date: Mon, 22 Apr 2024 18:42:38 +0330 Subject: [PATCH 02/16] second practice --- ... 4 Try this 1 => # Chapter 4 Try this 1.py | 0 # Chapter 4 Try this 2.py | 50 +++++++++++++++++++ 2 files changed, 50 insertions(+) rename # Chapter 4 Try this 1 => # Chapter 4 Try this 1.py (100%) create mode 100644 # Chapter 4 Try this 2.py diff --git a/# Chapter 4 Try this 1 b/# Chapter 4 Try this 1.py similarity index 100% rename from # Chapter 4 Try this 1 rename to # Chapter 4 Try this 1.py diff --git a/# Chapter 4 Try this 2.py b/# Chapter 4 Try this 2.py new file mode 100644 index 0000000..eb39ca9 --- /dev/null +++ b/# Chapter 4 Try this 2.py @@ -0,0 +1,50 @@ +# Chapter 4 Try this 2 +#TRY THIS: MANIPULATING STRINGS AND NUMBERS + +this_one = 'one' +print (this_one) +That = 'test this' +print(That) +#my-name = "my" +my_name = 'my' +print(my_name) +your_name = "your" +print(your_name) +print(type(your_name)) +together = That + my_name +print(together) +together = That +" "+ my_name +print(together) +#print(your_name - my_name) +print(That*4) +print((That +' ')*3) +#print(my_name *2.5) + + +#testing math and cmath +from math import * +q=5 +w=6 +e=7.2 +print(w*q) +print(q*e) +print(e+w) +y=sqrt(w) +u=pow(q,3) +print(u) +print(y) +print(sin(30)) +r=1-9j +t=2+8j +print(r*t) +from cmath import * +print(w*q) +y=sqrt(w) +print(y) +import math +print(math.sqrt(w)) +print(sqrt(-1)) +print(pow(w,4)) + + + From 1251de0f0f54abbbf715efe93346bc63c5875aca Mon Sep 17 00:00:00 2001 From: mahdavis2024 Date: Tue, 23 Apr 2024 22:23:52 +0330 Subject: [PATCH 03/16] file name changed, practice 3 ch 4 --- # Chapter 4 Try this 1.py => ch4-trythis1.py | 0 # Chapter 4 Try this 2.py => ch4-trythis2.py | 0 ch4-trythis3.py | 17 +++++++++++++++++ 3 files changed, 17 insertions(+) rename # Chapter 4 Try this 1.py => ch4-trythis1.py (100%) rename # Chapter 4 Try this 2.py => ch4-trythis2.py (100%) create mode 100644 ch4-trythis3.py diff --git a/# Chapter 4 Try this 1.py b/ch4-trythis1.py similarity index 100% rename from # Chapter 4 Try this 1.py rename to ch4-trythis1.py diff --git a/# Chapter 4 Try this 2.py b/ch4-trythis2.py similarity index 100% rename from # Chapter 4 Try this 2.py rename to ch4-trythis2.py diff --git a/ch4-trythis3.py b/ch4-trythis3.py new file mode 100644 index 0000000..725a49b --- /dev/null +++ b/ch4-trythis3.py @@ -0,0 +1,17 @@ +# Chapter 4 Try this 3 +# TRY THIS: GETTING INPUT + +city = input('Where do you live? ') +print('Welcome to %s.' %city) +dob = int(input('Which year were you born? ')) +#today = input('What year is it? ') +today = int(input('What year is it? ')) + +age = today - dob +print('You are %s years old.' %age) + +weight = float(input('your weight in kg? ')) +height = float(input('your height in m? ')) + +BMI = weight/height**2 +print('your BMI is: ',BMI) \ No newline at end of file From a550c513691f35c6e2c4cb1d54298b494815b8ea Mon Sep 17 00:00:00 2001 From: mahdavis2024 Date: Wed, 24 Apr 2024 13:30:42 +0330 Subject: [PATCH 04/16] ch4 quick check 1 --- ch4-quickcheck1.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 ch4-quickcheck1.py diff --git a/ch4-quickcheck1.py b/ch4-quickcheck1.py new file mode 100644 index 0000000..1dc213a --- /dev/null +++ b/ch4-quickcheck1.py @@ -0,0 +1,23 @@ +# Chapter 4 Quick check 1 +# QUICK CHECK: PYTHONIC STYLE +''' Which of the following variable and function names do you think are not good Pythonic style? + Why? +bar(), varName, VERYLONGVARNAME, foobar, longvarname, +foo_bar(), really_very_long_var_name ''' + +bar() # good, functions should be all lowercase + +varName # not good, variable names should be all lowercase +varname + +VERYLONGVARNAME # not good, variable names should be all lowercase, underscores_for_readablitiy +very_long_var_name + +foobar # good + +longvarname # not good, variable names should be all lowercase, underscores_for_readablitiy +long_var_name + +foo_bar() # good, functions should be all lowercase, underscores_for_readablitiy + +really_very_long_var_name # good, variable names should be all lowercase, underscores_for_readablitiy \ No newline at end of file From f5c65bb0e7dec9ebc9acdc1e75986103d7096ad3 Mon Sep 17 00:00:00 2001 From: mahdavis2024 Date: Sun, 19 May 2024 18:03:10 +0330 Subject: [PATCH 05/16] all the practices of chapter 5 --- ch5-lab1.py | 37 ++ ch5-quickcheck1.py | 7 + ch5-quickcheck2.py | 27 ++ ch5-quickcheck3.py | 17 + ch5-quickcheck4.py | 9 + ch5-trythis1.py | 10 + ch5-trythis2.py | 8 + ch5-trythis3.py | 14 + ch5-trythis4.py | 26 ++ ch5-trythis5.py | 24 ++ lab_05.txt | 828 +++++++++++++++++++++++++++++++++++++++++++++ 11 files changed, 1007 insertions(+) create mode 100644 ch5-lab1.py create mode 100644 ch5-quickcheck1.py create mode 100644 ch5-quickcheck2.py create mode 100644 ch5-quickcheck3.py create mode 100644 ch5-quickcheck4.py create mode 100644 ch5-trythis1.py create mode 100644 ch5-trythis2.py create mode 100644 ch5-trythis3.py create mode 100644 ch5-trythis4.py create mode 100644 ch5-trythis5.py create mode 100644 lab_05.txt diff --git a/ch5-lab1.py b/ch5-lab1.py new file mode 100644 index 0000000..6506aa5 --- /dev/null +++ b/ch5-lab1.py @@ -0,0 +1,37 @@ +''' +Lab 5: Examining a List +In this lab, the task is to read a set of temperature data (the monthly high temperatures +at Heathrow Airport for 1948 through 2016) from a file and then find some basic information: + the highest and lowest temperatures, the mean (average) temperature, +and the median temperature (the temperature in the middle if all the temperatures are sorted). +The temperature data is in the file lab_05.txt in the source code directory for thischapter. + Because I haven’t yet discussed reading files, here’s the code to read the files into a list: +temperatures = [] +with open('lab_05.txt') as infile: +for row in infile: +temperatures.append(int(row.strip()) +You should find the highest and lowest temperature, the average, and the median. +You’ll probably want to use the min(), max(), sum(), len(), and sort() functions/methods. +Bonus +Determine how many unique temperatures are in the list. +''' +temperatures = [] +with open('lab_05.txt') as infile: + for row in infile: + temperatures.append(float(row.strip())) + +min_temp = min(temperatures) +max_temp = max(temperatures) +mean_temp = round(sum(temperatures)/len(temperatures), 2) +sorting = temperatures[:] +sorting.sort() +middle_index = len(temperatures)//2 +median_temp = sorting[middle_index] + +print('lowest temperatures: ', min_temp) +print('highest temperatures: ', max_temp) +print('mean/average temperatures: ', mean_temp) +print('median/middle temperatures: ', median_temp) +print('number of all temperatures: ', len(temperatures) ) +unique = set(temperatures) +print('number of unique temperatures: ', len(unique)) diff --git a/ch5-quickcheck1.py b/ch5-quickcheck1.py new file mode 100644 index 0000000..b273f27 --- /dev/null +++ b/ch5-quickcheck1.py @@ -0,0 +1,7 @@ +''' +Quick Check: len() +What would len() return for each of the following: [0]; []; [[1, 3, [4, 5], 6], 7]? +''' +print(len([0])) +print(len([])) +print(len([[1, 3, [4, 5], 6], 7])) diff --git a/ch5-quickcheck2.py b/ch5-quickcheck2.py new file mode 100644 index 0000000..e30f219 --- /dev/null +++ b/ch5-quickcheck2.py @@ -0,0 +1,27 @@ +''' +Quick Check: List Operations +What would be the result of len([[1,2]] * 3)? +What are two differences between using the in operator and a list’s index() method? +Which of the following will raise an exception?: min(["a", "b", "c"]); max([1, 2, "three"]); [1, 2, 3].count("one") +''' + +x = [[1,2]] * 3 +print(x) +print(len(x)) + +y = [9, 8, 7, 0, 1, 7] +print(2 in y) #returns only boolean, no more information of the position +print(8 in y) +print(y.index(7)) #returns the position of only the first occurance +#print(y.index(2)) #returns Traceback ValueError: 2 is not in list + + +print(min(["a", "b", "c"])) + +#print(max([1, 2, "three"])) #TypeError: '>' not supported between instances of 'str' and 'int' + +print([1, 2, 3].count("one")) + + + + diff --git a/ch5-quickcheck3.py b/ch5-quickcheck3.py new file mode 100644 index 0000000..5ea60f8 --- /dev/null +++ b/ch5-quickcheck3.py @@ -0,0 +1,17 @@ +''' +Quick Check: Tuples +Explain why the following operations aren’t legal for the tuple x = (1, 2, 3, 4): +x.append(1) +x[1] = "hello" +del x[2] +If you had a tuple x = (3, 1, 4, 2), how might you end up with x sorted? +''' + +x = (1, 2, 3, 4) +x.append(1) #Traceback AttributeError: 'tuple' object has no attribute 'append' +x[1] = "hello" #Traceback TypeError: 'tuple' object does not support item assignment +del x[2] #Traceback TypeError: 'tuple' object doesn't support item deletion + +y = (3, 1, 4, 2) +print(sorted(y)) #[1, 2, 3, 4] +print(type(sorted(y))) # turns the tuple to list then sorts diff --git a/ch5-quickcheck4.py b/ch5-quickcheck4.py new file mode 100644 index 0000000..049ebce --- /dev/null +++ b/ch5-quickcheck4.py @@ -0,0 +1,9 @@ +''' +Quick Check: Sets +If you were to construct a set from the following list, how many elements would the set +have?: [1, 2, 5, 1, 0, 2, 3, 1, 1, (1, 2, 3)] +''' + +x = set([1, 2, 5, 1, 0, 2, 3, 1, 1, (1, 2, 3)]) +print(x) +print(len(x)) \ No newline at end of file diff --git a/ch5-trythis1.py b/ch5-trythis1.py new file mode 100644 index 0000000..2c25642 --- /dev/null +++ b/ch5-trythis1.py @@ -0,0 +1,10 @@ +''' +Try this: List slices and indexes +Using what you know about the len() function and list slices, how would you combine +the two to get the second half of a list when you don’t know what size it is? +Experiment in the Python shell to confirm that your solution works. +''' + +x = [00, 11, 22, 33, 44, 55, 66, 77, 88] +y = x[len(x)//2:] +print(y) \ No newline at end of file diff --git a/ch5-trythis2.py b/ch5-trythis2.py new file mode 100644 index 0000000..6b67fb7 --- /dev/null +++ b/ch5-trythis2.py @@ -0,0 +1,8 @@ +''' +Try this: Modifying lists +Suppose that you have a list 10 items long. How might you move the last three items +from the end of the list to the beginning, keeping them in the same order? +''' + +x = [00, 11, 22, 33, 44, 55, 66, 77, 88, 99] +print(x[-3:] + x[:-3]) \ No newline at end of file diff --git a/ch5-trythis3.py b/ch5-trythis3.py new file mode 100644 index 0000000..8a736e7 --- /dev/null +++ b/ch5-trythis3.py @@ -0,0 +1,14 @@ +''' +Try this: Sorting lists +Suppose that you have a list in which each element is in turn a list: [[1, 2, 3], [2, 1, 3], [4, 0, 1]]. +If you wanted to sort this list by the second element in each list +so that the result would be [[4, 0, 1], [2, 1, 3], [1, 2, 3]], what function +would you write to pass as the key value to the sort() method? +''' + +def second_item(in_list): + return in_list[1] + +x = [[1, 2, 3], [2, 1, 3], [4, 0, 1]] +x.sort(key = second_item) +print(x) \ No newline at end of file diff --git a/ch5-trythis4.py b/ch5-trythis4.py new file mode 100644 index 0000000..23053c7 --- /dev/null +++ b/ch5-trythis4.py @@ -0,0 +1,26 @@ +''' +Try this: List operations +If you have a list x, write the code to safely remove an item if—and only if—that value is in the list. +Modify that code to remove the element only if the item occurs in the list more than once. +''' + +def remove_if_is(x, item): + if item in x: + x.remove(item) + return x + else: + return 'item not in the list' + +def remove_first_one(x, item): + if x.count(item) > 1: + x.remove(item) + return x + else: + return 'item less then twice in list' + +y = [0, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4] + +print(remove_if_is(y, 0)) +print(remove_if_is(y, 7)) +print(remove_first_one(y, 2)) +print(remove_first_one(y, 6)) diff --git a/ch5-trythis5.py b/ch5-trythis5.py new file mode 100644 index 0000000..3f762bb --- /dev/null +++ b/ch5-trythis5.py @@ -0,0 +1,24 @@ +''' +Try this: List copies +Suppose that you have the following list: x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +What code could you use to get a copy y of that list in which you could change the +elements without the side effect of changing the contents of x? +''' +x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + + +shallow = x[:] +print('shallow ', shallow) + +import copy +deep = copy.deepcopy(x) + +print('deep ', deep) + +del deep[1][1] +print('deep after del ', deep) +print('x after deep del ', x) + +del shallow[2][2] +print('shallow after del ', shallow) +print('x after shallow del ', x) \ No newline at end of file diff --git a/lab_05.txt b/lab_05.txt new file mode 100644 index 0000000..d8530bb --- /dev/null +++ b/lab_05.txt @@ -0,0 +1,828 @@ +8.9 +7.9 +14.2 +15.4 +18.1 +19.1 +21.7 +20.8 +19.6 +14.9 +10.8 +8.8 +8.5 +10.4 +9.3 +16.2 +17.1 +22.0 +25.1 +23.9 +22.8 +17.0 +10.2 +9.2 +7.1 +9.9 +12.3 +12.9 +17.2 +23.6 +21.6 +21.9 +17.6 +14.0 +9.3 +3.8 +7.3 +7.0 +8.4 +12.3 +15.0 +20.5 +23.0 +20.2 +19.2 +14.6 +11.8 +8.9 +6.2 +6.7 +10.6 +15.6 +19.6 +20.9 +23.3 +21.6 +16.4 +13.2 +7.5 +5.8 +5.6 +7.5 +11.1 +13.1 +18.7 +19.8 +21.0 +22.6 +19.5 +14.7 +11.3 +10.0 +5.9 +6.1 +10.4 +13.2 +16.8 +18.6 +19.2 +19.8 +18.0 +16.2 +11.2 +9.7 +5.6 +5.0 +7.9 +15.2 +15.5 +20.0 +24.4 +24.3 +19.9 +13.5 +10.7 +9.5 +7.0 +2.9 +11.0 +12.1 +19.1 +18.5 +20.9 +18.8 +19.2 +13.8 +9.3 +8.2 +8.7 +9.0 +13.9 +14.2 +16.2 +23.6 +22.5 +21.1 +17.6 +15.5 +9.4 +7.6 +6.8 +8.9 +8.1 +12.3 +17.3 +19.4 +21.7 +20.8 +20.0 +14.9 +9.7 +8.0 +5.7 +7.4 +11.9 +14.2 +18.7 +22.1 +24.7 +24.2 +22.7 +17.8 +10.8 +9.3 +6.9 +7.9 +10.2 +14.3 +18.4 +22.1 +20.1 +20.3 +18.5 +14.2 +11.2 +6.9 +6.9 +10.3 +13.9 +15.0 +16.8 +21.7 +22.1 +21.7 +20.9 +15.6 +9.9 +6.8 +7.9 +7.6 +7.4 +12.7 +15.0 +20.4 +20.6 +20.0 +17.8 +15.7 +9.1 +5.0 +0.8 +2.8 +10.7 +13.6 +16.0 +20.8 +21.1 +19.8 +18.0 +14.8 +11.8 +5.4 +5.8 +7.6 +7.6 +12.8 +19.6 +19.3 +22.8 +22.3 +21.1 +13.7 +11.2 +7.1 +6.6 +5.9 +10.5 +13.4 +16.8 +19.7 +19.3 +20.8 +17.4 +16.2 +8.4 +8.4 +5.3 +9.3 +10.9 +12.2 +17.0 +21.8 +20.1 +20.6 +19.6 +14.7 +8.8 +9.3 +7.3 +9.3 +11.6 +12.5 +15.6 +20.1 +23.5 +21.5 +18.5 +15.0 +9.7 +7.2 +7.2 +5.7 +11.1 +13.7 +15.4 +20.6 +20.7 +20.2 +18.8 +16.5 +9.5 +5.4 +8.9 +4.9 +8.0 +13.6 +17.1 +20.6 +23.9 +21.8 +19.6 +18.2 +9.6 +6.1 +7.1 +7.2 +8.1 +11.4 +19.2 +23.6 +21.3 +22.3 +20.3 +15.7 +11.9 +7.0 +7.8 +8.6 +9.1 +12.2 +18.1 +17.8 +24.1 +21.3 +20.7 +17.2 +10.4 +9.3 +6.9 +7.9 +12.4 +12.9 +16.0 +17.5 +22.3 +21.8 +17.3 +15.6 +9.9 +9.4 +7.3 +8.1 +11.5 +12.5 +16.9 +21.9 +21.4 +23.7 +20.7 +13.9 +10.3 +8.6 +9.6 +9.2 +10.3 +14.0 +17.0 +20.1 +20.9 +21.5 +17.5 +11.0 +10.6 +11.0 +10.3 +9.3 +8.4 +13.3 +15.1 +21.8 +24.1 +25.9 +19.5 +14.4 +10.1 +7.6 +8.8 +7.8 +9.5 +13.7 +19.3 +25.5 +26.6 +25.1 +19.0 +14.9 +9.9 +5.6 +6.1 +9.6 +11.2 +12.2 +16.4 +17.4 +22.4 +20.3 +18.0 +16.3 +10.4 +9.2 +6.7 +6.2 +11.3 +10.7 +17.2 +19.7 +20.5 +20.7 +20.1 +17.1 +12.6 +7.8 +3.8 +4.5 +9.2 +12.7 +15.9 +19.0 +22.5 +21.0 +19.6 +16.4 +10.8 +9.2 +6.0 +9.9 +9.0 +14.0 +17.3 +19.8 +19.7 +21.9 +20.1 +14.0 +9.3 +8.9 +8.1 +7.1 +11.8 +12.9 +16.1 +18.5 +22.0 +22.8 +20.3 +12.9 +11.5 +4.4 +6.9 +8.4 +11.1 +14.3 +18.0 +21.5 +22.7 +22.2 +20.8 +14.1 +11.4 +8.2 +10.0 +5.5 +10.8 +12.4 +15.6 +20.8 +27.6 +24.5 +19.3 +15.1 +11.3 +9.2 +8.0 +7.4 +8.9 +14.6 +14.9 +21.3 +24.2 +24.4 +18.6 +15.8 +12.2 +8.7 +4.1 +6.3 +9.4 +14.0 +16.4 +18.5 +22.9 +20.3 +20.6 +16.1 +8.1 +10.0 +7.2 +1.7 +10.1 +10.9 +16.3 +21.8 +22.6 +20.0 +17.4 +16.4 +12.1 +9.7 +3.6 +7.7 +8.5 +15.8 +16.3 +18.6 +21.8 +21.8 +19.3 +15.0 +9.8 +8.9 +8.8 +8.7 +10.7 +13.5 +18.0 +19.7 +20.0 +21.8 +18.8 +15.5 +9.9 +10.4 +9.5 +10.2 +12.9 +11.5 +21.0 +22.1 +25.8 +24.2 +20.7 +17.1 +10.9 +9.4 +10.2 +11.7 +13.6 +14.6 +20.5 +19.5 +24.7 +26.0 +19.7 +16.9 +10.7 +7.6 +7.3 +5.4 +12.5 +13.1 +15.7 +17.8 +23.2 +24.1 +21.4 +14.6 +10.6 +8.3 +7.5 +9.5 +11.8 +14.0 +21.0 +22.5 +22.5 +21.7 +18.9 +12.5 +12.0 +7.8 +10.3 +7.2 +11.8 +14.6 +18.0 +21.8 +21.6 +21.6 +17.5 +13.0 +8.8 +9.2 +9.3 +7.7 +12.3 +13.3 +16.0 +21.5 +26.2 +23.0 +17.8 +15.4 +13.6 +10.7 +8.9 +10.7 +11.2 +15.0 +19.0 +20.7 +26.3 +27.0 +19.2 +18.3 +12.0 +5.8 +7.2 +6.8 +8.6 +14.3 +15.1 +22.8 +24.2 +23.1 +19.2 +16.6 +10.5 +6.2 +5.5 +10.8 +13.8 +15.6 +18.7 +20.2 +23.5 +25.8 +20.9 +15.9 +12.5 +9.5 +9.2 +11.6 +12.1 +12.7 +19.6 +19.9 +21.4 +23.5 +20.4 +14.7 +9.6 +9.7 +9.4 +8.8 +12.2 +14.9 +19.1 +20.3 +24.9 +22.8 +21.3 +15.6 +11.3 +8.7 +8.6 +10.4 +12.1 +12.9 +18.0 +21.0 +21.0 +23.2 +20.1 +14.7 +11.0 +9.0 +7.1 +9.2 +9.5 +12.8 +18.8 +20.8 +24.3 +23.5 +18.1 +17.6 +11.3 +7.3 +9.5 +11.3 +12.4 +15.7 +17.3 +20.1 +22.3 +23.3 +20.3 +15.3 +12.4 +9.0 +8.0 +8.4 +13.6 +15.7 +18.2 +23.3 +24.2 +26.4 +21.9 +14.5 +12.6 +8.8 +8.8 +8.7 +10.8 +14.9 +18.2 +22.1 +22.7 +23.8 +20.8 +15.3 +11.2 +8.8 +9.5 +7.3 +11.5 +14.6 +17.7 +22.8 +23.3 +23.2 +21.4 +17.8 +10.7 +8.2 +7.6 +7.2 +9.4 +14.1 +18.0 +23.7 +28.2 +22.2 +22.7 +17.8 +12.7 +9.7 +10.5 +9.9 +12.5 +18.9 +17.9 +21.2 +21.4 +21.5 +19.9 +15.4 +11.4 +8.9 +10.4 +11.0 +10.6 +13.7 +19.8 +20.8 +22.8 +21.5 +18.5 +15.0 +10.7 +7.3 +6.8 +7.8 +12.9 +16.1 +19.1 +22.4 +23.0 +23.9 +20.5 +16.3 +12.6 +7.0 +4.5 +6.9 +11.1 +15.8 +17.3 +23.5 +25.0 +21.6 +19.4 +15.2 +9.1 +3.9 +7.4 +10.2 +12.3 +19.7 +19.4 +20.7 +21.7 +21.8 +21.3 +18.1 +13.6 +9.9 +9.8 +8.0 +14.7 +13.3 +18.2 +19.4 +21.3 +23.5 +20.0 +14.2 +11.0 +9.0 +6.5 +6.7 +6.9 +13.5 +16.4 +20.3 +27.0 +24.3 +19.7 +17.0 +10.4 +10.2 +10.0 +10.6 +14.1 +16.1 +18.0 +22.1 +25.8 +21.7 +21.5 +17.6 +12.5 +9.2 +8.8 +8.0 +11.6 +16.3 +17.6 +22.2 +23.7 +22.2 +18.6 +15.8 +13.4 +13.7 +9.5 +9.4 +10.7 +13.5 +19.0 +20.7 +24.0 +24.7 +22.4 +15.9 +10.5 +10.2 From d6d663e0c264509d59f1a131650c540f6e6353aa Mon Sep 17 00:00:00 2001 From: mahdavis2024 Date: Fri, 24 May 2024 22:18:12 +0330 Subject: [PATCH 06/16] all exercises in chapter 6 --- ch5-lab1.py => ch5-lab5.py | 0 ch6-lab6.py | 36 +++++ ch6-quickcheck1.py | 11 ++ ch6-quickcheck2.py | 12 ++ ch6-quickcheck3.py | 15 ++ ch6-quickcheck4.py | 10 ++ ch6-quickcheck5.py | 10 ++ ch6-quickcheck6.py | 23 ++++ ch6-quickcheck7.py | 13 ++ ch6-quickcheck8.py | 15 ++ ch6-trythis1.py | 26 ++++ ch7-trythis2.py | 0 ch7-trythis3.py | 0 ch7-trythis4.py | 0 ch7-trythis5.py | 0 moby_01.txt | 26 ++++ moby_01_clean.txt | 272 +++++++++++++++++++++++++++++++++++++ 17 files changed, 469 insertions(+) rename ch5-lab1.py => ch5-lab5.py (100%) create mode 100644 ch6-lab6.py create mode 100644 ch6-quickcheck1.py create mode 100644 ch6-quickcheck2.py create mode 100644 ch6-quickcheck3.py create mode 100644 ch6-quickcheck4.py create mode 100644 ch6-quickcheck5.py create mode 100644 ch6-quickcheck6.py create mode 100644 ch6-quickcheck7.py create mode 100644 ch6-quickcheck8.py create mode 100644 ch6-trythis1.py create mode 100644 ch7-trythis2.py create mode 100644 ch7-trythis3.py create mode 100644 ch7-trythis4.py create mode 100644 ch7-trythis5.py create mode 100644 moby_01.txt create mode 100644 moby_01_clean.txt diff --git a/ch5-lab1.py b/ch5-lab5.py similarity index 100% rename from ch5-lab1.py rename to ch5-lab5.py diff --git a/ch6-lab6.py b/ch6-lab6.py new file mode 100644 index 0000000..ecb6f87 --- /dev/null +++ b/ch6-lab6.py @@ -0,0 +1,36 @@ +''' +Lab 6: Preprocessing Text +In processing raw text, it’s quite often necessary to clean and normalize the text before doing anything else. +If you want to find the frequency of words in text, for example, you can make the job easier if, +before you start counting, you make sure that everything is lowercase (or uppercase, if you prefer) +and that all punctuation has been removed. You can also make things easier by breaking the text into a series of words. +In this lab, the task is to read the first part of the first chapter of Moby Dick (found in the book’s source code), +make sure that everything is one case, remove all punctuation, and write the words one per line to a second file. +Because I haven’t yet covered reading and writing files, here’s the code for those operations: +with open("moby_01.txt") as infile, open("moby_01_clean.txt", "w") as outfile: +for line in infile: +# make all one case +# remove punctuation +# split into words +# write all words for line +outfile.write(cleaned_words) +''' +with open("moby_01.txt") as infile, open("moby_01_clean.txt", "w") as outfile: + words_list = [] + for line in infile: +# make all one case + lower_case = line.lower() +# remove punctuation + table = lower_case.maketrans('.,?;:!"-_][)(\'',' '*14) + sans_punct = lower_case.translate(table) +# split into words + line_list = sans_punct.split() +# write all words for line + words_list = words_list + line_list + cleaned_words = '\n'.join(words_list) + outfile.write(cleaned_words) + +# see the outfile +with open('moby_01_clean.txt','r') as outfile: + for each in outfile: + print(each) \ No newline at end of file diff --git a/ch6-quickcheck1.py b/ch6-quickcheck1.py new file mode 100644 index 0000000..1ddd40e --- /dev/null +++ b/ch6-quickcheck1.py @@ -0,0 +1,11 @@ +''' +Quick Check: split and join +How could you use split and join to change all the whitespace in string x to dashes, +such as changing "this is a test" to "this—is—a—test""? +''' +x = "this is a test" + +x = '—'.join(x.split()) + +print(x) + diff --git a/ch6-quickcheck2.py b/ch6-quickcheck2.py new file mode 100644 index 0000000..319ad63 --- /dev/null +++ b/ch6-quickcheck2.py @@ -0,0 +1,12 @@ +''' +Quick Check: Strings to Numbers +Which of the following will not be converted to numbers, and why? +int('a1') +int('12G', 16) +float("12345678901234567890") +int("12*2") +''' +#int('a1') ValueError: invalid literal for int() with base 10: 'a1' +#int('12G', 16) ValueError: invalid literal for int() with base 16: '12G' +float("12345678901234567890") +#int("12*2") ValueError: invalid literal for int() with base 10: '12*2' \ No newline at end of file diff --git a/ch6-quickcheck3.py b/ch6-quickcheck3.py new file mode 100644 index 0000000..e92d8a7 --- /dev/null +++ b/ch6-quickcheck3.py @@ -0,0 +1,15 @@ +''' +Quick Check: strip +If the string x equals "(name, date),\n", which of the following would return a +string containing "name, date"? +x.rstrip("),") +x.strip("),\n") +x.strip("\n)(,") +''' + +x = "(name, date),\n" + + +print(x.rstrip("),")) # (name, date), +print(x.strip("),\n")) # (name, date +print(x.strip("\n)(,")) # name, date #correct diff --git a/ch6-quickcheck4.py b/ch6-quickcheck4.py new file mode 100644 index 0000000..0197bca --- /dev/null +++ b/ch6-quickcheck4.py @@ -0,0 +1,10 @@ +''' +Quick Check: String searching +If you wanted to check whether a line ends with the string "rejected", +what string method would you use? +Would there be any other ways to get the same result? +''' + +line.endswith("rejected") + +line[-8:] == "rejected" \ No newline at end of file diff --git a/ch6-quickcheck5.py b/ch6-quickcheck5.py new file mode 100644 index 0000000..118142b --- /dev/null +++ b/ch6-quickcheck5.py @@ -0,0 +1,10 @@ +''' +Quick Check: Modifying strings +What would be a quick way to change all punctuation in a string to spaces? +''' +x = 'q,w.e:r;t"y-u?i!o_p[a]s)d(f\'g' + +table = x.maketrans('.,?;:!"-_][)(\'',' '*14) +y = x.translate(table) + +print(y) \ No newline at end of file diff --git a/ch6-quickcheck6.py b/ch6-quickcheck6.py new file mode 100644 index 0000000..3973a55 --- /dev/null +++ b/ch6-quickcheck6.py @@ -0,0 +1,23 @@ +''' +Quick Check: the format() method +What will be in x when the following snippets of code are executed?: +x = "{1:{0}}".format(3, 4) +x = "{0:$>5}".format(3) +x = "{a:{b}}".format(a=1, b=5) +x = "{a:{b}}:{0:$>5}".format(3, 4, a=1, b=5, c=10) +''' +x = "{1:{0}}".format(3, 4) +print(x) +x = "{0:$>5}".format(3) +print(x) +x = "{a:{b}}".format(a=1, b=5) +print(x) +x = "{a:{b}}:{0:$>5}".format(3, 4, a=1, b=5, c=10) +print(x) + +''' + 4 +$$$$3 + 1 + 1:3$$$$ +''' \ No newline at end of file diff --git a/ch6-quickcheck7.py b/ch6-quickcheck7.py new file mode 100644 index 0000000..8eca295 --- /dev/null +++ b/ch6-quickcheck7.py @@ -0,0 +1,13 @@ +''' +Quick Check: Formatting strings with % +What would be in the variable x after the following snippets of code have executed? +x = "%.2f" % 1.1111 +x = "%(a).2f" % {'a':1.1111} +x = "%(a).08f" % {'a':1.1111} +''' +x = "%.2f" % 1.1111 +print(x) # 1.11 +x = "%(a).2f" % {'a':1.1111} +print(x) # 1.11 +x = "%(a).08f" % {'a':1.1111} +print(x) # 1.11110000 \ No newline at end of file diff --git a/ch6-quickcheck8.py b/ch6-quickcheck8.py new file mode 100644 index 0000000..82dfcea --- /dev/null +++ b/ch6-quickcheck8.py @@ -0,0 +1,15 @@ +''' +Quick Check: Bytes +For which of the following kinds of data would you want to use a string? +For which could you use bytes? +1 Data file storing binary data +2 Text in a language with accented characters +3 Text with only uppercase and lowercase roman characters +4 A series of integers no larger than 255 +''' + + +1 Data file storing binary data # bytes, binary numbers +2 Text in a language with accented characters # string, unicode covers accent +3 Text with only uppercase and lowercase roman characters # string, text +4 A series of integers no larger than 255 # bytes, integers in range \ No newline at end of file diff --git a/ch6-trythis1.py b/ch6-trythis1.py new file mode 100644 index 0000000..9c0ae35 --- /dev/null +++ b/ch6-trythis1.py @@ -0,0 +1,26 @@ +''' +Try this: String operations +Suppose that you have a list of strings in which some (but not necessarily all) + of the strings begin and end with the double quote character: +x = ['"abc"', 'def', '"ghi"', '"klm"', 'nop'] +What code would you use on each element to remove just the double quotes? +What code could you use to find the position of the last p in Mississippi? +When you’ve found that position, what code would you use to remove just that letter? +''' +x = ['"abc"', 'def', '"ghi"', '"klm"', 'nop'] + +y = [] +for i in x: + n = i.strip('"') + y.append(n) +x = y +print(x) + +##################### +m = "Mississippi" +n = [] +for i in m: + n.append(i) +del(n[m.rfind("p")]) +l =''.join(n) +print(l) diff --git a/ch7-trythis2.py b/ch7-trythis2.py new file mode 100644 index 0000000..e69de29 diff --git a/ch7-trythis3.py b/ch7-trythis3.py new file mode 100644 index 0000000..e69de29 diff --git a/ch7-trythis4.py b/ch7-trythis4.py new file mode 100644 index 0000000..e69de29 diff --git a/ch7-trythis5.py b/ch7-trythis5.py new file mode 100644 index 0000000..e69de29 diff --git a/moby_01.txt b/moby_01.txt new file mode 100644 index 0000000..bcfbd95 --- /dev/null +++ b/moby_01.txt @@ -0,0 +1,26 @@ +Call me Ishmael. Some years ago--never mind how long precisely-- +having little or no money in my purse, and nothing particular +to interest me on shore, I thought I would sail about a little +and see the watery part of the world. It is a way I have +of driving off the spleen and regulating the circulation. +Whenever I find myself growing grim about the mouth; +whenever it is a damp, drizzly November in my soul; whenever I +find myself involuntarily pausing before coffin warehouses, +and bringing up the rear of every funeral I meet; +and especially whenever my hypos get such an upper hand of me, +that it requires a strong moral principle to prevent me from +deliberately stepping into the street, and methodically knocking +people's hats off--then, I account it high time to get to sea +as soon as I can. This is my substitute for pistol and ball. +With a philosophical flourish Cato throws himself upon his sword; +I quietly take to the ship. There is nothing surprising in this. +If they but knew it, almost all men in their degree, some time +or other, cherish very nearly the same feelings towards +the ocean with me. + +There now is your insular city of the Manhattoes, belted round by wharves +as Indian isles by coral reefs--commerce surrounds it with her surf. +Right and left, the streets take you waterward. Its extreme downtown +is the battery, where that noble mole is washed by waves, and cooled +by breezes, which a few hours previous were out of sight of land. +Look at the crowds of water-gazers there. diff --git a/moby_01_clean.txt b/moby_01_clean.txt new file mode 100644 index 0000000..d08880c --- /dev/null +++ b/moby_01_clean.txt @@ -0,0 +1,272 @@ +call +me +ishmael +some +years +ago +never +mind +how +long +precisely +having +little +or +no +money +in +my +purse +and +nothing +particular +to +interest +me +on +shore +i +thought +i +would +sail +about +a +little +and +see +the +watery +part +of +the +world +it +is +a +way +i +have +of +driving +off +the +spleen +and +regulating +the +circulation +whenever +i +find +myself +growing +grim +about +the +mouth +whenever +it +is +a +damp +drizzly +november +in +my +soul +whenever +i +find +myself +involuntarily +pausing +before +coffin +warehouses +and +bringing +up +the +rear +of +every +funeral +i +meet +and +especially +whenever +my +hypos +get +such +an +upper +hand +of +me +that +it +requires +a +strong +moral +principle +to +prevent +me +from +deliberately +stepping +into +the +street +and +methodically +knocking +people +s +hats +off +then +i +account +it +high +time +to +get +to +sea +as +soon +as +i +can +this +is +my +substitute +for +pistol +and +ball +with +a +philosophical +flourish +cato +throws +himself +upon +his +sword +i +quietly +take +to +the +ship +there +is +nothing +surprising +in +this +if +they +but +knew +it +almost +all +men +in +their +degree +some +time +or +other +cherish +very +nearly +the +same +feelings +towards +the +ocean +with +me +there +now +is +your +insular +city +of +the +manhattoes +belted +round +by +wharves +as +indian +isles +by +coral +reefs +commerce +surrounds +it +with +her +surf +right +and +left +the +streets +take +you +waterward +its +extreme +downtown +is +the +battery +where +that +noble +mole +is +washed +by +waves +and +cooled +by +breezes +which +a +few +hours +previous +were +out +of +sight +of +land +look +at +the +crowds +of +water +gazers +there \ No newline at end of file From 36ecbb342e7f2c16d199d8fe36a27e82a521fae5 Mon Sep 17 00:00:00 2001 From: mahdavis2024 Date: Wed, 29 May 2024 09:56:20 +0330 Subject: [PATCH 07/16] chapter 7 exercises --- ch6-lab6.py | 2 +- ch7-lab7.py | 30 ++++++++++++++++++++++++++++++ ch7-quickcheck1.py | 16 ++++++++++++++++ ch7-quickcheck2.py | 12 ++++++++++++ ch7-trythis1.py | 18 ++++++++++++++++++ ch7-trythis2.py | 14 ++++++++++++++ ch7-trythis3.py | 0 ch7-trythis5.py | 0 8 files changed, 91 insertions(+), 1 deletion(-) create mode 100644 ch7-lab7.py create mode 100644 ch7-quickcheck1.py create mode 100644 ch7-quickcheck2.py create mode 100644 ch7-trythis1.py delete mode 100644 ch7-trythis3.py delete mode 100644 ch7-trythis5.py diff --git a/ch6-lab6.py b/ch6-lab6.py index ecb6f87..8fac075 100644 --- a/ch6-lab6.py +++ b/ch6-lab6.py @@ -33,4 +33,4 @@ # see the outfile with open('moby_01_clean.txt','r') as outfile: for each in outfile: - print(each) \ No newline at end of file + print(each, end = "") \ No newline at end of file diff --git a/ch7-lab7.py b/ch7-lab7.py new file mode 100644 index 0000000..b135510 --- /dev/null +++ b/ch7-lab7.py @@ -0,0 +1,30 @@ +''' +Lab 7: Word Counting +In the previous lab, you took the text of the first chapter of Moby Dick, normalized the case, +removed punctuation, and wrote the separated words to a file. +In this lab, you read that file, use a dictionary to count the number of times each word occurs, +and then report the most common and least common words. +''' + +with open("moby_01_clean.txt") as infile: + word_count = {} + for word in infile: + word_count[word] = word_count.get(word, 0) + 1 + +maxi = max(list(word_count.values())) +mini = min(list(word_count.values())) + +most_common = [] +least_common = [] + +for key in list(word_count.keys()): + if word_count[key] >= maxi - 7: + most_common.append(key.strip("\n")) + + if word_count[key] == mini: + least_common.append(key.strip("\n")) + + +print('''In the first chapter of Moby Dick\nThe most common words are {0} with {1} to {2} times of occorance.\n + The least common words are {3} with only {4} times of occurance.'''.format( + most_common, maxi - 7 , maxi , least_common, mini )) diff --git a/ch7-quickcheck1.py b/ch7-quickcheck1.py new file mode 100644 index 0000000..6386863 --- /dev/null +++ b/ch7-quickcheck1.py @@ -0,0 +1,16 @@ +''' +Quick Check: Dictionary operations +Assume that you have a dictionary x = {'a':1, 'b':2, 'c':3, 'd':4} and a +dictionary y = {'a':6, 'e':5, 'f':6}. +What would be the contents of x after the following snippets of code have executed?: +del x['d'] +z = x.setdefault('g', 7) +x.update(y) +''' +x = {'a':1, 'b':2, 'c':3, 'd':4} +y = {'a':6, 'e':5, 'f':6} + +del x['d'] # {'a': 1, 'b': 2, 'c': 3} +z = x.setdefault('g', 7) # {'a': 1, 'b': 2, 'c': 3, 'g': 7} +x.update(y) +print(x) # {'a': 6, 'b': 2, 'c': 3, 'g': 7, 'e': 5, 'f': 6} \ No newline at end of file diff --git a/ch7-quickcheck2.py b/ch7-quickcheck2.py new file mode 100644 index 0000000..c7ecc74 --- /dev/null +++ b/ch7-quickcheck2.py @@ -0,0 +1,12 @@ +''' +Quick Check: What can be a key? +Decide which of the following expressions can be a dictionary key: + 1; 'bob'; ('tom', [1, 2, 3]); ["filename"]; "filename"; ("filename", "extension") +''' + +1; #can, number: immutable, hashable +'bob'; #can, string: immutable, hashable +('tom', [1, 2, 3]); #cannot, list item in a tuple: mutable +["filename"]; #cannot, list: mutable +"filename"; #can, string: immutable, hashable +("filename", "extension") #can, tuple with string items \ No newline at end of file diff --git a/ch7-trythis1.py b/ch7-trythis1.py new file mode 100644 index 0000000..4301fe3 --- /dev/null +++ b/ch7-trythis1.py @@ -0,0 +1,18 @@ +''' +Try this: Create a dictionary +Write the code to ask the user for three names and three ages. After the names and ages +are entered, ask the user for one of the names, and print the correct age. +''' + +nameage_dict = {} +for i in range(0,3): + name = str(input("Enter your name: ")) + age = int(input("Enter your age: ")) + nameage_dict[name] = age + +who = input("Whose age do you want? ") + +if who in nameage_dict: + print("{}'s age is: ".format(who)) +else: + print("Sorry, there is no {} in the records".format(who)) diff --git a/ch7-trythis2.py b/ch7-trythis2.py index e69de29..51c868f 100644 --- a/ch7-trythis2.py +++ b/ch7-trythis2.py @@ -0,0 +1,14 @@ +''' +Try this: Using dictionaries +Suppose that you’re writing a program that works like a spreadsheet. +How might you use a dictionary to store the contents of a sheet? +Write some sample code to both store a value and retrieve a value in a particular cell. +What might be some drawbacks to this approach? +''' + +spreadsheet = {} + +x = input('enter x index of cell: ') +y = input('enter x index of cell: ') + +cell_content = spreadsheet.get((x, y), input('enter content for this cell: ')) diff --git a/ch7-trythis3.py b/ch7-trythis3.py deleted file mode 100644 index e69de29..0000000 diff --git a/ch7-trythis5.py b/ch7-trythis5.py deleted file mode 100644 index e69de29..0000000 From 897bf0ca766730f3cfc5c95cd55d7361c9a831fb Mon Sep 17 00:00:00 2001 From: mahdavis2024 Date: Thu, 30 May 2024 20:07:36 +0330 Subject: [PATCH 08/16] chapter 8 exercises --- ch7-trythis4.py | 0 ch8-lab8.py | 20 ++++++++++++++++++++ ch8-quickcheck1.py | 13 +++++++++++++ ch8-trythis1.py | 45 +++++++++++++++++++++++++++++++++++++++++++++ ch8-trythis2.py | 21 +++++++++++++++++++++ word_count.txt | 4 ++++ 6 files changed, 103 insertions(+) delete mode 100644 ch7-trythis4.py create mode 100644 ch8-lab8.py create mode 100644 ch8-quickcheck1.py create mode 100644 ch8-trythis1.py create mode 100644 ch8-trythis2.py create mode 100644 word_count.txt diff --git a/ch7-trythis4.py b/ch7-trythis4.py deleted file mode 100644 index e69de29..0000000 diff --git a/ch8-lab8.py b/ch8-lab8.py new file mode 100644 index 0000000..4bc63d1 --- /dev/null +++ b/ch8-lab8.py @@ -0,0 +1,20 @@ +''' +Lab 8: Refactor word_count +Rewrite the word_count program from section 8.7 to make it shorter. +You may want to look at the string and list operations already discussed, as well as think about different +ways to organize the code. You may also want to make the program smarter so that only +alphabetic strings (not symbols or punctuation) count as words. +''' + +line_count = 0 +word_count = 0 +char_count = 0 + +with open('word_count.txt') as infile: + for line in infile: + line_count += 1 + char_count += len(line) + words = line.split() + word_count += len(words) + +print("File has {0} lines, {1} words, {2} characters".format(line_count, word_count, char_count)) \ No newline at end of file diff --git a/ch8-quickcheck1.py b/ch8-quickcheck1.py new file mode 100644 index 0000000..265a410 --- /dev/null +++ b/ch8-quickcheck1.py @@ -0,0 +1,13 @@ +''' +Quick Check: Booleans and truthiness +Decide whether the following statements are true or false: + 1, 0, -1, [0], 1 and 0, 1 > 0 or []. +''' + +print("1", 1 == True) #True +print("0", 0 == True) #False +print("-1", -1 == True) #False +print("[0]", [0] is True) #False +print("1 and 0", 1 and 0 == True) #False +print("1 > 0 or []", 1 > 0 or [] is True) #True + diff --git a/ch8-trythis1.py b/ch8-trythis1.py new file mode 100644 index 0000000..0f725c9 --- /dev/null +++ b/ch8-trythis1.py @@ -0,0 +1,45 @@ +''' +Try this: Looping and if statements +Suppose that you have a list x = [1, 3, 5, 0, -1, 3, -2], and you need to +remove all negative numbers from that list. Write the code to do this. +''' +x = [1, 3, 5, 0, -1, 3, -2] +j = 0 +for i in range(len(x)): + if x[i - j] < 0: + del(x[i - j]) + j += 1 +print(x) + +''' +How would you count the total number of negative numbers in a list +y = [[1, -1, 0], [2, 5, -9], [-2, -3, 0]]? +''' +y = [[1, -1, 0], [2, 5, -9], [-2, -3, 0]] +tot = 0 +for i in range(len(y)): + for j in range(len(y[i])): + if y[i][j] < 0: + tot = tot + y[i][j] +print('total of negetives: ', tot) + +''' +What code would you use to print very low if the value of x is below -5, low if it’s +from -5 up to 0, neutral if it’s equal to 0, high if it’s greater than 0 up to 5, and very +high if it’s greater than 5? +''' +def ranking(x): + if x < -5: + print('x is very low') + elif x < 0: + print('x is low') + elif x == 0: + print('x is neutral') + elif x < 5: + print('x is high') + else: + print('x is very high') +# test +for i in range(-7 , 7): + print(i) + ranking(i) diff --git a/ch8-trythis2.py b/ch8-trythis2.py new file mode 100644 index 0000000..becc621 --- /dev/null +++ b/ch8-trythis2.py @@ -0,0 +1,21 @@ +''' +Try this: Comprehensions +What list comprehension would you use to process the list x so that all negative values +are removed? +''' +x = [1, 3, 5, 0, -1, 3, -2] +x = [item for item in x if item > -1] +print(x) +''' +Create a generator that returns only odd numbers from 1 to 100. +(Hint: A number is odd if there is a remainder if divided by 2; use % 2 to get the remainder of division by 2.) +''' +odd = (i for i in range(1, 100) if i % 2 > 0) +#test +for o in odd: + print(o) +''' +Write the code to create a dictionary of the numbers and their cubes from 11 through 15. +''' +xcubes = {x : x*x for x in range(11,16)} +print(xcubes) \ No newline at end of file diff --git a/word_count.txt b/word_count.txt new file mode 100644 index 0000000..6f90e9b --- /dev/null +++ b/word_count.txt @@ -0,0 +1,4 @@ +Python provides a complete set of control flow elements, +including while and for loops, and conditionals. +Python uses the level of indentation to group blocks +of code with control elements. \ No newline at end of file From 595a0d52ab02361246d72168829262b2ca1e3d0e Mon Sep 17 00:00:00 2001 From: mahdavis2024 Date: Wed, 3 Jul 2024 22:31:01 +0330 Subject: [PATCH 09/16] chapter 9 solutions --- ch8-trythis1.py | 2 +- ch9-lab9.py | 80 ++++++++++++++++++++++++++++++++++++++++++++++ ch9-quickcheck1.py | 43 +++++++++++++++++++++++++ ch9-quickcheck2.py | 13 ++++++++ ch9-quickcheck3.py | 18 +++++++++++ ch9-trythis1.py | 26 +++++++++++++++ ch9-trythis2.py | 18 +++++++++++ word_count.txt | 4 --- 8 files changed, 199 insertions(+), 5 deletions(-) create mode 100644 ch9-lab9.py create mode 100644 ch9-quickcheck1.py create mode 100644 ch9-quickcheck2.py create mode 100644 ch9-quickcheck3.py create mode 100644 ch9-trythis1.py create mode 100644 ch9-trythis2.py delete mode 100644 word_count.txt diff --git a/ch8-trythis1.py b/ch8-trythis1.py index 0f725c9..637d7a1 100644 --- a/ch8-trythis1.py +++ b/ch8-trythis1.py @@ -21,7 +21,7 @@ for j in range(len(y[i])): if y[i][j] < 0: tot = tot + y[i][j] -print('total of negetives: ', tot) +print('total of negatives: ', tot) ''' What code would you use to print very low if the value of x is below -5, low if it’s diff --git a/ch9-lab9.py b/ch9-lab9.py new file mode 100644 index 0000000..196e211 --- /dev/null +++ b/ch9-lab9.py @@ -0,0 +1,80 @@ +''' +Lab 9: Useful functions +Looking back at the labs in chapters 6 and 7 , refactor that code into functions for +cleaning and processing the data. +The goal should be that most of the logic is moved into functions. +Use your own judgment as to the types of functions and parameters, but +keep in mind that functions should do just one thing, and they shouldn’t have any side +effects that carry over outside the function. +''' + +# removing punctuation refactored into funtion +def remove_punc(string): + table = string.maketrans('.,?;:!"-_][)(\'',' '*14) + return string.translate(table) + +# counting words refactored into funtion +def w_counter(text): + counted = {} + for word in text: + counted[word] = counted.get(word, 0) + 1 + return counted + +# cleaning file refactored into funtion +def cleaner(text): + words_list = [] + for line in text: + lower_case = line.lower() + sans_punct = remove_punc(lower_case) + line_list = sans_punct.split() + words_list = words_list + line_list + return '\n'.join(words_list) + +# finding most common refactored into funtion +def least_finder(counted_dict): + global maxi + maxi = max(list(counted_dict.values())) + most = [] + for key in list(counted_dict.keys()): + if counted_dict[key] >= maxi - 7: + most.append(key.strip("\n")) + return most + +# finding least common refactored into funtion +def most_finder(counted_dict): + global mini + mini = min(list(counted_dict.values())) + least = [] + for key in list(counted_dict.keys()): + if counted_dict[key] == mini: + least.append(key.strip("\n")) + return least + + +#lab6 refactored +with open("moby_01.txt") as infile, open("moby_01_clean.txt", "w") as outfile: + cleaned_words = cleaner(infile) + outfile.write(cleaned_words) + +# see the outfile +with open('moby_01_clean.txt','r') as outfile: + for each in outfile: + print(each, end = "") + + +#lab7 refactored +with open("moby_01_clean.txt") as infile: + word_count = w_counter(infile) +most_common = most_finder(word_count) +least_common = least_finder(word_count) + + +print('''In the first chapter of Moby Dick\nThe most common words are + {0} with {1} to {2} times of occorance.\n + The least common words are {3} with only {4} times of occurance.'''.format( + most_common, maxi - 7 , maxi , least_common, mini )) + + + + + diff --git a/ch9-quickcheck1.py b/ch9-quickcheck1.py new file mode 100644 index 0000000..ec078df --- /dev/null +++ b/ch9-quickcheck1.py @@ -0,0 +1,43 @@ +''' +Quick Check: Functions and parameters +How would you write a function that could take any number of unnamed arguments +and print their values out in reverse order? +''' +# if reverse order mean descending order: +def reverser(*a): + my_list = [*a] + my_list.sort(reverse = True) + for j in my_list: + print(j) + +reverser(8,5,4,1,3,9,7) +# if reverse means LIFO: + +def lifo(*args): + my_list = [*args] + my_list.reverse() + for i in my_list: + print(i) + +lifo('i','c','a','n') + + +''' +What do you need to do to create a procedure or void function—that is, a function with +no return value? +''' +# There would not be a return statement at the end of the function. +# Or there would not be anything in front of the return statement. +# The funtion can do one of the following to still be productive: +## The procedure might make some changanes to a mutable type, which would hold outside the function. +## Or it can print something in terminal. +## Or it may save a file locally or push a code ... + + +'''What happens if you capture the return value of a function with a variable?''' +# it is possible to use that variable as any other variable then. + + + + + diff --git a/ch9-quickcheck2.py b/ch9-quickcheck2.py new file mode 100644 index 0000000..8ad4b1d --- /dev/null +++ b/ch9-quickcheck2.py @@ -0,0 +1,13 @@ +''' +Quick Check: Mutable function parameters +What would be the result of changing a list or dictionary that was passed into a function +as a parameter value? +Which operations would be likely to create changes that would be +visible outside the function? What steps might you take to minimize that risk? +''' +# The changes would hold outside the function as those are mutable data types. + +# Operations like del, append, +, *, decreasing or increasing the list or dictionary by slice notation... + +# It is possible to avoid modifying a list or dict by making a copy of them by .copy() and .deepcopy() +# and working with that copy. Though it would be wise to refrain from using mutable data types altogether. \ No newline at end of file diff --git a/ch9-quickcheck3.py b/ch9-quickcheck3.py new file mode 100644 index 0000000..ca6ebf5 --- /dev/null +++ b/ch9-quickcheck3.py @@ -0,0 +1,18 @@ +''' +Quick Check: Generator functions +What would you need to modify in the previous code for the function four()to make it +work for any number? +What would you need to add to allow the starting point to also be +set? +''' + +def any_number(starts, any): + x = starts + while x < any: + print("in generator, x =", x) + yield x + x += 1 + + +for _ in any_number(5, 9): + print(_) diff --git a/ch9-trythis1.py b/ch9-trythis1.py new file mode 100644 index 0000000..7ef7e9e --- /dev/null +++ b/ch9-trythis1.py @@ -0,0 +1,26 @@ + +''' +Try this: Global vs. local variables +Assuming that x = 5, what will be the value of x after funct_1() below executes? +After funct_2() executes? +def funct_1(): +x = 3 +def funct_2(): +global x +x = 2 +''' + +x = 5 + +def funct_1(): + x = 3 + +funct_1() +print(x) #5 + +def funct_2(): + global x + x = 2 + +funct_2() +print(x) #2 \ No newline at end of file diff --git a/ch9-trythis2.py b/ch9-trythis2.py new file mode 100644 index 0000000..d5cd602 --- /dev/null +++ b/ch9-trythis2.py @@ -0,0 +1,18 @@ +''' +Try this: Decorators +How would you modify the code for the decorator function to remove unneeded +messages and enclose the return value of the wrapped function in "" and " +", so that myfunction ("hello") would return "hello"? +''' + +def decorate(func): + def wrapper_func(*args): + return func('{}'.format(*args)) + return wrapper_func +## +@decorate +def myfunction(parameter): + print(parameter) + + +myfunction("meu meu") diff --git a/word_count.txt b/word_count.txt deleted file mode 100644 index 6f90e9b..0000000 --- a/word_count.txt +++ /dev/null @@ -1,4 +0,0 @@ -Python provides a complete set of control flow elements, -including while and for loops, and conditionals. -Python uses the level of indentation to group blocks -of code with control elements. \ No newline at end of file From 732eca93116c1b0a98793ecbc2a38d406523b8d2 Mon Sep 17 00:00:00 2001 From: mahdavis2024 Date: Tue, 9 Jul 2024 22:12:16 +0330 Subject: [PATCH 10/16] Chapter 10 exercises --- ch10-lab10.py | 53 +++++++++++++++++++++++++++++++++++++++++++++ ch10-quickcheck1.py | 34 +++++++++++++++++++++++++++++ ch10-quickcheck2.py | 9 ++++++++ ch9-lab9.py | 4 ++-- 4 files changed, 98 insertions(+), 2 deletions(-) create mode 100644 ch10-lab10.py create mode 100644 ch10-quickcheck1.py create mode 100644 ch10-quickcheck2.py diff --git a/ch10-lab10.py b/ch10-lab10.py new file mode 100644 index 0000000..894cfde --- /dev/null +++ b/ch10-lab10.py @@ -0,0 +1,53 @@ +'''Lab 10: Create a module +Package the functions created at the end of chapter 9 as a standalone module. Although +you can include code to run the module as the main program, the goal should be for the +functions to be completely usable from another script.''' + +'''the module for cleaning a text file, counting the words, and reporting frequent words''' + +def remove_punc(string): + '''removing punctuations from any given string''' + table = string.maketrans('.,?;:!"-_][)(\'',' '*14) + return string.translate(table) + + + +def cleaner(text): + '''cleaning a file and making it standard to proccess''' + words_list = [] + for line in text: + lower_case = line.lower() + sans_punct = remove_punc(lower_case) + line_list = sans_punct.split() + words_list = words_list + line_list + return '\n'.join(words_list) + + +def w_counter(text): + '''counting words in any given text''' + counted = {} + for word in text: + counted[word] = counted.get(word, 0) + 1 + return counted + + +def most_finder(counted_dict): + '''inding most common words in a dictionary''' + global maxi + maxi = max(list(counted_dict.values())) + most = [] + for key in list(counted_dict.keys()): + if counted_dict[key] >= maxi - 7: + most.append(key.strip("\n")) + return most + + +def least_finder(counted_dict): + '''finding least common words in a dictionary''' + global mini + mini = min(list(counted_dict.values())) + least = [] + for key in list(counted_dict.keys()): + if counted_dict[key] == mini: + least.append(key.strip("\n")) + return least \ No newline at end of file diff --git a/ch10-quickcheck1.py b/ch10-quickcheck1.py new file mode 100644 index 0000000..efc1ac2 --- /dev/null +++ b/ch10-quickcheck1.py @@ -0,0 +1,34 @@ +''' +Quick Check: Modules +Suppose that you have a module called new_math that contains a function called +new_divide. What are the ways that you might import and then use that function? +What are the pros and cons of each method? +Suppose that the new_math module contains a function call _helper_math(). How +will the underscore character affect the way that _helper_math() is imported? +''' +# first +import new_math +new_math.new_divide() +'''prepending the module name is mandatory. +But the code is more readable and function names are safer to use +and do not clash with other modules.''' + +#second +from new_math import new_divide +new_divide() +'''imports a specific function, less keystrocks are needed for typing. +do not bring upon other methods. function names might interfere with other names.''' + +#third +from new_math import * +''' brings all the opjects inside the module. +this is risky as it does not indicated which functions blong to which module. +it faster in typing but more difficult for debugging.''' + +import new_math +new_math._helper_math() +#or +from new_math import _helper_math +_helper_math() + +''' _helper_math can be accessed using one of these two ways. but not the *.''' \ No newline at end of file diff --git a/ch10-quickcheck2.py b/ch10-quickcheck2.py new file mode 100644 index 0000000..164c931 --- /dev/null +++ b/ch10-quickcheck2.py @@ -0,0 +1,9 @@ +'''Quick Check: Namespaces and scope +Consider a variable width that’s in the module make_window.py. In which of the +following contexts is width in scope?: +(A) within the module itself +(B) inside the resize() function in the module +(C) within the script that imported the make_window.py module''' + +#width is in scope of A the module itself and B the function is the module that uses it. +#but not is the scope of the code that imported the module. \ No newline at end of file diff --git a/ch9-lab9.py b/ch9-lab9.py index 196e211..d65b447 100644 --- a/ch9-lab9.py +++ b/ch9-lab9.py @@ -31,7 +31,7 @@ def cleaner(text): return '\n'.join(words_list) # finding most common refactored into funtion -def least_finder(counted_dict): +def most_finder(counted_dict): global maxi maxi = max(list(counted_dict.values())) most = [] @@ -41,7 +41,7 @@ def least_finder(counted_dict): return most # finding least common refactored into funtion -def most_finder(counted_dict): +def least_finder(counted_dict): global mini mini = min(list(counted_dict.values())) least = [] From 3b9d4c2838c4501e6b175cdd87c197b4709dc9c2 Mon Sep 17 00:00:00 2001 From: mahdavis2024 Date: Wed, 10 Jul 2024 07:46:40 +0330 Subject: [PATCH 11/16] changed solotion for lab 10 --- __pycache__/text_processor.cpython-312.pyc | Bin 0 -> 2383 bytes ch10-lab10.py | 78 ++++++++------------- text_processor.py | 49 +++++++++++++ 3 files changed, 79 insertions(+), 48 deletions(-) create mode 100644 __pycache__/text_processor.cpython-312.pyc create mode 100644 text_processor.py diff --git a/__pycache__/text_processor.cpython-312.pyc b/__pycache__/text_processor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3fbc8a3b48af4e59a69fb7e8e8b6c8af5e87635 GIT binary patch literal 2383 zcmc&$&rcgi6rR~1W*4xH2~eN}7Q!zBp-P$)pjK_us=ZXLNG}PIwe_yag1zg`t|7LJ zx>S`C6x0w^Dpcwr$5i|&xnNll?ka~!Z4dN>peIg!Z;Xi{h^nWKv~OqUy_tRfzVE&D z^KiJ4!1z=BAtlI!{EiQ`L60Yg!!X$-2DwcP`aQW#4FRlRh+suS0xKCZSUDexHx$0| z?wMM~F>+~BOF2wSrcK?p?0HSsJoCP%rL43$p(UN1?cpj$FFVX|Cp6tQG-hTU#vLhU zev>n8uj)ShQix1WygxnFKX5g1_fC9tq!7_gjkpk~ z8GX_8m~Oj)%5Q1iGhsbcJt2@i{p+;pVvd@2H1hG(+()x>U*@dj;um@Eo@0OLIE!`J>D!@whY(55$MYxfY?66`c-vc*(5plf$#K@QB0WF{(of(?vXowdAc0?QF zQXr?DWs`BJ0@=-`EiaH39LtV}0tw*_8o2-yY0Cvq+Oo}{k#9*PbrJ72<+wr((?!`3I?r}han&pK#4E|_w^nL=DZ+Ymnla`v+TM$K{#Q!W?|l;sFIqel=acRHO?imNNs2E_`MQ9-*Nf|C-vJ z5-gu%wni=6z+%Wat_RFzGLBtso}4$$u#(u%be7*k!7_Ypyde-X`h8SAXg{>1r*ozo zNU&rD(xRDngOHxhnzjLj18pxG7lYfr{AhV0v}>q5C+$mfvc7^z93=Z(oMkeRx6GfBOP$`~ivluiAKr zSLPeqSRCc5X!%d7IQfXxsp8tPDuluql7O;+@9@9q;jwiITeiin;PW7w zAuv$q_{D+Vil;J2o17LvGk4S!Fo|0*CI#j~1*lDa`?(6}uU9}>?yZQ*gPGNt4RKR_ zqHYcT7=0mX$bLVvAMtxQ`=3LPZ%8BzCz(j_4*>7ZyzOvRGED4O!ee=JI#On;|6Sf= p*T9A4<{}8taVY(b+&Kt|R6B?$wD+JxrY#383Jo82C^W*4_y_Yp30D9B literal 0 HcmV?d00001 diff --git a/ch10-lab10.py b/ch10-lab10.py index 894cfde..ca07f19 100644 --- a/ch10-lab10.py +++ b/ch10-lab10.py @@ -3,51 +3,33 @@ you can include code to run the module as the main program, the goal should be for the functions to be completely usable from another script.''' -'''the module for cleaning a text file, counting the words, and reporting frequent words''' - -def remove_punc(string): - '''removing punctuations from any given string''' - table = string.maketrans('.,?;:!"-_][)(\'',' '*14) - return string.translate(table) - - - -def cleaner(text): - '''cleaning a file and making it standard to proccess''' - words_list = [] - for line in text: - lower_case = line.lower() - sans_punct = remove_punc(lower_case) - line_list = sans_punct.split() - words_list = words_list + line_list - return '\n'.join(words_list) - - -def w_counter(text): - '''counting words in any given text''' - counted = {} - for word in text: - counted[word] = counted.get(word, 0) + 1 - return counted - - -def most_finder(counted_dict): - '''inding most common words in a dictionary''' - global maxi - maxi = max(list(counted_dict.values())) - most = [] - for key in list(counted_dict.keys()): - if counted_dict[key] >= maxi - 7: - most.append(key.strip("\n")) - return most - - -def least_finder(counted_dict): - '''finding least common words in a dictionary''' - global mini - mini = min(list(counted_dict.values())) - least = [] - for key in list(counted_dict.keys()): - if counted_dict[key] == mini: - least.append(key.strip("\n")) - return least \ No newline at end of file +#importing everything from the module +import text_processor + +#What was done in lab 6 +with open("moby_01.txt") as infile, open("moby_01_clean.txt", "w") as outfile: + cleaned_words = text_processor.cleaner(infile) + outfile.write(cleaned_words) + +# see the outfile +with open('moby_01_clean.txt','r') as outfile: + for each in outfile: + print(each, end = "") + + +#What was done in lab 7 +with open("moby_01_clean.txt") as infile: + word_count = text_processor.w_counter(infile) +most_common = text_processor.most_finder(word_count) +least_common = text_processor.least_finder(word_count) + + +print('''In the first chapter of Moby Dick\nThe most common words are + {0} with {1} to {2} times of occorance.\n + The least common words are {3} with only {4} times of occurance. + '''.format(most_common, text_processor.maxi - 7 , text_processor.maxi , least_common, text_processor.mini )) + + + + + diff --git a/text_processor.py b/text_processor.py new file mode 100644 index 0000000..f06ff61 --- /dev/null +++ b/text_processor.py @@ -0,0 +1,49 @@ +'''the module for cleaning a text file, counting the words, and reporting frequent words''' + + +def remove_punc(string): + '''removing punctuations from any given string''' + table = string.maketrans('.,?;:!"-_][)(\'',' '*14) + return string.translate(table) + + + +def cleaner(text): + '''cleaning a file and making it standard to proccess''' + words_list = [] + for line in text: + lower_case = line.lower() + sans_punct = remove_punc(lower_case) + line_list = sans_punct.split() + words_list = words_list + line_list + return '\n'.join(words_list) + + +def w_counter(text): + '''counting words in any given text''' + counted = {} + for word in text: + counted[word] = counted.get(word, 0) + 1 + return counted + + +def most_finder(counted_dict): + '''inding most common words in a dictionary''' + global maxi + maxi = max(list(counted_dict.values())) + most = [] + for key in list(counted_dict.keys()): + if counted_dict[key] >= maxi - 7: + most.append(key.strip("\n")) + return most + + +def least_finder(counted_dict): + '''finding least common words in a dictionary''' + global mini + mini = min(list(counted_dict.values())) + least = [] + for key in list(counted_dict.keys()): + if counted_dict[key] == mini: + least.append(key.strip("\n")) + return least \ No newline at end of file From 21d5fdf76d8539934bb14e6f3cecaf1f32a765b2 Mon Sep 17 00:00:00 2001 From: mahdavis2024 Date: Sat, 13 Jul 2024 14:22:47 +0330 Subject: [PATCH 12/16] solutions to chapter 15 exercises --- ch15-lab15.py | 67 +++++++++++++++++++++ ch15-trythis,all.py | 138 ++++++++++++++++++++++++++++++++++++++++++++ ch15-trythis3.py | 38 ++++++++++++ ch15csmodule.py | 65 +++++++++++++++++++++ 4 files changed, 308 insertions(+) create mode 100644 ch15-lab15.py create mode 100644 ch15-trythis,all.py create mode 100644 ch15-trythis3.py create mode 100644 ch15csmodule.py diff --git a/ch15-lab15.py b/ch15-lab15.py new file mode 100644 index 0000000..3baa915 --- /dev/null +++ b/ch15-lab15.py @@ -0,0 +1,67 @@ +'''Lab 15: HTML classes +In this lab, you create classes to represent an HTML document. +To keep things simple, assume that each element can contain only text and one subelement. +So the element contains only a element, and the element contains (optional) +text and a

element that contains only text. +The key feature to implement is the __str__() method, +which in turn calls its subelement’s __str__() method, +so that the entire document is returned when the str() function is called on an element. +You can assume that any text comes before the subelement. +Here’s example output from using the classes: +para = p(text="this is some body text") +doc_body = body(text="This is the body", subelement=para) +doc = html(subelement=doc_body) +print(doc) + + +This is the body +

+this is some body text +

+ + +''' + +class element: + def __init__(self, text=None, subelement=None): + '''default value None takes care of nonexicting arguments.''' + self.subelement = subelement + self.text = text + + def __str__(self): + '''__str__ is a dunder method or magic method which is also recursive in this case. + It replaces the regular str method to teach python a special behavior for this program ''' + value = "<{}>\n".format(self.__class__.__name__) #places the class name inside opening element notation <>. + if self.text: + value += "{}\n".format(self.text) + if self.subelement: + value += str(self.subelement) + value += "\n".format(self.__class__.__name__) #places the class name inside closing element notation . + return value + +class html(element): + '''html class inherits instantiation and str method from parent class element.''' + def __init__ (self, text=None, subelement=None): + super().__init__(text, subelement) + def __str__(self): + return super().__str__() + +class body(element): + '''body class inherits instantiation and str method from parent class element.''' + def __init__ (self, text=None, subelement=None): + return super().__init__(text, subelement) + def __str__(self): + return super().__str__() + +class p(element): + '''p class inherits instantiation and str method from parent class element.''' + def __init__(self, text=None, subelement=None): + super().__init__(text, subelement) + def __str__(self): + return super().__str__() + +#testing +para = p(text="this is some body text") +doc_body = body(text="This is the body", subelement=para) +doc = html(subelement=doc_body) +print(doc) \ No newline at end of file diff --git a/ch15-trythis,all.py b/ch15-trythis,all.py new file mode 100644 index 0000000..c9d468d --- /dev/null +++ b/ch15-trythis,all.py @@ -0,0 +1,138 @@ +'''Try this-1: Instance Variables +What code would you use to create a Rectangle class?''' +'''Try this-2: Instance variables and Methods +Update the code for a Rectangle class so that you can set the dimensions when an +instance is created, just as for the Circle class above. Also, add an area() method.''' +'''Try this-3: Class methods +Write a class method similar to total_area() that returns the total circumference of +all circles.''' +'''Try this-4: Inheritance +Rewrite the code for a Rectangle class to inherit from Shape. Because squares and +rectangles are related, would it make sense to inherit one from the other? If so, which +would be the base class, and which would inherit? +How would you write the code to add an area() method for the Square class? Should +the area method be moved into the base Shape class and inherited by circle, square, +and rectangle? If so, what issues would result?''' +'''Try this-5: Private instance variables +Modify the Rectangle class’s code to make the dimension variables private. What +restriction will this modification impose on using the class?''' +'''Try this-6: Properties +Update the dimensions of the Rectangle class to be properties with getters and +setters that don’t allow negative sizes.''' + + +class Shape: + """ parent class defining any shape with coordinates and moving function""" + def __init__(self, x, y): + """defining x and y coordinates for any shape""" + self.x = x + self.y = y + def move(self, delta_x, delta_y): + """defining movement as change of coordinates""" + self.x = self.x + delta_x + self.y = self.y + delta_y + +class Circle(Shape): + """Circle class inheriting from Shape""" + all_circles = [] + pi = 3.14159 + + def __init__(self, rad=1, x=0, y=0): + """inheritin from the base class Shape""" + super().__init__(x, y) + """Creates a Circle with the given radius""" + self.radius = rad + self.__class__.all_circles.append(self) + + def area(self): + """determine the area of the Circle""" + return self.__class__.pi * self.radius * self.radius + + def circumference(self): + return 2 * self.radius * Circle.pi + + @classmethod + def total_area(cls): + total = 0 + for c in cls.all_circles: + total = total + c.area() + return total + + @classmethod + def total_circ(cls): + """class method to total the circumference of all circles created """ + total = 0 + for c in cls.all_circles: + total = total + c.circumference() + return total + +class Rectangle(Shape): + """Rectangle class inhering from Shape""" + def __init__(self, arg1=1, arg2=2, x=0, y=0): + """assigning measurment for two sides of the rectangle""" + super().__init__(x, y) + self.__height = arg1 + self.__width = arg2 + +"""making hieght and width variables private is by using double underscores before their name. +it makes them safe from name clash and accidental change in other programs. +however there's no way to access private variables from instance attributes. +unless explicitally prepended by class name. +Or there should be getter and setter defined for them with @property decorator.""" + + @property + def height(self): + return self.__height + + @height.setter + def height(self, value): + if value <= 0: + raise ValueError('Height must be a positive number.') + self.__height = value + + @property + def width(self): + return self.__width + + @width.setter + def width(self, value): + if value <= 0: + raise ValueError('Width must be a positive number.') + self.__width = value + + + def area(self): + """calculating the area of rectangle""" + return self.__height * self.__width + + def perimeter(self): + """calculating the perimeter of ractangle""" + return 2*self.__height + 2*self.__width + +"""it makes sense for square class to ingerit from rectangle class, +as it is just a rectangle with both sides the same size. +the area method can be ingerited by square from regtangle but it cannot be put into +shape class and be inherited by circle class, +because the formula for the area of a circle is different and not the same as rectangle.""" + +class Square(Rectangle): + def __init__(self, arg=1): + self.arg1 = arg + self.arg2 = arg + Rectangle.__init__(self, self.arg1, self.arg2) + + +#testing Rectangle class +rec = Rectangle(2,3) +print(rec.area()) +print(rec.perimeter()) +rec.move(5,5) +print((rec.x,rec.y)) + + +#testing Square class +squ = Square(2) +print(squ.area()) +print((squ.x,squ.y)) + + diff --git a/ch15-trythis3.py b/ch15-trythis3.py new file mode 100644 index 0000000..dbd6716 --- /dev/null +++ b/ch15-trythis3.py @@ -0,0 +1,38 @@ +'''Try this: Class methods +Write a class method similar to total_area() that returns the total circumference of +all circles.''' + +"""circle module: contains the Circle class.""" +class Circle(Shape): + """Circle class""" + all_circles = [] + pi = 3.14159 + + def __init__(self, r=1, x=0, x=0): + """inheritin from the base class Shape""" + super().__init__(x, y) + """Create a Circle with the given radius""" + self.radius = r + self.__class__.all_circles.append(self) + + def area(self): + """determine the area of the Circle""" + return self.__class__.pi * self.radius * self.radius + + def circumference(self): + return 2 * self.radius * Circle.pi + + @classmethod + def total_area(cls): + total = 0 + for c in cls.all_circles: + total = total + c.area() + return total + + @classmethod + def total_circ(cls): + """class method to total the circumference of all circles created """ + total = 0 + for c in cls.all_circles: + total = total + c.circumference() + return total \ No newline at end of file diff --git a/ch15csmodule.py b/ch15csmodule.py new file mode 100644 index 0000000..d3d19bf --- /dev/null +++ b/ch15csmodule.py @@ -0,0 +1,65 @@ +"""cs module: class scope demonstration module.""" +mv ="module variable: mv" +def mf(): + return "module function (can be used like a class method in " \ + "other languages): mf()" +class SC: + scv = "superclass class variable: self.scv" + __pscv = "private superclass class variable: no access" + def __init__(self): + self.siv = "superclass instance variable: self.siv " \ + "(but use SC.siv for assignment)" + self.__psiv = "private superclass instance variable: " \ + "no access" + def sm(self): + return "superclass method: self.sm()" + def __spm(self): + return "superclass private method: no access" +class C(SC): + cv = "class variable: self.cv (but use C.cv for assignment)" + __pcv = "class private variable: self.__pcv (but use C.__pcv " \ + "for assignment)" + def __init__(self): + SC.__init__(self) + self.__piv = "private instance variable: self.__piv" + def m2(self): + return "method: self.m2()" + def __pm(self): + return "private method: self.__pm()" + def m(self, p="parameter: p"): + lv = "local variable: lv" + self.iv = "instance variable: self.xi" + print("Access local, global and built-in " \ + "namespaces directly") + print("local namespace:", list(locals().keys())) + print(p) #1 Parameter + + print(lv) #2 Local variable + print("global namespace:", list(globals().keys())) + + print(mv) #3 Module variable + + print(mf()) #4 Module function + print("Access instance, class, and superclass namespaces " \ + + + "through 'self'") + print("Instance namespace:",dir(self)) + + print(self.iv) #5 Instance variable + + print(self.__piv) #6 Private instance variable + + print(self.siv) #7 Superclass instance variable + print("Class namespace:",dir(C)) + print(self.cv) #8 Class variable + + print(self.m2()) #9 Method + + print(self.__pcv) #10 Private class variable + + print(self.__pm()) #11 Private method + print("Superclass namespace:",dir(SC)) + print(self.sm()) #12 Superclass method + + print(self.scv) #13 Superclass class variable through instance From 612e2fad8cc664f3db6d3e6a40f1760107d77452 Mon Sep 17 00:00:00 2001 From: mahdavis2024 Date: Wed, 21 Aug 2024 11:42:37 +0330 Subject: [PATCH 13/16] origin --- ch12-lab12.py | 37 ++++++++++++++++++++++++++++++ ch12-quickcheck1.py | 20 +++++++++++++++++ ch15-trythis,all.py | 30 ++++++++++++------------- ch15-trythis3.py | 12 +++++----- path.py | 55 +++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 133 insertions(+), 21 deletions(-) create mode 100644 ch12-lab12.py create mode 100644 ch12-quickcheck1.py create mode 100644 path.py diff --git a/ch12-lab12.py b/ch12-lab12.py new file mode 100644 index 0000000..45b4642 --- /dev/null +++ b/ch12-lab12.py @@ -0,0 +1,37 @@ +''' +Lab 12: More file operations +How might you calculate the total size of all files ending with .txt that aren’t symlinks in +a directory? If your first answer was using os.path, also try it with pathlib, and vice +versa. +Write some code that builds off your solution to move the same .txt files in the lab +question to a new subdirectory called backup in the same directory. +''' +import os +cur_path = os.path.abspath('.') +size = 0 +for text_path in os.listdir(cur_path): + if text_path.endswith('.txt') and not os.path.islink(os.path.join(cur_path, text_path)): + size += os.path.getsize(os.path.join(cur_path, text_path)) + backup_dir = os.path.join(cur_path, 'backup') + if not os.path.exists(backup_dir): + os.makedirs(backup_dir) + backup_path = os.path.join(backup_dir, text_path) + os.rename(os.path.join(cur_path, text_path), backup_path) +print(size) + + +import pathlib +cur_path = pathlib.Path(".") +size = 0 +moved_files = [] +for text_path in cur_path.glob("*.txt"): + if not text_path.is_symlink(): + size += text_path.stat().st_size + backup_dir = cur_path / "backup" + if not backup_dir.exists(): + backup_dir.mkdir() + backup_path = backup_dir / text_path.name + text_path.replace(backup_path) + moved_files.append(text_path.name) +print(size) +print(moved_files) \ No newline at end of file diff --git a/ch12-quickcheck1.py b/ch12-quickcheck1.py new file mode 100644 index 0000000..06994fc --- /dev/null +++ b/ch12-quickcheck1.py @@ -0,0 +1,20 @@ +''' +Quick Check: Manipulating paths +How would you use the os module’s functions to take a path to a file called test.log +and create a new file path in the same directory for a file called test.log.old? How +would you do the same thing using the pathlib module? +What path would you get if you created a pathlib Path object from os .pardir? Try it +and find out. +''' +import os +old_path = os.path.abspath('test.log') +print(old_path) +new_path = '{}.{}'.format(old_path, "old") +print(new_path) + +import pathlib +path = pathlib.Path('test.log') +abs_path = path.resolve() +print(abs_path) +new_path = str(abs_path) + ".old" +print(new_path) \ No newline at end of file diff --git a/ch15-trythis,all.py b/ch15-trythis,all.py index c9d468d..84a4287 100644 --- a/ch15-trythis,all.py +++ b/ch15-trythis,all.py @@ -74,21 +74,21 @@ def __init__(self, arg1=1, arg2=2, x=0, y=0): self.__height = arg1 self.__width = arg2 -"""making hieght and width variables private is by using double underscores before their name. -it makes them safe from name clash and accidental change in other programs. -however there's no way to access private variables from instance attributes. -unless explicitally prepended by class name. -Or there should be getter and setter defined for them with @property decorator.""" - - @property - def height(self): - return self.__height - - @height.setter - def height(self, value): - if value <= 0: - raise ValueError('Height must be a positive number.') - self.__height = value +# """making hieght and width variables private is by using double underscores before their name. +# it makes them safe from name clash and accidental change in other programs. +# however there's no way to access private variables from instance attributes. +# unless explicitally prepended by class name. +# Or there should be getter and setter defined for them with @property decorator.""" + +@property +def height(self): + return self.__height + + @height.setter + def height(self, value): + if value <= 0: + raise ValueError('Height must be a positive number.') + self.__height = value @property def width(self): diff --git a/ch15-trythis3.py b/ch15-trythis3.py index dbd6716..ae1cb6d 100644 --- a/ch15-trythis3.py +++ b/ch15-trythis3.py @@ -8,7 +8,7 @@ class Circle(Shape): all_circles = [] pi = 3.14159 - def __init__(self, r=1, x=0, x=0): + def __init__(self, r=1, x=0, y=0): """inheritin from the base class Shape""" super().__init__(x, y) """Create a Circle with the given radius""" @@ -24,10 +24,10 @@ def circumference(self): @classmethod def total_area(cls): - total = 0 - for c in cls.all_circles: - total = total + c.area() - return total + total = 0 + for c in cls.all_circles: + total = total + c.area() + return total @classmethod def total_circ(cls): @@ -35,4 +35,4 @@ def total_circ(cls): total = 0 for c in cls.all_circles: total = total + c.circumference() - return total \ No newline at end of file + return total \ No newline at end of file diff --git a/path.py b/path.py new file mode 100644 index 0000000..9b00744 --- /dev/null +++ b/path.py @@ -0,0 +1,55 @@ +# working with os + +import os +os.getcwd() # current working directory +os.curdir # constant, returns whatever string your system happens to use as the same directory indicator . or .. +os.listdir(os.curdir) # returns a list of filenames in the current working directory +os.listdir() # appends it to the path for the current working directory +os.chdir(folder name) # “Change directory” function, moves into that folder +os.name # constant returns the name of the Python module imported to handle the operating system: 'nt' for windows, 'posix' for linux +os.environ #All your environment variables and the values associated with them are available in a dictionary +os.rename('old name', 'new name') # To rename (move) a file or directory +os.remove() # Remove or delete a data file with +os.rmdir() # To remove an empty directory +os.mkdir() # create directory without any necessary intermediate directories +os.makedirs() # create directory with all necessary intermediate directories + +os.path.join() # construct pathnames by componants +os.path.split() # returns a two-element tuple splitting the basename of a path +os.path.basename() # returns only the basename of the path +os.path.dirname() # returns the path up to but not including the last name +os.path.splitext() # returns a tuple with separated file extention +os.path.commonprefix(path1, path2, ...) # finds the common prefix (if any) for a set of paths +os.path.expanduser() # expands username shortcuts in paths +os.path.expandvars() # expands environment variables +os.path.isdir(os.path.join(path, os.pardir, os.curdir)) # asks whether the parent of the parent of path is a directory + +os.path.exists() # returns True if its argument is a path corresponding tosomething that exists in the filesystem +os.path.isfile() # returns True if and only if the path it’s given indicates a normal data file of some sort +os.path.isdir() # returns True if and only if its path argument indicates a directory +os.path.islink() # Linux and other UNIX operating +os.path.ismount() # Linux and other UNIX operating +os.path.samefile(path1, path2) # returns True if and only if the two path arguments point to the same file +os.path.isabs(path) # returns True if its argument is an absolute path +os.path.getsize(path) # returns the size of a pathname +os.path.getmtime(path) # returns the last modify time of a pathname +os.path.getatime(path) # returns last access time of a pathname + +# working with pathlib +import pathlib +cur_path = pathlib.Path() +cur_path.cwd() + +from pathlib import Path +cur_path = Path() +cur_path.joinpath() +a_path = WindowsPath('bin/utils/disktools') +a_path.parts # returns a tuple of all the components of a path +a_path.name # returns only the basename of the path +a_path.parent # returns the path up to but not including the last name +a_path.suffix # dotted extension notation used by most filesystems to indicate file type +new_path = cur_path.joinpath('C:', 'my documents', 'tmp') +new_path.iterdir() # returns an iterator of paths +new_path.unlink() # Remove or delete a data file +new_path.mkdir(parents=True) # creates directory with any necessaryintermediate directories +new_path.rmdir() # To remove an empty directory \ No newline at end of file From 41f2886028cd1147c83df2f15e62da27d4b52ccc Mon Sep 17 00:00:00 2001 From: mahdavis2024 Date: Sat, 24 Aug 2024 20:54:23 +0330 Subject: [PATCH 14/16] chapter 13 exercises --- ch12-lab12.py | 3 +- ch13-lab13.py | 69 +++++++++++++++++++++++++++++++++++++++++++++ ch13-quickcheck1.py | 17 +++++++++++ ch13-quickcheck2.py | 7 +++++ ch13-quickcheck3.py | 13 +++++++++ ch13-quickcheck4.py | 8 ++++++ ch13-trythis1.py | 12 ++++++++ 7 files changed, 127 insertions(+), 2 deletions(-) create mode 100644 ch13-lab13.py create mode 100644 ch13-quickcheck1.py create mode 100644 ch13-quickcheck2.py create mode 100644 ch13-quickcheck3.py create mode 100644 ch13-quickcheck4.py create mode 100644 ch13-trythis1.py diff --git a/ch12-lab12.py b/ch12-lab12.py index 45b4642..a7347e1 100644 --- a/ch12-lab12.py +++ b/ch12-lab12.py @@ -1,8 +1,7 @@ ''' Lab 12: More file operations How might you calculate the total size of all files ending with .txt that aren’t symlinks in -a directory? If your first answer was using os.path, also try it with pathlib, and vice -versa. +a directory? If your first answer was using os.path, also try it with pathlib, and vice versa. Write some code that builds off your solution to move the same .txt files in the lab question to a new subdirectory called backup in the same directory. ''' diff --git a/ch13-lab13.py b/ch13-lab13.py new file mode 100644 index 0000000..f0a1424 --- /dev/null +++ b/ch13-lab13.py @@ -0,0 +1,69 @@ +'''Lab 13: Final fixes to wc +If you look at the man page for the wc utility, you see two command­line options that do +very similar things. ­c makes the utility count the bytes in the file, and ­m makes it +count characters (which in the case of some Unicode characters can be two or more +bytes long). In addition, if a file is given, it should read from and process that file, but if +no file is given, it should read from and process stdin. +Rewrite your version of the wc utility to implement both the distinction between bytes +and characters and the ability to read from files and standard input.''' + +import sys + +def wc(filename = None ): + if filename == None: + content = sys.stdin.read() + else: + with open(filename, 'r') as file: + content = file.read() + + lines = content.splitlines() + line_count = len(lines) + word_count = sum(len(line.split()) for line in lines) + char_count = len(content) + + return line_count, word_count, char_count + +if __name__ == "__main__": + filename = input('Enter your text file name example.txt: ') + lines, words, chars = wc(filename) + print(f"Lines: {lines}, Words: {words}, Characters: {chars}") + + + + + +'''The `if __name__ == "__main__":` line is a special construct in Python that allows you to execute code only when the script is run directly (i.e., not when it's imported as a module by another script). + +When you run a Python script, Python assigns a special variable `__name__` to the script. The value of `__name__` is the name of the script, including the file extension. + +When you run a script directly, `__name__` is set to `"__main__"`. When you import a script as a module, `__name__` is set to the name of the module. + +So, when you write `if __name__ == "__main__":`, you're checking if the current script is being run directly (i.e., `__name__ == "__main__"`). If it is, then the code inside the `if` block is executed. + +In other words, this construct allows you to write code that can be executed both when the script is run directly and when it's imported as a module by another script. It's often used to define "main" entry points for scripts, or to provide functionality that can be used by other scripts. + +Here's an example: + +``` +# my_script.py +print("Hello, world!") + +if __name__ == "__main__": + print("This is the main entry point!") +``` + +If you run `my_script.py` directly, it will print: + +``` +Hello, world! +This is the main entry point! +``` + +But if you import `my_script` as a module in another script, it will only print: + +``` +Hello, world! +``` + +Because the code inside the `if __name__ == "__main__":` block is only executed when the script is run directly. +''' \ No newline at end of file diff --git a/ch13-quickcheck1.py b/ch13-quickcheck1.py new file mode 100644 index 0000000..7a4bde1 --- /dev/null +++ b/ch13-quickcheck1.py @@ -0,0 +1,17 @@ +''' +Quick Check +What is the significance of adding a "b" to the file open mode string, as in +open("file", "wb")?''' +# it wirtes to the file in byte mode. + +''' +Suppose that you want to open a file named myfile.txt and write additional data on +the end of it. What command would you use to open myfile.txt? What command +would you use to reopen the file to read from the beginning?''' +with open('myfile', 'a') as mine: + mine.write('this is the added content') + +with open('myfile') as mine: + for line in mine.readline(): + pass + diff --git a/ch13-quickcheck2.py b/ch13-quickcheck2.py new file mode 100644 index 0000000..0d80c9f --- /dev/null +++ b/ch13-quickcheck2.py @@ -0,0 +1,7 @@ +'''Quick Check: struct +What use cases can you think of in which the struct module would be useful for either +reading or writing binary data?''' + +# it is useful for networking, sending and receiving data over sockets. +# also it is good for cryptography, handling data for encryption/decryption. +# reading and saving sensors' data in robotics. \ No newline at end of file diff --git a/ch13-quickcheck3.py b/ch13-quickcheck3.py new file mode 100644 index 0000000..a7fb6cf --- /dev/null +++ b/ch13-quickcheck3.py @@ -0,0 +1,13 @@ +'''Quick Check: Pickles +Think about why a pickle would or would not be a good solution in the following use +cases: +1- Saving some state variables from one run to the next +2- Keeping a higg-score list for a game +3- Storing usernames and passwords +4- Storing a large dictionary of English terms +''' + +# 1- it is doable but time-consuming and memory-guzzling. +# 2- it is a good use but still can be accessed by malicious actors and changed. +# 3- it is not secure to store credentials this way. +# 4- it does not make sense to dump and load the dictionary each time we want to look up a term. \ No newline at end of file diff --git a/ch13-quickcheck4.py b/ch13-quickcheck4.py new file mode 100644 index 0000000..b8079e0 --- /dev/null +++ b/ch13-quickcheck4.py @@ -0,0 +1,8 @@ +'''Quick Check: Shelve +Using a shelf object looks very much like using a dictionary. In what ways is using a +shelf object different? What disadvantages would you expect in using a shelf object? +''' + +# keys can only be in string form. +# shelf objects are stores in disk. +# therefore it goes more slower, but more permanent. \ No newline at end of file diff --git a/ch13-trythis1.py b/ch13-trythis1.py new file mode 100644 index 0000000..ada6c3e --- /dev/null +++ b/ch13-trythis1.py @@ -0,0 +1,12 @@ +'''Try this: Redirecting input and outputWrite some code to use the mio.py module in listing 13.1 to capture all the print output +of a script to a file named myfile.txt, reset the standard output to the screen, and print +that file to screen.''' +import mio + +mio.capture_output("myfile.txt") +print("whatever you want to write.") +print(13/3) +print('these go to the file not the standard screen') +mio.restore_output() +print('this shows on the screen') +mio.print_file("myfile.txt") \ No newline at end of file From a063b25c1b02b8edfcd12808fdaa6c0962242d0c Mon Sep 17 00:00:00 2001 From: mahdavis2024 Date: Thu, 29 Aug 2024 18:21:25 +0330 Subject: [PATCH 15/16] chapter 14 exercises --- ch14-lab14.py | 110 ++++++++++++++++++++++++++++++++++++++++++++ ch14-quickcheck1.py | 6 +++ ch14-quickcheck2.py | 13 ++++++ ch14-quickcheck3.py | 10 ++++ ch14-trythis1.py | 16 +++++++ ch14-trythis2.py | 12 +++++ ch14-trythis3.py | 12 +++++ 7 files changed, 179 insertions(+) create mode 100644 ch14-lab14.py create mode 100644 ch14-quickcheck1.py create mode 100644 ch14-quickcheck2.py create mode 100644 ch14-quickcheck3.py create mode 100644 ch14-trythis1.py create mode 100644 ch14-trythis2.py create mode 100644 ch14-trythis3.py diff --git a/ch14-lab14.py b/ch14-lab14.py new file mode 100644 index 0000000..38a1a23 --- /dev/null +++ b/ch14-lab14.py @@ -0,0 +1,110 @@ +'''Lab 14: Custom exceptions +Think about the module you wrote in chapter 9 to count word frequencies. What errors +might reasonably occur in those functions? Refactor those functions to handle those +exception conditions appropriately.''' + +class FileProcessingError(Exception): + """Custom exception for file processing errors.""" + pass + +class WordCountError(Exception): + """Custom exception for word counting errors.""" + pass + + +def remove_punc(string): + """Remove punctuation from a string.""" + try: + table = string.maketrans('.,?;:!"-_][)(\'',' '*14) + return string.translate(table) + except Exception as e: + raise FileProcessingError(f"Error removing punctuation: {e}") + + +def w_counter(text): + """Count the frequency of words in a text.""" + try: + counted = {} + for word in text: + counted[word] = counted.get(word, 0) + 1 + return counted + except Exception as e: + raise WordCountError(f"Error counting words: {e}") + + +def cleaner(text): + """Clean the text by converting to lowercase and removing punctuation.""" + try: + words_list = [] + for line in text: + lower_case = line.lower() + sans_punct = remove_punc(lower_case) + line_list = sans_punct.split() + words_list = words_list + line_list + return '\n'.join(words_list) + except Exception as e: + raise FileProcessingError(f"Error cleaning text: {e}") + + +def most_finder(counted_dict): + """Find the most common words in the counted dictionary.""" + try: + global maxi + maxi = max(list(counted_dict.values())) + most = [] + for key in list(counted_dict.keys()): + if counted_dict[key] >= maxi - 7: + most.append(key.strip("\n")) + return most + except Exception as e: + raise WordCountError(f"Error finding most common words: {e}") + + +def least_finder(counted_dict): + """Find the least common words in the counted dictionary.""" + try: + global mini + mini = min(list(counted_dict.values())) + least = [] + for key in list(counted_dict.keys()): + if counted_dict[key] == mini: + least.append(key.strip("\n")) + return least + except Exception as e: + raise WordCountError(f"Error finding least common words: {e}") + + +#lab6 refactored +try: + with open("moby_01.txt") as infile, open("moby_01_clean.txt", "w") as outfile: + cleaned_words = cleaner(infile) + outfile.write(cleaned_words) +except FileProcessingError as e: + print(e) + +# see the outfile +try: + with open('moby_01_clean.txt','r') as outfile: + for each in outfile: + print(each, end = "") +except FileProcessingError as e: + print(e) + + +#lab7 refactored +try: + with open("moby_01_clean.txt") as infile: + word_count = w_counter(infile) + most_common = most_finder(word_count) + least_common = least_finder(word_count) +except (FileProcessingError, WordCountError) as e: + print(e) + + +print('''In the first chapter of Moby Dick\nThe most common words are + {0} with {1} to {2} times of occorance.\n + The least common words are {3} with only {4} times of occurance.'''.format( + most_common, maxi - 7 , maxi , least_common, mini )) + + + diff --git a/ch14-quickcheck1.py b/ch14-quickcheck1.py new file mode 100644 index 0000000..b1890ea --- /dev/null +++ b/ch14-quickcheck1.py @@ -0,0 +1,6 @@ +'''Quick Check: Exceptions as classes +If MyError inherits from Exception, what is the difference between except +Exception as e and except MyError as e?''' + +# The first catches any exception that inherits from Exception (most of them), +# whereas the second catches only MyError exceptions. \ No newline at end of file diff --git a/ch14-quickcheck2.py b/ch14-quickcheck2.py new file mode 100644 index 0000000..bd740b1 --- /dev/null +++ b/ch14-quickcheck2.py @@ -0,0 +1,13 @@ +'''Quick Check: Exceptions +Do Python exceptions force a program to halt? +Suppose that you want accessing a dictionary x to always return None if a key doesn’t +exist in the dictionary (that is, if a KeyError exception is raised). What code would you +use? +''' +# not if the exception is safely handled and else and finally clause used. + +def check_dict(dict,akey): + try: + val = dict[akey] + except KeyError as e: + val = None diff --git a/ch14-quickcheck3.py b/ch14-quickcheck3.py new file mode 100644 index 0000000..ee65439 --- /dev/null +++ b/ch14-quickcheck3.py @@ -0,0 +1,10 @@ +'''Quick Check: Context managers +Assume that you’re using a context manager in a script that reads and/or writes several +files. Which of the following approaches do you think would be best? + +A) Put the entire script in a block managed by a with statement. +B) Use one with statement for all file reads and another for all file writes. +C) Use a with statement each time you read a file or write a file (for each line, for example). +D) Use a with statement for each file that you read or write.''' + +D makes more sense. \ No newline at end of file diff --git a/ch14-trythis1.py b/ch14-trythis1.py new file mode 100644 index 0000000..a1ba480 --- /dev/null +++ b/ch14-trythis1.py @@ -0,0 +1,16 @@ +''' +Try this: Catching exceptions +Write code that gets two numbers from the user and divides the first number by the +second. Check for and catch the exception that occurs if the second number is zero +(ZeroDivisionError)''' + +x = int(input('Enter the numerator : ')) +y = int(input('Enter the denominator: ')) +# x,y = 5,0 +try: + z = x / y +except ZeroDivisionError as er: + print(er, '"The denominator cannot be zero."') + y = input('Enter another denominator: ') + +print('The quotient: ', z) \ No newline at end of file diff --git a/ch14-trythis2.py b/ch14-trythis2.py new file mode 100644 index 0000000..7836298 --- /dev/null +++ b/ch14-trythis2.py @@ -0,0 +1,12 @@ +'''Try this: The assert statement +Write a simple program that gets a number from the user and then uses the assert +statement to raise an exception if the number is zero. Test to make sure that the +assert statement fires; then turn it off, +using one of the methods mentioned in this section.''' + +x = int(input('Enter a number: ')) + +print(__debug__) + +assert x != 0, 'the number is zero' +print('entered:', x) \ No newline at end of file diff --git a/ch14-trythis3.py b/ch14-trythis3.py new file mode 100644 index 0000000..b0c9952 --- /dev/null +++ b/ch14-trythis3.py @@ -0,0 +1,12 @@ +''' +Try this: Exceptions +What code would you use to create a custom ValueTooLarge exception and raise that +exception if the variable x is over 1000?''' + +class ValueTooLarge(Exception): + pass + + +def check_value_size(val): + if val > 1000: + raise ValueTooLarge('Value must be less than a thousand.') From c65b4c2e151b8701190d715675a83ebdcd60d813 Mon Sep 17 00:00:00 2001 From: mahdavis2024 Date: Thu, 29 Aug 2024 18:28:33 +0330 Subject: [PATCH 16/16] chapter 14 exercises --- ch14-quickcheck3.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/ch14-quickcheck3.py b/ch14-quickcheck3.py index ee65439..2575658 100644 --- a/ch14-quickcheck3.py +++ b/ch14-quickcheck3.py @@ -7,4 +7,9 @@ C) Use a with statement each time you read a file or write a file (for each line, for example). D) Use a with statement for each file that you read or write.''' -D makes more sense. \ No newline at end of file +# The best approach would be D) Use a with statement for each file that you read or write. +# Using a with statement for each file ensures that each file is properly opened and closed, +# which is crucial for resource management. +# This approach helps prevent resource leaks +# and ensures that files are closed as soon as their operations are complete, +# even if an error occurs during the process \ No newline at end of file