├── main_function
├── .idea
│ ├── .gitignore
│ ├── misc.xml
│ ├── inspectionProfiles
│ │ └── profiles_settings.xml
│ ├── modules.xml
│ └── main_function.iml
├── utils
│ ├── __pycache__
│ │ └── functions1.cpython-38.pyc
│ ├── functions3.py
│ ├── functions2.py
│ └── functions1.py
├── definitions
│ ├── __pycache__
│ │ └── class_example.cpython-38.pyc
│ └── class_example.py
├── main.py
└── test
│ ├── functions_and_arguments.py
│ └── memoization.py
├── Libraries - Pandas.pdf
├── pythonics
├── excel
│ ├── data.xlsx
│ └── excel_example.py
├── json
│ ├── example.json
│ └── json_example.py
├── csv
│ ├── data.csv
│ ├── csv_examples.py
│ └── csv_example.ipynb
├── map_example.py
├── enumerate_example.py
├── zip_example.py
├── lambda_example.py
└── list_tips_tricks.py
├── lessons_pdf
├── Programming - Lesson21.pdf
├── Programming - Lesson22.pdf
├── Programming - Lesson23.pdf
├── Programming - Lesson24.pdf
├── Programming - Lesson25.pdf
├── Programming - Lesson26.pdf
├── Programming - Lesson27.pdf
├── Programming – Lesson1.pdf
├── Programming – Lesson10.pdf
├── Programming – Lesson11.pdf
├── Programming – Lesson12.pdf
├── Programming – Lesson13.pdf
├── Programming – Lesson14.pdf
├── Programming – Lesson15.pdf
├── Programming – Lesson16.pdf
├── Programming – Lesson17.pdf
├── Programming – Lesson18.pdf
├── Programming – Lesson19.pdf
├── Programming – Lesson2.pdf
├── Programming – Lesson20.pdf
├── Programming – Lesson3.pdf
├── Programming – Lesson4.pdf
├── Programming – Lesson5.pdf
├── Programming – Lesson6.pdf
├── Programming – Lesson7.pdf
├── Programming – Lesson8.pdf
├── Programming – Lesson9.pdf
└── README.md
├── exercises
├── exercise5
│ ├── names2.txt
│ ├── names1.txt
│ └── exercise5.py
├── exercise1.py
├── exercise11
│ ├── students.txt
│ └── exercise11.py
├── exercise12.py
├── exercise7.py
├── names.txt
├── exercise13.py
├── exercise4.py
├── exercise3.py
├── exercise10.py
├── exercise8.py
├── exercise9.py
├── exercise2.py
└── exercise6.py
├── pyqt5
├── pyqt_example1.py
├── qt_designer
│ ├── qt_designer_load_ui.py
│ ├── example.ui
│ └── qt_designer_example.py
├── pyqt_vlayout.py
├── pyqt_hlayout.py
├── pyqt_formlayout.py
├── pyqt_example2.py
├── pyqt_gridlayout.py
├── pyqt_nestedlayout.py
└── pyqt_complextlayout.py
├── expert
├── perf_counter.py
├── line_profiler_measurement.py
├── profiler_measurement.py
├── memory_measurement.py
└── notebooks
│ └── boost_app.ipynb
├── static_methods.py
├── sys_example.py
├── math
├── math_examples.py
└── math_example.ipynb
├── algos
├── quick_sort.py
├── merge_sort.py
└── backtracking.py
├── os_example.py
├── inheritance.py
├── privacy_class.py
├── requests_ex.py
├── numpy_examples.py
├── pandas_examples.py
├── pandas_examples2.py
├── styling
└── styling.ipynb
└── re_library
└── re_library.ipynb
/main_function/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/Libraries - Pandas.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/Libraries - Pandas.pdf
--------------------------------------------------------------------------------
/pythonics/excel/data.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/pythonics/excel/data.xlsx
--------------------------------------------------------------------------------
/lessons_pdf/Programming - Lesson21.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/lessons_pdf/Programming - Lesson21.pdf
--------------------------------------------------------------------------------
/lessons_pdf/Programming - Lesson22.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/lessons_pdf/Programming - Lesson22.pdf
--------------------------------------------------------------------------------
/lessons_pdf/Programming - Lesson23.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/lessons_pdf/Programming - Lesson23.pdf
--------------------------------------------------------------------------------
/lessons_pdf/Programming - Lesson24.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/lessons_pdf/Programming - Lesson24.pdf
--------------------------------------------------------------------------------
/lessons_pdf/Programming - Lesson25.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/lessons_pdf/Programming - Lesson25.pdf
--------------------------------------------------------------------------------
/lessons_pdf/Programming - Lesson26.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/lessons_pdf/Programming - Lesson26.pdf
--------------------------------------------------------------------------------
/lessons_pdf/Programming - Lesson27.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/lessons_pdf/Programming - Lesson27.pdf
--------------------------------------------------------------------------------
/lessons_pdf/Programming – Lesson1.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/lessons_pdf/Programming – Lesson1.pdf
--------------------------------------------------------------------------------
/lessons_pdf/Programming – Lesson10.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/lessons_pdf/Programming – Lesson10.pdf
--------------------------------------------------------------------------------
/lessons_pdf/Programming – Lesson11.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/lessons_pdf/Programming – Lesson11.pdf
--------------------------------------------------------------------------------
/lessons_pdf/Programming – Lesson12.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/lessons_pdf/Programming – Lesson12.pdf
--------------------------------------------------------------------------------
/lessons_pdf/Programming – Lesson13.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/lessons_pdf/Programming – Lesson13.pdf
--------------------------------------------------------------------------------
/lessons_pdf/Programming – Lesson14.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/lessons_pdf/Programming – Lesson14.pdf
--------------------------------------------------------------------------------
/lessons_pdf/Programming – Lesson15.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/lessons_pdf/Programming – Lesson15.pdf
--------------------------------------------------------------------------------
/lessons_pdf/Programming – Lesson16.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/lessons_pdf/Programming – Lesson16.pdf
--------------------------------------------------------------------------------
/lessons_pdf/Programming – Lesson17.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/lessons_pdf/Programming – Lesson17.pdf
--------------------------------------------------------------------------------
/lessons_pdf/Programming – Lesson18.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/lessons_pdf/Programming – Lesson18.pdf
--------------------------------------------------------------------------------
/lessons_pdf/Programming – Lesson19.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/lessons_pdf/Programming – Lesson19.pdf
--------------------------------------------------------------------------------
/lessons_pdf/Programming – Lesson2.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/lessons_pdf/Programming – Lesson2.pdf
--------------------------------------------------------------------------------
/lessons_pdf/Programming – Lesson20.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/lessons_pdf/Programming – Lesson20.pdf
--------------------------------------------------------------------------------
/lessons_pdf/Programming – Lesson3.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/lessons_pdf/Programming – Lesson3.pdf
--------------------------------------------------------------------------------
/lessons_pdf/Programming – Lesson4.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/lessons_pdf/Programming – Lesson4.pdf
--------------------------------------------------------------------------------
/lessons_pdf/Programming – Lesson5.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/lessons_pdf/Programming – Lesson5.pdf
--------------------------------------------------------------------------------
/lessons_pdf/Programming – Lesson6.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/lessons_pdf/Programming – Lesson6.pdf
--------------------------------------------------------------------------------
/lessons_pdf/Programming – Lesson7.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/lessons_pdf/Programming – Lesson7.pdf
--------------------------------------------------------------------------------
/lessons_pdf/Programming – Lesson8.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/lessons_pdf/Programming – Lesson8.pdf
--------------------------------------------------------------------------------
/lessons_pdf/Programming – Lesson9.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/lessons_pdf/Programming – Lesson9.pdf
--------------------------------------------------------------------------------
/pythonics/json/example.json:
--------------------------------------------------------------------------------
1 | {
2 | "students": [
3 | {"Name": "Saeed", "Grade": 100},
4 | {"Name": "Salam", "Grade": 99}
5 | ],
6 | "Class": "Math"
7 | }
8 |
--------------------------------------------------------------------------------
/main_function/utils/__pycache__/functions1.cpython-38.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/main_function/utils/__pycache__/functions1.cpython-38.pyc
--------------------------------------------------------------------------------
/main_function/definitions/__pycache__/class_example.cpython-38.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SaeedIsa90/PythonExamples/HEAD/main_function/definitions/__pycache__/class_example.cpython-38.pyc
--------------------------------------------------------------------------------
/exercises/exercise5/names2.txt:
--------------------------------------------------------------------------------
1 |
2 | 346721 Hussin 55
3 | 567342 Rabi 23
4 | 938423 Morad 14
5 |
6 |
7 | 872383 Salem 9
8 | 837612 Ihab 17
9 | 759321 Maisa 80
10 |
11 |
--------------------------------------------------------------------------------
/lessons_pdf/README.md:
--------------------------------------------------------------------------------
1 | السلام عليكم,
2 |
3 | هذه الدروس تتوافق مع ما تم تقديمنه في هذاه السلسلة
4 |
5 | https://www.youtube.com/watch?v=4kDHmNacCNY&list=PLQM0-hCuSIZ2cdxgNprBxwzT7FPo-4Hdw
6 |
7 | لا تنسوا الدعم والاشتراك
8 |
--------------------------------------------------------------------------------
/main_function/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/pythonics/csv/data.csv:
--------------------------------------------------------------------------------
1 | First Name, Last Name, Age, Grade, Address
2 | Saeed, Isa, 30, 100, Haifa
3 | Salam, Khatib-Isa, 10, 60, Baghdad
4 | Nasim, Ali, 60, 98, Qahera
5 | Ahmad, Manna, 32, 88, Tunis
6 | Rabi, Sabi, 40, 65, Italy
7 |
--------------------------------------------------------------------------------
/main_function/utils/functions3.py:
--------------------------------------------------------------------------------
1 |
2 | # Equal function
3 | def my_equal(num1, num2):
4 | print('$$ FUNCTIONS3 $$ is', num1, 'and', num2, 'are equal?')
5 | if num1 == num2:
6 | return True
7 | else:
8 | return False
9 |
--------------------------------------------------------------------------------
/main_function/.idea/inspectionProfiles/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/pyqt5/pyqt_example1.py:
--------------------------------------------------------------------------------
1 | import sys
2 | from PyQt5.QtWidgets import *
3 |
4 | app = QApplication([])
5 | w = QWidget()
6 | w.setGeometry(30, 30, 1000, 1000)
7 | l = QLabel(w)
8 | l.setText("I love programming")
9 | w.show()
10 | sys.exit(app.exec())
11 |
12 |
--------------------------------------------------------------------------------
/exercises/exercise5/names1.txt:
--------------------------------------------------------------------------------
1 | 112233 Saeed 60
2 | 901202 Ali 10
3 | 429112 Salam 29
4 |
5 | 881239 Muhammad 35
6 | 776922 Rasheed 63
7 | 238173 Assadi 19
8 | 472310 Fahd 12
9 | 356214 Samer 21
10 | 667162 Alaa 72
11 |
12 |
13 | 288001 Samar 3
--------------------------------------------------------------------------------
/main_function/main.py:
--------------------------------------------------------------------------------
1 | from utils.functions1 import my_max, get_persons
2 |
3 |
4 | if __name__ == '__main__':
5 | print('Im in main file')
6 | persons = get_persons(2)
7 | val = my_max(persons[0].get_age(), persons[1].get_age())
8 | print('Results is:', val)
9 |
--------------------------------------------------------------------------------
/exercises/exercise1.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def calculate_triangle_area(h, b):
4 | a = (h * b)/2
5 | print('Area is:', a)
6 |
7 |
8 | if __name__ == "__main__":
9 | h = int(input('Enter H: '))
10 | b = int(input('Enter B: '))
11 | calculate_triangle_area(h, b)
12 |
13 |
--------------------------------------------------------------------------------
/exercises/exercise11/students.txt:
--------------------------------------------------------------------------------
1 | ID Name Age Grade
2 | 112233 Saeed 60 80
3 | 901202 Ali 10 82
4 | 429112 Salam 29 92
5 | 881239 Muhammad 35 70
6 | 776922 Rasheed 63 76
7 | 238173 Assadi 19 79
8 | 472310 Fahd 12 91
9 | 356214 Samer 21 88
10 | 667162 Alaa 72 92
11 | 288001 Samar 3 84
12 |
--------------------------------------------------------------------------------
/main_function/test/functions_and_arguments.py:
--------------------------------------------------------------------------------
1 | def print_msg(sender, to='Viewers', msg="You are wonderful******"):
2 | print('Dear', to + ',\n')
3 | print(msg)
4 | print('\n\nBest regards,')
5 | print(sender)
6 |
7 |
8 | print_msg(to='Saeed', sender='Viewers', msg='Thanks:)')
9 |
10 |
--------------------------------------------------------------------------------
/exercises/exercise12.py:
--------------------------------------------------------------------------------
1 |
2 | if __name__ == '__main__':
3 | sentence = input("Enter a sentence: ")
4 | letters = input("Enter letters: ")
5 |
6 | new_words = []
7 | for word in sentence.split():
8 | if word[0] not in letters:
9 | new_words.append(word)
10 |
11 | print(new_words)
12 |
--------------------------------------------------------------------------------
/main_function/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/main_function/.idea/main_function.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/exercises/exercise7.py:
--------------------------------------------------------------------------------
1 | def dividable_by_3(n):
2 | lst = []
3 | for i in range(1, n+1):
4 | if i %3 !=0:
5 | lst.append(i)
6 |
7 | print('List is: ', lst)
8 | print('Length is: ', len(lst))
9 | print('Sum is: ', sum(lst))
10 |
11 |
12 | if __name__ == '__main__':
13 | n = int(input("Enter a number: "))
14 | dividable_by_3(n)
15 |
--------------------------------------------------------------------------------
/exercises/names.txt:
--------------------------------------------------------------------------------
1 | 112233 Saeed 60
2 | 901202 Ali 10
3 | 429112 Salam 29
4 |
5 | 881239 Muhammad 35
6 | 776922 Rasheed 63
7 | 238173 Assadi 19
8 | 472310 Fahd 12
9 | 356214 Samer 21
10 |
11 | 346721 Hussin 55
12 | 567342 Rabi 23
13 | 938423 Morad 14
14 | 872383 Salem 9
15 | 837612 Ihab 17
16 | 759321 Maisa 80
17 | 667162 Alaa 72
18 | 288001 Samar 3
19 |
--------------------------------------------------------------------------------
/exercises/exercise13.py:
--------------------------------------------------------------------------------
1 |
2 | def factorial(n):
3 | if n == 0:
4 | return 1
5 | return n * factorial(n-1)
6 |
7 |
8 | res = factorial(5)
9 | print('Factorial results is: ', res)
10 |
11 |
12 | def fib(n):
13 | if n == 0:
14 | return 0
15 | if n == 1:
16 | return 1
17 | return fib(n-1) + fib(n-2)
18 |
19 |
20 | res = fib(7)
21 | print('Fib result: ', res)
22 |
--------------------------------------------------------------------------------
/exercises/exercise4.py:
--------------------------------------------------------------------------------
1 | def find_adults(file_path):
2 | with open(file_path, 'r') as fd:
3 | for line in fd.readlines():
4 | if line == "" or line == "\n":
5 | continue
6 | split_line = line.split()
7 | if int(split_line[2]) > 20:
8 | print(split_line[1])
9 |
10 |
11 | if __name__ == "__main__":
12 | find_adults('names.txt')
13 |
--------------------------------------------------------------------------------
/expert/perf_counter.py:
--------------------------------------------------------------------------------
1 | from time import perf_counter
2 |
3 |
4 | def calculate_triangle_area(h, b):
5 | a = (h * b)/2
6 | return a
7 |
8 |
9 | if __name__ == "__main__":
10 | start = perf_counter()
11 |
12 | for (h, b) in zip(range(1, 10_000_000), range(101, 25_000_000)):
13 | area = calculate_triangle_area(h, b)
14 |
15 | end = perf_counter()
16 | print('total time = ', end-start)
17 |
--------------------------------------------------------------------------------
/main_function/utils/functions2.py:
--------------------------------------------------------------------------------
1 |
2 | # Max function
3 | def my_max(num1, num2):
4 | print('-- FUNCTIONS2 -- MAX number between', num1, 'and', num2)
5 | if num1 > num2:
6 | return num1
7 | else:
8 | return num2
9 |
10 |
11 | # Min function
12 | def my_min(num1, num2):
13 | print('-- FUNCTIONS2 -- MIN number between', num1, 'and', num2)
14 | if num1 > num2:
15 | return num2
16 | else:
17 | return num1
18 |
19 |
--------------------------------------------------------------------------------
/exercises/exercise3.py:
--------------------------------------------------------------------------------
1 | def check_if_prime(item):
2 | for i in range(2, (item//2)+1):
3 | if (item%i) == 0:
4 | return False
5 | return True
6 |
7 |
8 | if __name__ == '__main__':
9 | lst = [1, 4, 11, 13, 25, 217, 2, 3, 10, 5, 7, 11, 23, 29, 31, 43, 47, 100, 102, 1004]
10 | prime_lst = []
11 |
12 | for item in lst:
13 | if check_if_prime(item):
14 | prime_lst.append(item)
15 |
16 | print('Prime lst is:')
17 | print(prime_lst)
18 |
--------------------------------------------------------------------------------
/exercises/exercise10.py:
--------------------------------------------------------------------------------
1 | def binary_search(lst, n):
2 | left = 0
3 | right = len(lst) - 1
4 | while left <= right:
5 | middle = (left + right)//2
6 | if n < lst[middle]:
7 | right = middle - 1
8 | elif n > lst[middle]:
9 | left = middle + 1
10 | else:
11 | return middle
12 | return -1
13 |
14 |
15 | if __name__ == "__main__":
16 | lst = [1, 3, 4, 6, 9, 12, 15, 19, 25, 60, 120]
17 | idx = binary_search(lst, 25)
18 | print('Index is: ', idx)
19 |
--------------------------------------------------------------------------------
/pythonics/json/json_example.py:
--------------------------------------------------------------------------------
1 | import json
2 |
3 | # Reading json file
4 | file_path = "example.json"
5 | fd = open(file_path)
6 | content = json.load(fd)
7 | fd.close()
8 |
9 | print(content)
10 |
11 | # Writing json file
12 | data = {"Name": "Saeed",
13 | "Family": "Isa",
14 | "Job desc": "SW Eng",
15 | "Grades": [100, 88, 98],
16 | "Address": {"Street": "Ebn roshd",
17 | "House num": 100}
18 | }
19 |
20 | n_fd = open('example2.json', 'w')
21 | json.dump(data, n_fd)
22 | n_fd.close()
23 |
--------------------------------------------------------------------------------
/exercises/exercise8.py:
--------------------------------------------------------------------------------
1 | def ascii_func(sentence):
2 | odd = ''
3 | even = ''
4 | div_by3 = ''
5 |
6 | for i in sentence:
7 | ascii_value = ord(i)
8 | if (ascii_value % 2) == 1:
9 | odd += i
10 | else:
11 | even += i
12 | if (ascii_value % 3) == 0:
13 | div_by3 += i
14 |
15 | print('Odd: ', odd)
16 | print('Even: ', even)
17 | print('Div By3: ', div_by3)
18 |
19 |
20 | if __name__ == '__main__':
21 | inp = input('Enter a sentence: ')
22 | ascii_func(inp)
23 |
--------------------------------------------------------------------------------
/exercises/exercise9.py:
--------------------------------------------------------------------------------
1 | def selection_sort(lst):
2 | for i in range(len(lst)):
3 | # Find the max element in remaining lst
4 | max_idx = 0
5 | for j in range(0, len(lst)-i):
6 | if lst[max_idx] < lst[j]:
7 | max_idx = j
8 |
9 | last_idx = (len(lst)-i)-1
10 | # Swap elements - founded max with last
11 | lst[last_idx], lst[max_idx] = lst[max_idx], lst[last_idx]
12 | return lst
13 |
14 |
15 | if __name__ == '__main__':
16 | lst = [3, 10, 4, 2, 9, 1]
17 | sorted_lst = selection_sort(lst)
18 | print(sorted_lst)
19 |
--------------------------------------------------------------------------------
/expert/line_profiler_measurement.py:
--------------------------------------------------------------------------------
1 | from line_profiler import profile
2 |
3 |
4 | def calculate_triangle_area(h, b):
5 | a = (h * b)/2
6 | return a
7 |
8 |
9 | @profile
10 | def calculate_max(h, b):
11 | if h > b:
12 | return h
13 | else:
14 | return b
15 |
16 |
17 | if __name__ == "__main__":
18 |
19 | for (h, b) in zip(range(1, 15_000_000), range(15_000_000, 30_000_000)):
20 | area = calculate_triangle_area(h, b)
21 |
22 | for (h, b) in zip(range(1, 10_000_00), range(10_000_00, 20_000_00)):
23 | calculate_max(h, b)
24 |
25 | print('done')
26 |
--------------------------------------------------------------------------------
/main_function/definitions/class_example.py:
--------------------------------------------------------------------------------
1 | class Person:
2 | def __init__(self, first_name, last_name, age):
3 | self.firstName = first_name
4 | self.lastName = last_name
5 | self.age = age
6 |
7 | def set_last_name(self, val):
8 | self.lastName = val
9 |
10 | def print_details(self):
11 | print('Your first name is:', self.firstName, ' and your last name is: ', self.lastName,
12 | ' and your age is: ', self.age)
13 |
14 | def multiply_age(self, num):
15 | self.age = self.age * num
16 |
17 | def get_age(self):
18 | return self.age
19 |
--------------------------------------------------------------------------------
/expert/profiler_measurement.py:
--------------------------------------------------------------------------------
1 | from cProfile import Profile
2 |
3 |
4 | def calculate_triangle_area(h, b):
5 | a = (h * b)/2
6 | return a
7 |
8 |
9 | def calculate_max(h, b):
10 | if h > b:
11 | return h
12 | else:
13 | return b
14 |
15 |
16 | if __name__ == "__main__":
17 | with Profile() as pr:
18 |
19 | for (h, b) in zip(range(1, 15_000_000), range(15_000_000, 30_000_000)):
20 | area = calculate_triangle_area(h, b)
21 |
22 | for (h, b) in zip(range(1, 10_000_00), range(10_000_00, 20_000_00)):
23 | calculate_max(h, b)
24 |
25 | pr.print_stats()
26 |
27 |
28 |
--------------------------------------------------------------------------------
/pythonics/map_example.py:
--------------------------------------------------------------------------------
1 | # MAP
2 | lst1 = [1, 2, 3, 4, 5, 6]
3 |
4 | # + 1
5 | lst2 = []
6 | for i in lst1:
7 | lst2.append(i + 1)
8 | print(lst2)
9 |
10 |
11 | # Using map
12 | def add_1(x):
13 | return x + 1
14 |
15 | lst2 = []
16 | for i in lst1:
17 | lst2.append(add_1(i))
18 | print(lst2)
19 |
20 | lst3 = list(map(add_1, lst1))
21 | print(lst3)
22 |
23 | # Power example
24 | def power(x):
25 | return x*x
26 |
27 | lst4 = list(map(power, lst1))
28 | print(lst4)
29 |
30 | lst = ['Saeed', 'Isa', 'Hello']
31 | def add_space(x):
32 | return '__ ' + x + ' __'
33 |
34 | lst5 = list(map(add_space, lst))
35 | print(lst5)
36 |
--------------------------------------------------------------------------------
/static_methods.py:
--------------------------------------------------------------------------------
1 | class Calculator:
2 | def __init__(self):
3 | self.__my_name = 'Amazing CALCULATOR'
4 |
5 | def who_am_i(self):
6 | print('Im the', self.__my_name)
7 |
8 | def change_my_name(self, to):
9 | self.__my_name = to
10 |
11 | @staticmethod
12 | def sub_numbers(a, b):
13 | return a - b
14 |
15 | @staticmethod
16 | def add_numbers(a, b):
17 | return a + b
18 |
19 |
20 | res = Calculator.add_numbers(5, 6)
21 | print(res)
22 |
23 | res = Calculator.sub_numbers(3, 2)
24 | print(res)
25 |
26 | calc = Calculator()
27 |
28 | res = calc.sub_numbers(5, 4)
29 | print(res)
30 |
--------------------------------------------------------------------------------
/sys_example.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 | print("Python version", sys.version)
4 |
5 | # stdin, stdout, stderr (input, output and error channels) control
6 | sys.stdout.write('Hello\n')
7 |
8 | # control channel
9 | fd = open('my_stdout.txt', 'w')
10 | sys.stdout = fd
11 | print('Helllllllloooooooo')
12 | sys.stdout.close()
13 |
14 | sys.stdout = sys.__stdout__
15 | print('Hello again')
16 |
17 | # Max int size
18 | print('Max int size:', sys.maxsize)
19 |
20 | # Command line arguments
21 | print('Sys args:', sys.argv)
22 | print('Args[1]', sys.argv[1])
23 |
24 | # Path
25 | print('PYTHONPATH', sys.path)
26 | for i in sys.path:
27 | print('Path: ', i)
28 |
29 | # Exit
30 | sys.exit()
31 |
--------------------------------------------------------------------------------
/pyqt5/qt_designer/qt_designer_load_ui.py:
--------------------------------------------------------------------------------
1 | from PyQt5 import QtWidgets, uic
2 | import sys
3 |
4 |
5 | class MyApp(QtWidgets.QMainWindow):
6 | def __init__(self):
7 | super(MyApp, self).__init__()
8 | uic.loadUi("example.ui", self)
9 |
10 | self.button = self.findChild(QtWidgets.QPushButton, 'mainbutton') # Find the button
11 | self.button.clicked.connect(self.button_clicked) # function pointer
12 |
13 | self.show()
14 |
15 | def button_clicked(self):
16 | # This is executed when the button is clicked
17 | print('My button was clicked')
18 |
19 |
20 | app = QtWidgets.QApplication(sys.argv)
21 | window = MyApp()
22 | app.exec_()
23 |
--------------------------------------------------------------------------------
/pythonics/enumerate_example.py:
--------------------------------------------------------------------------------
1 | # old way
2 | lst = ['Saeed', 'Subscribe', 'Hello', 1, 105, True, 'World']
3 | my_dict = {"Name": "Saeed", "Family": "Isa", "Key2": "Val2"}
4 |
5 | # list example
6 | j = 0
7 | for item in lst:
8 | print("item:", item, "----- idx: ", j)
9 | j += 1
10 |
11 | # Dict example
12 | j = 0
13 | for key, val in my_dict.items():
14 | print("key:", key, "- val: ", val, "----- idx: ", j)
15 | j += 1
16 |
17 | # Enumerate
18 | # list example
19 | for j, item in enumerate(lst):
20 | print("item:", item, "----- idx: ", j)
21 |
22 | # Dict example
23 | for j, item in enumerate(my_dict.items()):
24 | key, val = item
25 | print("key:", key, "- val: ", val, "----- idx: ", j)
26 |
--------------------------------------------------------------------------------
/math/math_examples.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 | # Mathematical constants
4 | print('Pi:', math.pi)
5 | print('E:', math.e)
6 | print('Inf:', math.inf)
7 | print('Tau:', math.tau)
8 | print('NAN:', math.nan)
9 |
10 | # Mathematical tasks
11 | print('Abs:', math.fabs(-5678))
12 | print('SQRT:', math.sqrt(25))
13 | print('Pow:', math.pow(10, 2))
14 | print('Ceil:', math.ceil(9.123))
15 | print('Floor:', math.floor(9.123))
16 | print('Sin:', math.sin(0))
17 | print('Cos:', math.cos(0))
18 | print('Tan:', math.tan(0))
19 | print('Logarithm:', math.log(100))
20 | print('Logarithm2:', math.log2(100))
21 | print('Logarithm10:', math.log10(100))
22 | print('Exp:', math.exp(5))
23 | print('Factorial:', math.factorial(4))
24 |
25 | # help(math)
26 |
--------------------------------------------------------------------------------
/pyqt5/pyqt_vlayout.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 | from PyQt5.QtWidgets import QApplication, QVBoxLayout, QPushButton, QWidget
4 |
5 |
6 | class Window(QWidget):
7 | def __init__(self):
8 | super().__init__()
9 | self.setWindowTitle("Vertical layout example")
10 | # Create a QVBoxLayout instance
11 | layout = QVBoxLayout()
12 | # Add widgets to the layout
13 | layout.addWidget(QPushButton("Top"))
14 | layout.addWidget(QPushButton("Center"))
15 | layout.addWidget(QPushButton("Bottom"))
16 | # Set the layout on the application's window
17 | self.setLayout(layout)
18 |
19 |
20 | if __name__ == "__main__":
21 | app = QApplication(sys.argv)
22 | window = Window()
23 | window.show()
24 | sys.exit(app.exec())
25 |
--------------------------------------------------------------------------------
/expert/memory_measurement.py:
--------------------------------------------------------------------------------
1 | import tracemalloc
2 |
3 |
4 | def calculate_triangle_area(h, b):
5 | a = (h * b)/2
6 | return a
7 |
8 |
9 | def calculate_max(h, b):
10 | if h > b:
11 | return h
12 | else:
13 | return b
14 |
15 |
16 | def allocate(i):
17 | return [10] * i
18 |
19 |
20 | if __name__ == "__main__":
21 | tracemalloc.start()
22 |
23 | for (h, b) in zip(range(1, 15_000_000), range(15_000_000, 30_000_000)):
24 | area = calculate_triangle_area(h, b)
25 |
26 | for (h, b) in zip(range(1, 10_000_00), range(10_000_00, 20_000_00)):
27 | calculate_max(h, b)
28 | l = allocate(10000)
29 | snapshot = tracemalloc.take_snapshot()
30 | for stats in snapshot.statistics('lineno'):
31 | print(stats)
32 | print('done')
33 |
--------------------------------------------------------------------------------
/pyqt5/pyqt_hlayout.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 | from PyQt5.QtWidgets import QApplication, QHBoxLayout, QPushButton, QWidget
4 |
5 |
6 | class Window(QWidget):
7 | def __init__(self):
8 | super().__init__()
9 | self.setWindowTitle("Horizontal layout example")
10 | # Create a QHBoxLayout instance
11 | layout = QHBoxLayout()
12 | # Add widgets to the layout
13 | layout.addWidget(QPushButton("Left"))
14 | layout.addWidget(QPushButton("Center"), 1)
15 | layout.addWidget(QPushButton("Right"), 2)
16 |
17 | # Set the layout on the application's window
18 | self.setLayout(layout)
19 |
20 |
21 | if __name__ == "__main__":
22 | app = QApplication(sys.argv)
23 | window = Window()
24 | window.show()
25 | sys.exit(app.exec())
26 |
--------------------------------------------------------------------------------
/pyqt5/pyqt_formlayout.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 | from PyQt5.QtWidgets import QApplication, QFormLayout, QLabel, QLineEdit, QWidget
4 |
5 |
6 | class Window(QWidget):
7 | def __init__(self):
8 | super().__init__()
9 | self.setWindowTitle("QFormLayout Example")
10 | # Create a QFormLayout instance
11 | layout = QFormLayout()
12 | # Add widgets to the layout
13 | layout.addRow("Name:", QLineEdit())
14 | layout.addRow("Job:", QLineEdit())
15 | emailLabel = QLabel("Email:")
16 | layout.addRow(emailLabel, QLineEdit())
17 | # Set the layout on the application's window
18 | self.setLayout(layout)
19 |
20 |
21 | if __name__ == "__main__":
22 | app = QApplication(sys.argv)
23 | window = Window()
24 | window.show()
25 | sys.exit(app.exec_())
26 |
--------------------------------------------------------------------------------
/exercises/exercise5/exercise5.py:
--------------------------------------------------------------------------------
1 | def concatenate_names(file1, file2):
2 | fd1 = open(file1, 'r')
3 | fd2 = open(file2, 'r')
4 |
5 | res = open('res_names.txt', 'w')
6 |
7 | while True:
8 | l1 = fd1.readline()
9 | while l1 == '\n' or l1.isspace():
10 | l1 = fd1.readline()
11 |
12 | l2 = fd2.readline()
13 | while l2 == '\n' or l2.isspace():
14 | l2 = fd2.readline()
15 |
16 | if l1 != '':
17 | res.write(' '.join(l1.split()) + '\n')
18 |
19 | if l2 != '':
20 | res.write(' '.join(l2.split()) + '\n')
21 |
22 | if l1 == '' and l2 == '':
23 | break
24 |
25 | fd1.close()
26 | fd2.close()
27 | res.close()
28 |
29 |
30 | if __name__ == '__main__':
31 | concatenate_names('names1.txt', 'names2.txt')
32 |
--------------------------------------------------------------------------------
/pythonics/excel/excel_example.py:
--------------------------------------------------------------------------------
1 | # Reading EXCEL file
2 | import pandas as pd
3 |
4 | # Default behavior - sheet num 0
5 | df = pd.read_excel('data.xlsx')
6 | print('---------')
7 | print(df)
8 |
9 | # Read particular sheet - by name
10 | df = pd.read_excel('data.xlsx', sheet_name='courses')
11 | print('---------')
12 | print(df)
13 |
14 | # Read particular sheet - by Index
15 | df = pd.read_excel('data.xlsx', sheet_name=2)
16 | print('---------')
17 | print(df)
18 |
19 |
20 | # Read multiple sheets - by name
21 | df = pd.read_excel('data.xlsx', sheet_name=['students', 'cities'])
22 | print('---------')
23 | print(df)
24 |
25 | # Reading sheet from output
26 | print(df['students'])
27 |
28 | # Read multiple sheets - by index
29 | df = pd.read_excel('data.xlsx', sheet_name=[0, 1, 2])
30 | print('---------')
31 | print(df)
32 |
33 | # Reading sheet from output
34 | print(df[2])
35 |
--------------------------------------------------------------------------------
/main_function/utils/functions1.py:
--------------------------------------------------------------------------------
1 | from definitions.class_example import Person
2 |
3 | def get_persons(num):
4 | persons = []
5 | for i in range(num):
6 | print('Round: ', i)
7 | first_name = input('Enter first name: ')
8 | last_name = input('Enter last name: ')
9 | age = int(input('Enter age: '))
10 | new_person = Person(first_name, last_name, age)
11 | persons.append(new_person)
12 | return persons
13 |
14 | # Max function
15 | def my_max(num1, num2):
16 | print('** FUNCTIONS1 ** MAX number between', num1, 'and', num2)
17 | if num1 > num2:
18 | return num1
19 | else:
20 | return num2
21 |
22 |
23 | # Min function
24 | def my_min(num1, num2):
25 | print('** FUNCTIONS1 ** MIN number between', num1, 'and', num2)
26 | if num1 > num2:
27 | return num2
28 | else:
29 | return num1
30 |
--------------------------------------------------------------------------------
/exercises/exercise2.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 |
4 | def my_pow(x, y=7):
5 | res = 1
6 | for i in range(y):
7 | res *= x
8 | return res
9 |
10 |
11 | def my_recursive_pow(x, y=7):
12 | if y == 0:
13 | return 1
14 | return x * my_recursive_pow(x, y-1)
15 |
16 |
17 | def check_if_even_or_odd():
18 | while True:
19 | inp = input("Enter a number: ")
20 |
21 | if inp == "exit":
22 | print("End of program, thank you!!!")
23 | break
24 |
25 | if inp.isnumeric():
26 | int_inp = int(inp)
27 | if (int_inp % 2) == 0:
28 | # Even number
29 | print("Pow7 is: ", my_recursive_pow(int_inp))
30 | else:
31 | # Odd number
32 | print("Sqrt is: ", math.sqrt(int_inp))
33 |
34 |
35 | if __name__ == "__main__":
36 | check_if_even_or_odd()
37 |
--------------------------------------------------------------------------------
/exercises/exercise6.py:
--------------------------------------------------------------------------------
1 | def get_list():
2 | inp = input("Enter a list: ")
3 | lst = []
4 | for i in inp.split():
5 | lst.append(int(i))
6 | return lst
7 |
8 |
9 | def check_ascending(left):
10 | for i in range(len(left)-1):
11 | if left[i] >= left[i+1]:
12 | return False
13 | return True
14 |
15 |
16 | def check_descending(right):
17 | for i in range(len(right)-1):
18 | if right[i] <= right[i+1]:
19 | return False
20 | return True
21 |
22 |
23 | def check_if_middle_peak(lst):
24 | m = len(lst)//2
25 | if check_ascending(lst[:m+1]):
26 | if check_descending(lst[m:]):
27 | return True
28 | return False
29 |
30 |
31 | if __name__ == '__main__':
32 | num_lst = get_list()
33 | res = check_if_middle_peak(num_lst)
34 | if res:
35 | print('Yes middle peak!! :) ')
36 | else:
37 | print('Not middle peak!! :( ')
38 |
--------------------------------------------------------------------------------
/main_function/test/memoization.py:
--------------------------------------------------------------------------------
1 |
2 | def fib(idx):
3 | if idx == 0:
4 | return 0
5 | if idx == 1:
6 | return 1
7 | return fib(idx-1) + fib(idx-2)
8 |
9 |
10 | def fib_w_memo(idx, memo=None):
11 | if memo is None:
12 | memo = {} # dictionary from idx => fib(idx), example: memo[5] = 5
13 |
14 | # check if idx is in our dictionary, if so, return its value
15 | if idx in memo.keys():
16 | return memo[idx]
17 |
18 | # Compute
19 | if idx == 0:
20 | return 0
21 | if idx == 1:
22 | return 1
23 |
24 | value = fib_w_memo(idx-1, memo) + fib_w_memo(idx-2, memo)
25 |
26 | # Caching and return the value
27 | memo[idx] = value
28 | return value
29 |
30 |
31 |
32 | import time
33 |
34 | start = time.time()
35 | for i in range(30):
36 | val = fib_w_memo(i)
37 | print(val)
38 |
39 | end = time.time()
40 | print('Total time is', end-start)
41 |
42 | # 0.590054988861084
43 | # 0.0004990100860595703
44 |
45 |
--------------------------------------------------------------------------------
/algos/quick_sort.py:
--------------------------------------------------------------------------------
1 | def partition(num_list, start, end):
2 | # choose pivot
3 | pivot = num_list[end]
4 |
5 | greater_element_iterator = start
6 | for i in range(start, end):
7 | if num_list[i] < pivot:
8 | # Swapping
9 | num_list[i], num_list[greater_element_iterator] = num_list[greater_element_iterator], num_list[i]
10 | greater_element_iterator += 1
11 |
12 | # Swapping pivot
13 | num_list[end], num_list[greater_element_iterator] = num_list[greater_element_iterator], num_list[end]
14 | return greater_element_iterator
15 |
16 |
17 | def quick_sort(num_list, start, end):
18 | if start < end:
19 | pivot_idx = partition(num_list, start, end)
20 |
21 | # quick sort left part
22 | quick_sort(num_list, start, pivot_idx - 1)
23 |
24 | # quick sort right part
25 | quick_sort(num_list, pivot_idx + 1, end)
26 |
27 |
28 | my_list = [20, 7, 1, 62, 33, 29, 12, 50]
29 | quick_sort(my_list, 0, len(my_list)-1)
30 | print(my_list)
31 |
--------------------------------------------------------------------------------
/pyqt5/pyqt_example2.py:
--------------------------------------------------------------------------------
1 | import sys
2 | from PyQt5.QtWidgets import *
3 |
4 |
5 | class Window(QMainWindow):
6 | def __init__(self):
7 | super().__init__()
8 |
9 | # setting title
10 | self.setWindowTitle("Python ")
11 |
12 | # setting geometry
13 | self.setGeometry(100, 100, 600, 400)
14 |
15 | # calling method
16 | self.buildUI()
17 |
18 | # showing all the widgets
19 | self.show()
20 |
21 | # method for widgets build
22 | def buildUI(self):
23 | # creating label
24 | label = QLabel("Hello there", self)
25 |
26 | # setting geometry to label
27 | label.setGeometry(100, 100, 120, 40)
28 |
29 | # adding border to label
30 | label.setStyleSheet("border : 2px solid black")
31 |
32 | # opening window in maximized size
33 | self.show()
34 |
35 |
36 | # create pyqt5 app
37 | app = QApplication(sys.argv)
38 |
39 | # create the instance of our Window
40 | window = Window()
41 |
42 | # start the app
43 | sys.exit(app.exec())
--------------------------------------------------------------------------------
/pythonics/zip_example.py:
--------------------------------------------------------------------------------
1 | # ZIP
2 | lst1 = [1, 2, 3, 4, 5, 6]
3 | lst2 = [6, 5, 4, 3, 2, 1]
4 |
5 | # build lst3: lst3[i] = lst1[i] + lst2[i]
6 | # Old way
7 | lst3 = []
8 | for i in range(len(lst1)):
9 | lst3.append(lst1[i] + lst2[i])
10 | print(lst3)
11 |
12 | # Using ZIP
13 | lst3 = []
14 | for i, j in zip(lst1, lst2):
15 | lst3.append(i + j)
16 | print(lst3)
17 |
18 | # Not the same length
19 | lst1 = [1, 2, 3, 4, 5, 6]
20 | lst2 = [6, 5, 4, 3]
21 |
22 | lst3 = []
23 | for i, j in zip(lst1, lst2):
24 | print(i, j)
25 | lst3.append(i + j)
26 | print(lst3)
27 |
28 | # Multiple lists
29 | lst1 = [1, 2, 3, 4, 5, 6]
30 | lst2 = [6, 5, 4, 3, 2, 1]
31 | lst3 = [3, 5, 3, 5, 3]
32 | lst4 = []
33 | for i, j, k in zip(lst1, lst2, lst3):
34 | print(i, j, k)
35 | lst4.append(i + j + k)
36 | print(lst4)
37 |
38 | # Dict example
39 | dict1 = {"Name": "Saeed", "Family": "Isa", "Youtube": "Yes"}
40 | dict2 = {"Name": "Salam", "Family": "Isa"}
41 | for i, j in zip(dict1.items(), dict2.items()):
42 | print(i, '----', j)
43 |
44 | # Subscribe and share :)
45 |
--------------------------------------------------------------------------------
/os_example.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | print('Current work dir:', os.getcwd())
4 |
5 | # Making dir
6 | # os.mkdir('my_dir')
7 |
8 | # joining paths
9 | proj_dir = 'example_proj'
10 | parent_dir = 'example_dir'
11 | file_name = 'os_example.py'
12 |
13 | # Windows: proj_dir\parent_dir\file_name
14 | # Linux: proj_dir/parent_dir/file_name
15 |
16 | file_path = os.path.join(proj_dir, parent_dir, file_name)
17 | print('File path:', file_path)
18 |
19 | file_name = os.path.basename(file_path)
20 | print('File name:', file_name)
21 | print('File extension:', os.path.splitext(file_name))
22 |
23 | cwd = os.getcwd()
24 | parent_path = os.path.dirname(cwd)
25 | print('Parent path:', parent_path)
26 | print('List dirs:', os.listdir(parent_path))
27 | lst_dir = os.listdir(parent_path)
28 |
29 | # Removing
30 | # os.remove('to_delete.py')
31 | # os.rmdir('my_dir')
32 |
33 | # querying
34 | for i in lst_dir:
35 | full_path_i = os.path.join(parent_path, i)
36 | if os.path.isfile(full_path_i):
37 | print(i, ' is file')
38 | if os.path.isdir(full_path_i):
39 | print(i, ' is dir')
40 |
41 |
--------------------------------------------------------------------------------
/algos/merge_sort.py:
--------------------------------------------------------------------------------
1 | def merge_sort(num_list):
2 | # Stop condition
3 | if len(num_list) <= 1:
4 | return
5 |
6 | # find the middle index
7 | mid = len(num_list) // 2 # integer
8 | left = num_list[:mid] # left part [0->mid]
9 | right = num_list[mid:] # right part
10 |
11 | # solve left part
12 | merge_sort(left)
13 |
14 | # solve right part
15 | merge_sort(right)
16 |
17 | l_idx = r_idx = k_idx = 0
18 | while l_idx < len(left) and r_idx < len(right):
19 | if left[l_idx] < right[r_idx]:
20 | num_list[k_idx] = left[l_idx]
21 | l_idx += 1
22 | else:
23 | num_list[k_idx] = right[r_idx]
24 | r_idx += 1
25 | k_idx += 1
26 |
27 | while l_idx < len(left):
28 | num_list[k_idx] = left[l_idx]
29 | l_idx += 1
30 | k_idx += 1
31 |
32 | while r_idx < len(right):
33 | num_list[k_idx] = right[r_idx]
34 | r_idx += 1
35 | k_idx += 1
36 |
37 |
38 | # Examples:
39 | my_list = [20, 7, 1, 62, 33, 29, 12, 50]
40 | merge_sort(my_list)
41 | print(my_list)
42 |
--------------------------------------------------------------------------------
/inheritance.py:
--------------------------------------------------------------------------------
1 | class Animal:
2 | def __init__(self, name, age, color):
3 | self.name = name
4 | self.age = age
5 | self.color = color
6 |
7 | def get_name(self):
8 | return self.name
9 |
10 | def make_sound(self):
11 | print('This Animal:', self.name, 'has no sound!!!!!')
12 |
13 |
14 | class Dog(Animal):
15 | def make_sound(self):
16 | print('This Dog:', self.name, 'is barking')
17 |
18 |
19 | class Cat(Animal):
20 | def __init__(self, name, age, color, eyes_color):
21 | super().__init__(name, age, color)
22 | self.eyes_color = eyes_color
23 |
24 | def make_sound(self):
25 | print('This Cat:', self.name, 'is meowing')
26 |
27 | def print_eyes_colors(self):
28 | print('This cat has eyes color:', self.eyes_color)
29 |
30 |
31 | class Horse(Animal):
32 | def make_sound(self):
33 | print('This Horse:', self.name, 'is neighing')
34 |
35 |
36 | cat = Cat('my cat', 11, 'white', 'green')
37 | cat.make_sound()
38 | cat.print_eyes_colors()
39 |
40 | my_dog = Dog('my dog', 11, 'white')
41 | my_dog.make_sound()
42 |
--------------------------------------------------------------------------------
/pythonics/lambda_example.py:
--------------------------------------------------------------------------------
1 | # Lambda function
2 | # lambda args: expression
3 | # - any number of args
4 | # - only one expression
5 |
6 | # Default way to write a function
7 | def my_add(x):
8 | return x+1
9 | my_add(1)
10 |
11 | # 1 argument example:
12 | my_func = lambda x: x + 1
13 | print('Lambda add function', my_func(10))
14 |
15 | # multiple arguments example
16 | my_4_add = lambda a, b, c, d: a + b + c + d
17 | res = my_4_add(1, 2, 3, 4)
18 | print('Lambda add function with 4 arguments', res)
19 |
20 |
21 | # List example: add 1 to each item
22 | # without lambda:
23 | def add_1(x):
24 | return x + 1
25 |
26 | lst = [1, 2, 3, 4]
27 | new_lst = list(map(add_1, lst))
28 | print('New list res', new_lst)
29 |
30 | # with lambda function pointer
31 | new_lst = list(map(my_func, lst))
32 | print('New list with lambda res', new_lst)
33 |
34 | # Using lambda directly in map function
35 | new_lst = list(map(lambda x: x +1, lst))
36 | print('New list with lambda res', new_lst)
37 |
38 | # Lambda power example
39 | new_lst = list(map(lambda x: x**2, lst))
40 | print('New list - power one each element, new_lst', new_lst)
41 |
--------------------------------------------------------------------------------
/pythonics/list_tips_tricks.py:
--------------------------------------------------------------------------------
1 | # Definition
2 | lst = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
3 | print(lst)
4 | print(len(lst))
5 |
6 | # Indexing - starts from 0
7 | print(lst[0], '----', lst[5])
8 |
9 | # Slicing
10 | # from:to
11 | print(lst[2:5])
12 |
13 | # from: ==> to the end
14 | print(lst[4:])
15 |
16 | # :to ==> from the start
17 | print(lst[:6])
18 |
19 | # Indexing
20 | # from the end: last element
21 | print(lst[-1])
22 | print(lst[-2])
23 | # Slicing using minus
24 | print(lst[2:-1])
25 |
26 | # operator ::
27 | # from:steps
28 | print(lst[::2])
29 |
30 | # steps from
31 | print(lst[1::2])
32 |
33 | # Reverse using ::
34 | print(lst)
35 | lst2 = lst[::-1]
36 | print(lst2)
37 |
38 | # Concatenation
39 | lst2 = [5, 15, 25, 35]
40 | lst3 = lst + lst2
41 | print(lst3)
42 |
43 | # Functions
44 | # Clear
45 | print(lst2)
46 | lst2.clear()
47 | print('lst2 after clear:', lst2)
48 |
49 | # Copy
50 | print(lst3)
51 | lst4 = lst3.copy()
52 | print(lst4)
53 |
54 | # Sum
55 | s = sum(lst)
56 | print(s)
57 |
58 | # reverse
59 | lst2 = [5, 15, 25, 35]
60 | lst2.reverse()
61 | print(lst2)
62 |
63 | # Comprehension
64 | # lst2 = [1^2 ... 6^2]
65 | lst2 = [i**2 for i in range(1, 7)]
66 | print(lst2)
67 |
68 |
--------------------------------------------------------------------------------
/pyqt5/pyqt_gridlayout.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 | from PyQt5.QtWidgets import QApplication, QGridLayout, QPushButton, QWidget
4 |
5 |
6 | class Window(QWidget):
7 | def __init__(self):
8 | super().__init__()
9 | self.setWindowTitle("QGridLayout Example")
10 | # Create a QGridLayout instance
11 | layout = QGridLayout()
12 | # Add widgets to the layout
13 | layout.addWidget(QPushButton("Button at (0, 0)"), 0, 0)
14 | layout.addWidget(QPushButton("Button at (0, 1)"), 0, 1)
15 | layout.addWidget(QPushButton("Button at (0, 2)"), 0, 2)
16 | layout.addWidget(QPushButton("Button at (1, 0)"), 1, 0)
17 | layout.addWidget(QPushButton("Button at (1, 1)"), 1, 1)
18 | layout.addWidget(QPushButton("Button at (1, 2)"), 1, 2)
19 | layout.addWidget(QPushButton("Button at (2, 0)"), 2, 0)
20 | layout.addWidget(QPushButton("Button at (2, 1)"), 2, 1)
21 | layout.addWidget(QPushButton("Button at (2, 2)"), 2, 2)
22 | # Set the layout on the application's window
23 | self.setLayout(layout)
24 |
25 |
26 | if __name__ == "__main__":
27 | app = QApplication(sys.argv)
28 | window = Window()
29 | window.show()
30 | sys.exit(app.exec_())
31 |
--------------------------------------------------------------------------------
/privacy_class.py:
--------------------------------------------------------------------------------
1 | class Person:
2 | def __init__(self, first_name, last_name, age):
3 | self.__firstName = first_name
4 | self._lastName = last_name
5 | self.age = age
6 | self.__full_name = ''
7 | self.__update_full_name()
8 |
9 | def set_first_name(self, val):
10 | if type(val) != str or val == "":
11 | raise ValueError('First name can not be empty')
12 | self.__firstName = val
13 | self.__update_full_name()
14 |
15 | def get_first_name(self):
16 | return self.__firstName
17 |
18 | def set_last_name(self, val):
19 | if type(val) != str or val == "":
20 | raise ValueError('Last name can not be empty')
21 | self._lastName = val
22 | self.__update_full_name()
23 |
24 | def get_last_name(self):
25 | return self._lastName
26 |
27 | def __update_full_name(self):
28 | self.__full_name = self.__firstName + " " + self._lastName
29 |
30 | def get_age(self):
31 | return self.age
32 |
33 | def print_full_name(self):
34 | print(self.__full_name)
35 |
36 | p = Person('Saeed', 'Isa', 100)
37 |
38 | p.age = 'Isa120'
39 |
40 | p.print_full_name()
41 |
42 | p.set_first_name('Said')
43 | p.print_full_name()
44 |
--------------------------------------------------------------------------------
/pyqt5/pyqt_nestedlayout.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 | from PyQt5.QtWidgets import QApplication, QCheckBox, QFormLayout, QLineEdit, QVBoxLayout,QWidget
4 |
5 |
6 | class Window(QWidget):
7 | def __init__(self):
8 | super().__init__()
9 | self.setWindowTitle("Nested Layouts Example")
10 | # Create an outer layout
11 | outerLayout = QVBoxLayout()
12 | # Create a form layout for the label and line edit
13 | topLayout = QFormLayout()
14 | # Add a label and a line edit to the form layout
15 | topLayout.addRow("Some Text:", QLineEdit())
16 | # Create a layout for the checkboxes
17 | optionsLayout = QVBoxLayout()
18 | # Add some checkboxes to the layout
19 | optionsLayout.addWidget(QCheckBox("Option 1"))
20 | optionsLayout.addWidget(QCheckBox("Option 2"))
21 | optionsLayout.addWidget(QCheckBox("Option 3"))
22 | # Nest the inner layouts into the outer layout
23 | outerLayout.addLayout(topLayout)
24 | outerLayout.addLayout(optionsLayout)
25 | # Set the window's main layout
26 | self.setLayout(outerLayout)
27 |
28 |
29 | if __name__ == "__main__":
30 | app = QApplication(sys.argv)
31 | window = Window()
32 | window.show()
33 | sys.exit(app.exec_())
34 |
--------------------------------------------------------------------------------
/pythonics/csv/csv_examples.py:
--------------------------------------------------------------------------------
1 | # Pandas
2 |
3 | # Read CSV file
4 | import pandas as pd
5 | df = pd.read_csv("data.csv")
6 | print(df)
7 |
8 | # Writing csv
9 | data = [['Layan', 'Haj', 20], ['Muhammed', 'Khalaily', 50], ['Shdwan', 'Kriem', 33]]
10 | df2 = pd.DataFrame(data=data, columns=['FirstName', 'LastName', 'Age'])
11 | print(df2)
12 |
13 | df2.to_csv('data2.csv', index=False)
14 |
15 | # CSV library
16 |
17 | import csv
18 | # Each line is list
19 | with open('data.csv', 'r') as fd:
20 | csv_reader = csv.reader(fd)
21 | for r in csv_reader:
22 | print(r)
23 |
24 | # How can we check the header ?
25 | # Each line is list
26 | with open('data.csv', 'r') as fd:
27 | csv_reader = csv.reader(fd)
28 | for i, r in enumerate(csv_reader):
29 | if i == 0:
30 | print('header:', r)
31 | else:
32 | print('data:', r)
33 |
34 | # Each line is dictionary
35 | with open('data.csv', 'r') as fd:
36 | csv_reader = csv.DictReader(fd)
37 | for r in csv_reader:
38 | print(r)
39 |
40 | # Writing csv
41 | with open('data3.csv', 'w') as fd:
42 | csv_writer = csv.writer(fd)
43 | csv_writer.writerow(['Full Name', 'Day', 'Month'])
44 | csv_writer.writerow(['Saeed Isa', 15, 'July'])
45 | csv_writer.writerow(['Salam Isa-Khatib', 6, 'Feb'])
--------------------------------------------------------------------------------
/exercises/exercise11/exercise11.py:
--------------------------------------------------------------------------------
1 | class Student:
2 | def __init__(self, id, name, age, grade):
3 | self.__id = id
4 | self.__name = name
5 | self.__age = age
6 | self.__grade = grade
7 |
8 | def get_grade(self):
9 | return self.__grade
10 |
11 | def print_details(self):
12 | print('Student details, id', self.__id, '- name:', self.__name,
13 | '- age:', self.__age, '- grade:', self.__grade)
14 |
15 |
16 | def find_max_grade(students):
17 | max_grade = 0
18 | for s in students:
19 | if s.get_grade() > max_grade:
20 | max_grade = s.get_grade()
21 | return max_grade
22 |
23 |
24 | if __name__ == "__main__":
25 |
26 | students = []
27 | with open('students.txt') as fd:
28 | first_line = True
29 | for line in fd.readlines():
30 | if first_line:
31 | first_line = False
32 | continue
33 | details = line.split()
34 | student = Student(int(details[0]), details[1], int(details[2]), int(details[3]))
35 | students.append(student)
36 |
37 | # Find max grade
38 | max_grade = find_max_grade(students)
39 |
40 | # Print student details
41 | for s in students:
42 | if s.get_grade() == max_grade:
43 | s.print_details()
44 |
--------------------------------------------------------------------------------
/requests_ex.py:
--------------------------------------------------------------------------------
1 | import requests
2 |
3 | # Get method
4 | requests.get('https://api.github.com')
5 |
6 | # Response
7 | response = requests.get('https://api.github.com')
8 | print(response)
9 |
10 | # check all API from response
11 | print(dir(response))
12 |
13 | # status code
14 | print(response.status_code)
15 |
16 | print(response.content)
17 |
18 | print(response.json())
19 |
20 | print(response.headers)
21 |
22 | # Page NOT found example
23 | r = requests.get('https://api.github.com/saeed')
24 | print(r.status_code)
25 |
26 | # Search GitHub's repositories for requests demonstrates params usage
27 | response = requests.get(
28 | 'https://api.github.com/search/repositories',
29 | params={'q': 'requests+language:python'},
30 | )
31 |
32 | # Inspect some attributes of the `requests` repository
33 | json_response = response.json()
34 | repository = json_response['items'][0]
35 | print(f'Repository name: {repository["name"]}') # Python 3.6+
36 | print(f'Repository description: {repository["description"]}') # Python 3.6+
37 | print(response.json()['items'][0])
38 |
39 |
40 | # Post method
41 | # data can be dictionary, list of tuples, file-obj alike,...
42 | res = requests.post('https://httpbin.org/post', data={'key':'value'})
43 | print(res.json())
44 |
45 |
46 | res = requests.post('https://httpbin.org/post', json={'key':'value'})
47 | print(res.json())
--------------------------------------------------------------------------------
/pyqt5/pyqt_complextlayout.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 | from PyQt5.QtWidgets import (
4 | QApplication,
5 | QComboBox,
6 | QFormLayout,
7 | QLineEdit,
8 | QStackedLayout,
9 | QVBoxLayout,
10 | QWidget,
11 | )
12 |
13 |
14 | class Window(QWidget):
15 | def __init__(self):
16 | super().__init__()
17 | self.setWindowTitle("Stacked layout Example")
18 | # Create a top-level layout
19 | layout = QVBoxLayout()
20 | self.setLayout(layout)
21 | # Create and connect the combo box to switch between pages
22 | self.pageCombo = QComboBox()
23 | self.pageCombo.addItems(["Page 1", "Page 2"])
24 | self.pageCombo.activated.connect(self.switchPage)
25 | # Create the stacked layout
26 | self.stackedLayout = QStackedLayout()
27 |
28 | # Create the first page
29 | self.page1 = QWidget()
30 | self.page1Layout = QFormLayout()
31 | self.page1Layout.addRow("Name:", QLineEdit())
32 | self.page1Layout.addRow("Address:", QLineEdit())
33 | self.page1.setLayout(self.page1Layout)
34 | self.stackedLayout.addWidget(self.page1)
35 |
36 | # Create the second page
37 | self.page2 = QWidget()
38 | self.page2Layout = QFormLayout()
39 | self.page2Layout.addRow("Job:", QLineEdit())
40 | self.page2Layout.addRow("Department:", QLineEdit())
41 | self.page2.setLayout(self.page2Layout)
42 | self.stackedLayout.addWidget(self.page2)
43 | # Add the combo box and the stacked layout to the top-level layout
44 | layout.addWidget(self.pageCombo)
45 | layout.addLayout(self.stackedLayout)
46 |
47 | def switchPage(self):
48 | print(self.pageCombo.currentIndex())
49 | self.stackedLayout.setCurrentIndex(self.pageCombo.currentIndex())
50 |
51 |
52 | if __name__ == "__main__":
53 | app = QApplication(sys.argv)
54 | window = Window()
55 | window.show()
56 | sys.exit(app.exec_())
57 |
--------------------------------------------------------------------------------
/pyqt5/qt_designer/example.ui:
--------------------------------------------------------------------------------
1 |
2 |
3 | MainWindow
4 |
5 |
6 |
7 | 0
8 | 0
9 | 932
10 | 583
11 |
12 |
13 |
14 | MainWindow
15 |
16 |
17 |
18 |
19 |
20 | 40
21 | 50
22 | 421
23 | 91
24 |
25 |
26 |
27 |
28 | 20
29 |
30 |
31 |
32 | Main label of this window
33 |
34 |
35 |
36 |
37 |
38 | 470
39 | 350
40 | 431
41 | 161
42 |
43 |
44 |
45 |
46 | 22
47 |
48 |
49 |
50 | Click me
51 |
52 |
53 |
54 |
55 |
56 | 40
57 | 160
58 | 421
59 | 91
60 |
61 |
62 |
63 |
64 | 20
65 |
66 |
67 |
68 | hide me
69 |
70 |
71 |
72 |
82 |
83 |
84 |
85 |
86 |
87 | mainbutton
88 | clicked()
89 | hide_label
90 | hide()
91 |
92 |
93 | 685
94 | 451
95 |
96 |
97 | 250
98 | 226
99 |
100 |
101 |
102 |
103 |
104 |
--------------------------------------------------------------------------------
/pyqt5/qt_designer/qt_designer_example.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | # Form implementation generated from reading ui file 'D:\\Python programming\\Python libraries lessons\\Lesson13 - pyqt5 - qtDesigner\\example.ui'
4 | #
5 | # Created by: PyQt5 UI code generator 5.9.2
6 | #
7 | # WARNING! All changes made in this file will be lost!
8 |
9 | from PyQt5 import QtCore, QtGui, QtWidgets
10 |
11 | class Ui_MainWindow(object):
12 | def setupUi(self, MainWindow):
13 | MainWindow.setObjectName("MainWindow")
14 | MainWindow.resize(932, 583)
15 | self.centralwidget = QtWidgets.QWidget(MainWindow)
16 | self.centralwidget.setObjectName("centralwidget")
17 | self.main_label = QtWidgets.QLabel(self.centralwidget)
18 | self.main_label.setGeometry(QtCore.QRect(40, 50, 421, 91))
19 | font = QtGui.QFont()
20 | font.setPointSize(20)
21 | self.main_label.setFont(font)
22 | self.main_label.setObjectName("main_label")
23 | self.mainbutton = QtWidgets.QPushButton(self.centralwidget)
24 | self.mainbutton.setGeometry(QtCore.QRect(470, 350, 431, 161))
25 | font = QtGui.QFont()
26 | font.setPointSize(22)
27 | self.mainbutton.setFont(font)
28 | self.mainbutton.setObjectName("mainbutton")
29 | self.hide_label = QtWidgets.QLabel(self.centralwidget)
30 | self.hide_label.setGeometry(QtCore.QRect(40, 160, 421, 91))
31 | font = QtGui.QFont()
32 | font.setPointSize(20)
33 | self.hide_label.setFont(font)
34 | self.hide_label.setObjectName("hide_label")
35 | MainWindow.setCentralWidget(self.centralwidget)
36 | self.menubar = QtWidgets.QMenuBar(MainWindow)
37 | self.menubar.setGeometry(QtCore.QRect(0, 0, 932, 21))
38 | self.menubar.setObjectName("menubar")
39 | MainWindow.setMenuBar(self.menubar)
40 | self.statusbar = QtWidgets.QStatusBar(MainWindow)
41 | self.statusbar.setObjectName("statusbar")
42 | MainWindow.setStatusBar(self.statusbar)
43 |
44 | self.retranslateUi(MainWindow)
45 | self.mainbutton.clicked.connect(self.button_clicked)
46 | QtCore.QMetaObject.connectSlotsByName(MainWindow)
47 |
48 | def button_clicked(self):
49 | print('hello im clicked')
50 |
51 | def retranslateUi(self, MainWindow):
52 | _translate = QtCore.QCoreApplication.translate
53 | MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
54 | self.main_label.setText(_translate("MainWindow", "Main label of this window"))
55 | self.mainbutton.setText(_translate("MainWindow", "Click me"))
56 | self.hide_label.setText(_translate("MainWindow", "hide me"))
57 |
58 |
59 | if __name__ == "__main__":
60 | import sys
61 | app = QtWidgets.QApplication(sys.argv)
62 | MainWindow = QtWidgets.QMainWindow()
63 | ui = Ui_MainWindow()
64 | ui.setupUi(MainWindow)
65 | MainWindow.show()
66 | sys.exit(app.exec_())
67 |
68 |
--------------------------------------------------------------------------------
/algos/backtracking.py:
--------------------------------------------------------------------------------
1 | # Creating helper functions
2 | def print_sudoku(board):
3 | """
4 | Print sudoku board as matrix 9x9 with 3x3 each box
5 | """
6 | for i in range(len(board)):
7 | if i % 3 == 0 and i != 0:
8 | print("- - - - - - - - - - - - - ")
9 |
10 | for j in range(len(board[0])):
11 | if j % 3 == 0 and j != 0:
12 | print(" | ", end="")
13 |
14 | if j == 8:
15 | print(board[i][j])
16 | else:
17 | print(str(board[i][j]) + " ", end="")
18 |
19 |
20 | def find_next_empty_cell(board):
21 | """
22 | Finds next empty cell in all the board and returns row, col tuple
23 | """
24 | for i in range(len(board)):
25 | for j in range(len(board[0])):
26 | if board[i][j] == 0:
27 | return (i, j) # row, col
28 |
29 | return None
30 |
31 |
32 | ex_board = [
33 | [7, 8, 0, 4, 0, 0, 1, 2, 0],
34 | [6, 0, 0, 0, 7, 5, 0, 0, 9],
35 | [0, 0, 0, 6, 0, 1, 0, 7, 8],
36 | [0, 0, 7, 0, 4, 0, 2, 6, 0],
37 | [0, 0, 1, 0, 5, 0, 9, 3, 0],
38 | [9, 0, 4, 0, 6, 0, 0, 0, 5],
39 | [0, 7, 0, 3, 0, 0, 0, 1, 2],
40 | [1, 2, 0, 0, 0, 7, 4, 0, 0],
41 | [0, 4, 9, 2, 0, 6, 0, 0, 7]
42 | ]
43 |
44 | # print example
45 | print_sudoku(ex_board)
46 | # find example
47 | print('\nfind empty cell example', find_next_empty_cell(ex_board))
48 |
49 |
50 | # validation
51 | def valid_board(board, num, pos):
52 | """
53 | pos: (row, col)
54 |
55 | Checks if assiging num in position gives valid board or not.
56 | """
57 | # Check row - if any number in the row == num
58 | for i in range(len(board[0])):
59 | if board[pos[0]][i] == num and pos[1] != i:
60 | return False
61 |
62 | # Check column - if any number in the col == num
63 | for i in range(len(board)):
64 | if board[i][pos[1]] == num and pos[0] != i:
65 | return False
66 |
67 | # Check box - if any number in 3x3 box == num
68 | box_x = pos[1] // 3
69 | box_y = pos[0] // 3
70 |
71 | for i in range(box_y * 3, box_y * 3 + 3):
72 | for j in range(box_x * 3, box_x * 3 + 3):
73 | if board[i][j] == num and (i, j) != pos:
74 | return False
75 |
76 | return True
77 |
78 |
79 | # check row example
80 | print('\ninvalid row ex', valid_board(ex_board, 4, (0, 2)))
81 | # check column example
82 | print('invalid col ex', valid_board(ex_board, 7, (0, 2)))
83 | # check box example
84 | print('invalid box ex', valid_board(ex_board, 6, (0, 2)))
85 | # Valid example
86 | print('valid', valid_board(ex_board, 3, (0, 2)))
87 |
88 |
89 | def solve_sudoku(board):
90 | # Find next cell to solve
91 | find = find_next_empty_cell(board)
92 | if not find:
93 | return True # did not find any empty cell - filled all cells ==> solved
94 | else:
95 | row, col = find # found empty cell --> assigning to row, col
96 |
97 | for i in range(1,10):
98 | # Checking if assigning i in (row, col) gives valid solution
99 | if valid_board(board, i, (row, col)):
100 | # here --> means i gave valid solution
101 | board[row][col] = i # assigning i to (row, col) cell
102 |
103 | if solve_sudoku(board): # Solve the next empty cell
104 | return True
105 |
106 | board[row][col] = 0 # here --> means this approach does not give valid solution, assiging 0 back to this cell
107 |
108 | return False
109 |
110 |
111 | print('\n----------------before solving-------------------------')
112 | print_sudoku(ex_board)
113 | print('-----------------after solving--------------------------')
114 | solve_sudoku(ex_board)
115 | print_sudoku(ex_board)
116 |
--------------------------------------------------------------------------------
/numpy_examples.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 | a = np.array([1, 2, 3, 4])
4 | print(a)
5 |
6 | print('\n---------- Dimensions ----------')
7 | # Dimensions
8 | # 0-D array
9 | a = np.array(120)
10 | print('0 d array:', a)
11 |
12 | # 1-D array
13 | one_d = np.array([3, 1, 7, 5])
14 | print('1 d array:', one_d)
15 |
16 | # 2-D array
17 | two_d = np.array([[1, 3, 2], [5, 6, 4]])
18 | print('2 d array:\n', two_d)
19 |
20 | # 3-D array
21 | three_d = np.array([[[1, 2], [2, 3]], [[3, 5], [6, 7]]])
22 | print('3 d array:\n', three_d)
23 |
24 | # N-D array
25 | # ...
26 |
27 | print('\n---------- Array attributes ----------')
28 | print('Array dimensions:', two_d.ndim)
29 | print('Array shape:', two_d.shape)
30 |
31 | print('\n---------- Accessing/Indexing ----------')
32 | print('first item in one d array:', one_d[0])
33 | print('first item in two d array:', two_d[0, 0])
34 | print('first item in three d array:', three_d[0, 0, 0])
35 |
36 | print('\n---------- Iterating ----------')
37 | # 1-d array iterating
38 | for x in one_d:
39 | print(x)
40 |
41 | # 2-d array iterating
42 | print('Iterating over 2 d array')
43 | for x in two_d:
44 | for y in x:
45 | print(y)
46 |
47 | # 3-d array iterating
48 | print('Iterating over 3 d array')
49 | for x in three_d:
50 | for y in x:
51 | for f in y:
52 | print(f)
53 |
54 | print('Iterating over all items in array using nditer:')
55 | for x in np.nditer(two_d):
56 | print(x)
57 |
58 | print('\n---------- Search ----------')
59 | # where function
60 | print(np.where(two_d == 4)) # will find all indices match the condition
61 | print(np.where(two_d % 2 == 0)) # will find all indices match the condition (all even numbers)
62 |
63 | print('\n---------- Sort ----------')
64 | print('Sorting array:\n', np.sort(one_d))
65 | print('Sorting each row in array: \n', np.sort(two_d))
66 |
67 | print('\n---------- Random numbers ----------')
68 | print('Random integer:', np.random.randint(100))
69 | print('Random integer between 2 numbers:', np.random.randint(10, 80))
70 | print('Random float ben 0-1:', np.random.rand())
71 |
72 | print('\n---------- Array generation ----------')
73 | print('Generating integer matrix 2x3 with random integer numbers:\n', np.random.randint(10, 90, size=(2, 3)))
74 | print('Generating float matrix 2x3 with random numbers 0-1:\n', np.random.rand(2, 3))
75 | print('Generating zeros matrix 2x3:\n', np.zeros((2, 3), int))
76 | print('Generating ones matrix 2x3:\n', np.ones((2, 3), int))
77 |
78 | print('\n---------- Transpose ----------')
79 | two_d_t = two_d.T
80 | print('original 2 d:\n', two_d, two_d.shape)
81 | print('Transposed 2 d:\n', two_d_t, two_d_t.shape)
82 |
83 | print('\n---------- copy ----------')
84 | two_d_c = two_d.copy()
85 | two_d_c[0, 1] = 1000192
86 | print('Original 2d:\n', two_d)
87 | print('copied 2d:\n', two_d_c)
88 |
89 | print('---------- Mathematical operations ----------')
90 | a = np.array([1, 2])
91 | b = np.array([3, 4])
92 | print('Result of a + b: ', np.add(a, b))
93 | print('Result of a - b: ', np.subtract(a, b))
94 | print('Result of a * b: ', np.multiply(a, b))
95 | print('Result of a / b: ', np.divide(a, b))
96 | print('Result of a ^ b: ', np.power(a, b))
97 | print('Result of a ^ 2: ', np.power(a, 2))
98 |
99 |
100 | print('\n---------- Trigonometric operations ----------')
101 | a = np.array([0, 1])
102 | print(np.sin(a))
103 | print(np.cos(a))
104 |
105 | print('\n---------- Statistical functions ----------')
106 | a = two_d
107 | print('Min item in array:', np.amin(a))
108 | print('Max item in array:', np.amax(a))
109 | print('Median of array:', np.median(a))
110 | print('standard deviation of array:', np.std(a))
111 | print('Average of array:', np.average(a))
112 | print('Mean of array:', np.mean(a))
113 | print('Variance of array:', np.var(a))
114 |
115 | print('\n---------- Algebra functions ----------')
116 | a = np.array([2, 4])
117 | b = np.array([3, 5])
118 | print('1-d Matrices multiplication:\n', np.matmul(a, b))
119 |
120 | a = np.array([[2, 4], [1, 3]])
121 | b = np.array([[3, 5], [4, 6]])
122 | print('2-d Matrices multiplication:\n', np.matmul(a, b))
123 |
124 | print('\n---------- Algebra functions ----------')
125 | a = np.array([1, 2, 3, 5, 6, 1, 2, 3, 4, 1, 1, 2, 6])
126 | print('Histogram of array', np.histogram(a))
127 |
--------------------------------------------------------------------------------
/pandas_examples.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 |
3 | # Generating DataFrame
4 | print('\n---------- Generating DataFrame ----------')
5 | print('\n---------- DataFrame from 2-D Array ----------')
6 | df = pd.DataFrame(columns=['Name', 'City', 'Grade'],
7 | data=[['Saeed', 'Majd el kurum', 88],
8 | ['Salam', 'Qahera', 97],
9 | ['Nidal', 'Bagdad', 93]])
10 | print(df)
11 |
12 | print('\n---------- DataFrame from dictionary ----------')
13 | data = {'Name': ['Saeed', 'Salam', 'Nidal'],
14 | 'City': ['Majd el kurum', 'Qahera', 'Bagdad'],
15 | 'Grade': [88, 97, 93]}
16 |
17 | # Takes dictionary keys as column names
18 | # Default Index labels (numbers)
19 | df = pd.DataFrame(data)
20 | print(df)
21 |
22 | # Saving data frame as a csv
23 | df.to_csv('my_data.csv', index=False)
24 |
25 | print('\n---------- DataFrame from CSV file ----------')
26 | new_df = pd.read_csv('my_data.csv')
27 | print(new_df)
28 |
29 | # Dataframe attributes
30 | print('\n---------- DataFrame attributes ----------')
31 | print('Dataframe shape:', df.shape)
32 | print('Dataframe indices description:', df.index)
33 | print('Dataframe columns:', df.columns) # Can convert to regular list
34 |
35 | # Accessing and Indexing data in DataFrame
36 | print('\n---------- Accessing and Indexing ----------')
37 | print('\n----- Getting data subset -----')
38 | print('Getting subset from index 1:\n', df[1:]) # Same as list but works with indices
39 | print('Getting subset from index 1-2', df[1:2]) # getting data from index 1 till 2 not included
40 |
41 | print('\n----- By Position -----')
42 | # Only numbers - be careful
43 | print('Getting single value:', df.iloc[0, 1]) # Treat it as 2-D array
44 | print('Getting whole row:\n', df.iloc[0])
45 |
46 | print('\n----- By Label -----')
47 | # Index & Column names
48 | print('Getting single value:', df.loc[0, 'City']) # Treat it as 2-D array but with real label names
49 | print('Getting whole row0:\n', df.loc[0])
50 |
51 | print('\n----- Getting Column -----')
52 | print('Getting column data:\n', df['City']) # Returns DataSeries - including indices
53 |
54 | print('\n----- Setting data -----')
55 | df.loc[0, 'City'] = 'Demashq' # Setting single value
56 | print(df)
57 |
58 | print('\n----- Filtering data -----')
59 | # use boolean expressions - brackets are super important
60 | print('Showing data where grade > 90:\n', df[df['Grade'] > 90]) # Returns new DataFrame
61 | print('Showing data where grade > 90 & from Bagdad:\n', df[(df['Grade'] > 90) & (df['City'] == 'Bagdad')])
62 |
63 | print('\n---------- Dropping ----------')
64 | print('Dropping city column:\n', df.drop(columns=['City'])) # Returns new DataFrame
65 | print('Dropping 0 row:\n', df.drop(index=[0])) # Returns new DataFrame
66 |
67 | print('\n---------- Copy ----------')
68 | new_df = df.copy()
69 | print('New dataframe is a total new copy:\n', new_df)
70 |
71 | print('\n---------- Creating new column ----------')
72 | new_df['New Grade'] = new_df['Grade']/10 # Creating "new grade" column based on original grade scaled by 10
73 | print(new_df)
74 | new_df['Family name'] = ['Isa', 'Isa', 'Isa2'] # Creating new column based on external data
75 | print(new_df)
76 |
77 | print('\n---------- Iterating over ----------')
78 | # Do you real need it?
79 | for index, row in df.iterrows():
80 | print('This student: ', row['Name'], '- is from:', row['City'])
81 |
82 | print('\n---------- Sorting ----------')
83 | print('Sorting by grade:\n', df.sort_values(by=['Grade'])) # Can be multiple columns
84 |
85 | print('\n---------- Cleaning ----------')
86 | new_df = df.copy()
87 | print(new_df)
88 | # NaN value can be fetched from numpy
89 | import numpy as np
90 | new_df['Family name'] = ['Isa', 'Isa', np.nan]
91 | print(new_df)
92 | print('Dropping NaN data\n', new_df.dropna()) # Will drop the whole row
93 | print('Filling NaN data\n', new_df.fillna('Anything')) # will fill any NaN cell with this value
94 |
95 | # More & More of data analytics
96 | print('\n---------- More & More ----------')
97 | # df.sum() will sum all columns, strings will be one string, nums will be sum of them...
98 | print('Dataframe grade sum:', df['Grade'].sum()) # sum can be used in whole data frame as well
99 | print('Max grade:', df['Grade'].max())
100 | print('Min grade:', df['Grade'].min())
101 | print('Index of Max grade:', df['Grade'].idxmax())
102 | print('Index of Min grade:', df['Grade'].idxmin())
103 | print('Mean of grades:', df['Grade'].mean())
104 | print('Median of grades:', df['Grade'].median())
105 |
106 | print('\n---------- Applying function ----------')
107 | # Running function on DataFrame values
108 | def add_factor(x):
109 | return x * 2
110 |
111 |
112 | print('Applying function to single columns:\n', df['Grade'].apply(add_factor)) # df.apply(..) will run it for each val
113 | # df['Grade'] = df['Grade'].apply(add_factor)
114 | print('Applying function for each value:\n', df.apply(add_factor))
115 |
116 | print('\n---------- GroupBy ----------')
117 | # Grouping according to value, e.g. group by city
118 | new_df = df.copy()
119 | new_df.loc[1, 'City'] = 'Bagdad'
120 | print(new_df)
121 | grouped_df = new_df.groupby(by=['City'])
122 | for g, d in grouped_df:
123 | print('Group name:', g)
124 | print('Group dataframe:\n', d)
125 | print('************')
126 |
127 | # Rows shifting
128 | # Handling NaN values
129 | # ...
130 |
--------------------------------------------------------------------------------
/pandas_examples2.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 |
3 | products = pd.DataFrame({'category': ['Cleaning', 'Cleaning', 'Entertainment', 'Entertainment', 'Tech', 'Tech'],
4 | 'store': ['Walmart', 'Target', 'Walmart', 'MySuper', 'Target', 'Walmart'],
5 | 'price': [11.42, 23.50, 19.99, 15.95, 55.75, 111.55],
6 | 'amount': [4, 3, 5, 7, 5, 8]})
7 | print(products)
8 |
9 | print('\n---------- Head & Tail ----------')
10 | print('----- Head -----')
11 | print(products.head(2)) # Default is 10
12 | print('\n----- Tail -----')
13 | print(products.tail(2)) # Default is 10
14 |
15 | print('\n---------- Pivoting ----------')
16 | print(products)
17 | # Pivoting data according to index by column
18 | pivot_products = products.pivot(index='category', columns='store', values='price')
19 | print('\n--------------------')
20 | print(pivot_products)
21 |
22 |
23 | print('\n---------- New DataFrame ----------')
24 | df = pd.DataFrame(columns=['Name', 'City', 'Grade'],
25 | data=[['Saeed', 'Majd el kurum', 88],
26 | ['Salam', 'Qahera', 97],
27 | ['Nidal', 'Bagdad', 93]])
28 | print(df)
29 |
30 | print('\n---------- Rename ----------')
31 | print('----- Rename columns -----')
32 | new_df = df.rename(columns={'City': 'Country'})
33 | print(new_df)
34 |
35 | print('\n----- Rename index -----')
36 | new_df = df.rename(index={0: 'row0'})
37 | print(new_df)
38 |
39 | print('\n----- Rename index & columns -----')
40 | new_df = df.rename(index={0: 'row0'}, columns={'City': 'Country'})
41 | print(new_df)
42 |
43 |
44 | print('\n---------- Data types ----------')
45 | print('DataFrame columns data types:\n', df.dtypes) # type per column
46 | print('DataFrame City column data type:', df['City'].dtype) # type per City column
47 |
48 | new_df = df.copy() # Creating new copy of DF
49 | # print(new_df)
50 | print('\n----- Changing single column type -----')
51 | new_df['Grade'] = new_df['Grade'].astype('float') # Converting int to float
52 | print('DataFrame columns data types:\n', new_df.dtypes) # type per column
53 |
54 |
55 | print('\n----- Changing all DataFrame -----')
56 | new_df = new_df.astype('str') # Converting all data frame to string
57 | print('DataFrame columns data types:\n', new_df.dtypes) # type per column
58 |
59 | print('\n----- Changing multiple columns at once -----')
60 | new_df = new_df.astype({'City': 'str', 'Grade': 'float'})
61 | print('DataFrame columns data types:\n', new_df.dtypes) # type per column
62 | print(new_df)
63 |
64 | print('\n---------- New DataFrame ----------')
65 | df1 = df.copy()
66 | df2 = pd.DataFrame(columns=['Name', 'City', 'Grade'],
67 | data=[['Saeed2', 'kurum2', 99],
68 | ['Salam2', 'Qahera2', 45],
69 | ['Nidal2', 'Bagdad2', 66]])
70 | print(df2)
71 |
72 | print('\n---------- Concatenating & re-indexing ----------')
73 | print('----- Concatenate index axis -----')
74 | df3 = pd.concat([df1, df2]) # Same as default axis=0
75 | print(df3)
76 |
77 | print('----- Index resetting -----')
78 | # For non meaningful indices
79 | df3 = df3.reset_index(drop=True) # will reset index and drop original indices
80 | print(df3)
81 |
82 | print('----- Index resetting during concat -----')
83 | df3 = pd.concat([df1, df2], ignore_index=True) # Same as default axis=0
84 | print(df3)
85 |
86 | print('----- Redefining DataFrame -----')
87 | df2 = pd.DataFrame(columns=['Name', 'City', 'Grade2'],
88 | data=[['Saeed2', 'kurum2', 99],
89 | ['Salam2', 'Qahera2', 45],
90 | ['Nidal2', 'Bagdad2', 66]])
91 | print(df2)
92 |
93 | # Concatenate index axis with different column names
94 | print('----- Concatenating different columns -----')
95 | df3 = pd.concat([df1, df2]) # Will fill NaN
96 | print(df3)
97 |
98 | # Concatenate index axis with different column names but removing columns has NaN Values
99 | print('----- Concatenating different columns - remove NaN columns -----')
100 | df3 = pd.concat([df1, df2], join='inner') # Will remove NaN columns
101 | print(df3)
102 |
103 | print('----- Concatenate column axis -----')
104 | df2 = pd.DataFrame(columns=['Family Name', 'Country'],
105 | data=[['Isa', 'c1'],
106 | ['Isa', 'C2'],
107 | ['ISa2', 'C3']])
108 | print(df2)
109 |
110 | df3 = pd.concat([df1, df2], axis=1)
111 | print(df3)
112 | # All above concatenating function works with axis=1
113 |
114 | print('----- Concatenate using append -----')
115 | df = df1.append(df2)
116 | print(df)
117 |
118 |
119 | # Duplications
120 | print('----- Duplications -----')
121 | df = pd.DataFrame(columns=['Name', 'City', 'Grade'],
122 | data=[['Saeed', 'Majd el kurum', 88],
123 | ['Salam', 'Qahera', 97],
124 | ['Saeed', 'Majd el kurum', 88]])
125 | print(df)
126 | new_df = df.drop_duplicates()
127 | print(new_df)
128 |
129 | # Merge and Join
130 | print('\n---------- Merge ----------')
131 | left = pd.DataFrame({"ID": ["K0", "K0", "K1", "K2"],
132 | "FirstName": ["K0", "K1", "K0", "K1"],
133 | "A": ["A0", "A1", "A2", "A3"],
134 | "B": ["B0", "B1", "B2", "B3"]})
135 | print('--------------\nLeft data frame:\n', left)
136 |
137 | right = pd.DataFrame({"ID": ["K0", "K1", "K1", "K2"],
138 | "FirstName": ["K0", "K0", "K0", "K0"],
139 | "C": ["C0", "C1", "C2", "C3"],
140 | "D": ["D0", "D1", "D2", "D3"]})
141 | print('--------------\nRight data frame:\n', right)
142 |
143 | # Main questions while merging: on what ? how to ?
144 | # on ==> which keys (default index)
145 | # how ==> left, right, outer, inner (default left)
146 |
147 | df3 = pd.merge(left, right, on=['ID', 'FirstName'], how='left') # Iterating over left "on" keys
148 | print('--------------\nMerging how=left:\n', df3)
149 |
150 | print('--------------\nLeft data frame:\n', left)
151 | print('--------------\nRight data frame:\n', right)
152 | df3 = pd.merge(left, right, on=['ID', 'FirstName'], how='outer') # Union
153 | print('--------------\nMerging how=outer:\n', df3)
154 |
155 |
156 | print('--------------\nLeft data frame:\n', left)
157 | print('--------------\nRight data frame:\n', right)
158 | df3 = pd.merge(left, right, on=['ID', 'FirstName'], how='inner') # Intersection
159 | print('--------------\nMerging how=inner:\n', df3)
160 |
161 | # Homework: join
162 |
--------------------------------------------------------------------------------
/expert/notebooks/boost_app.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "id": "4c5b4b0e-7e9c-4f84-891a-20d9e478a048",
6 | "metadata": {
7 | "tags": []
8 | },
9 | "source": [
10 | "## Built in functions"
11 | ]
12 | },
13 | {
14 | "cell_type": "code",
15 | "execution_count": 1,
16 | "id": "157c1ad6-b8c1-42d4-ae7f-469ea0d46d49",
17 | "metadata": {
18 | "tags": []
19 | },
20 | "outputs": [],
21 | "source": [
22 | "def my_sum(lst):\n",
23 | " lst_sum = 0\n",
24 | " for item in lst:\n",
25 | " lst_sum += item\n",
26 | " return lst_sum"
27 | ]
28 | },
29 | {
30 | "cell_type": "code",
31 | "execution_count": 2,
32 | "id": "09fd4412-08a8-485a-a3f5-20daf4ffd485",
33 | "metadata": {
34 | "tags": []
35 | },
36 | "outputs": [],
37 | "source": [
38 | "my_lst = [10] * 100"
39 | ]
40 | },
41 | {
42 | "cell_type": "code",
43 | "execution_count": 3,
44 | "id": "5854811d-ea92-4190-8dea-16a12d222460",
45 | "metadata": {},
46 | "outputs": [
47 | {
48 | "name": "stdout",
49 | "output_type": "stream",
50 | "text": [
51 | "1.91 µs ± 5.27 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)\n"
52 | ]
53 | }
54 | ],
55 | "source": [
56 | "%timeit my_sum(my_lst)"
57 | ]
58 | },
59 | {
60 | "cell_type": "code",
61 | "execution_count": 4,
62 | "id": "f1668eb8-30c1-4210-a0e2-9bc214e3a74f",
63 | "metadata": {},
64 | "outputs": [
65 | {
66 | "name": "stdout",
67 | "output_type": "stream",
68 | "text": [
69 | "345 ns ± 2.09 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)\n"
70 | ]
71 | }
72 | ],
73 | "source": [
74 | "%timeit sum(my_lst)"
75 | ]
76 | },
77 | {
78 | "cell_type": "code",
79 | "execution_count": 5,
80 | "id": "c3c04347-8b30-4932-916f-20c8a9abb4b8",
81 | "metadata": {},
82 | "outputs": [
83 | {
84 | "data": {
85 | "text/plain": [
86 | "0.1806282722513089"
87 | ]
88 | },
89 | "execution_count": 5,
90 | "metadata": {},
91 | "output_type": "execute_result"
92 | }
93 | ],
94 | "source": [
95 | "345/1910"
96 | ]
97 | },
98 | {
99 | "cell_type": "code",
100 | "execution_count": 6,
101 | "id": "748a5a4d-0651-4df1-914e-72a547623dda",
102 | "metadata": {
103 | "tags": []
104 | },
105 | "outputs": [],
106 | "source": [
107 | "def my_max(lst):\n",
108 | " lst_max = 0\n",
109 | " for item in lst:\n",
110 | " if item > lst_max:\n",
111 | " lst_max = item\n",
112 | " return lst_max"
113 | ]
114 | },
115 | {
116 | "cell_type": "code",
117 | "execution_count": 7,
118 | "id": "b527690c-2766-4006-9a50-d25d03160441",
119 | "metadata": {
120 | "tags": []
121 | },
122 | "outputs": [],
123 | "source": [
124 | "from random import randint\n",
125 | "my_lst = [randint(1, 500) for i in range(100)]"
126 | ]
127 | },
128 | {
129 | "cell_type": "code",
130 | "execution_count": 8,
131 | "id": "b0c229ae-e6ec-4e6b-8e95-26642011ce35",
132 | "metadata": {},
133 | "outputs": [
134 | {
135 | "name": "stdout",
136 | "output_type": "stream",
137 | "text": [
138 | "1.26 µs ± 5.15 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)\n"
139 | ]
140 | }
141 | ],
142 | "source": [
143 | "%timeit my_max(my_lst)"
144 | ]
145 | },
146 | {
147 | "cell_type": "code",
148 | "execution_count": 9,
149 | "id": "78730e11-6383-430e-a216-98129b441280",
150 | "metadata": {},
151 | "outputs": [
152 | {
153 | "name": "stdout",
154 | "output_type": "stream",
155 | "text": [
156 | "533 ns ± 2.58 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)\n"
157 | ]
158 | }
159 | ],
160 | "source": [
161 | "%timeit max(my_lst)"
162 | ]
163 | },
164 | {
165 | "cell_type": "code",
166 | "execution_count": 10,
167 | "id": "9de583c8-0002-4eb5-9295-5b18b0662100",
168 | "metadata": {},
169 | "outputs": [
170 | {
171 | "data": {
172 | "text/plain": [
173 | "0.423015873015873"
174 | ]
175 | },
176 | "execution_count": 10,
177 | "metadata": {},
178 | "output_type": "execute_result"
179 | }
180 | ],
181 | "source": [
182 | "533/1260"
183 | ]
184 | },
185 | {
186 | "cell_type": "markdown",
187 | "id": "239e776e-d7b9-4f13-9dc8-a2f441e30fc5",
188 | "metadata": {
189 | "tags": []
190 | },
191 | "source": [
192 | "## Local caching"
193 | ]
194 | },
195 | {
196 | "cell_type": "code",
197 | "execution_count": 11,
198 | "id": "140c9410-f93e-4ed6-b72d-544853fbce05",
199 | "metadata": {},
200 | "outputs": [],
201 | "source": [
202 | "class Rectangle:\n",
203 | " def __init__(self):\n",
204 | " self.width = 10\n",
205 | " self.height = 20\n",
206 | " \n",
207 | "rec = Rectangle()"
208 | ]
209 | },
210 | {
211 | "cell_type": "code",
212 | "execution_count": 12,
213 | "id": "7076963f-1cdf-4b12-a8ff-6c8b079bce29",
214 | "metadata": {},
215 | "outputs": [],
216 | "source": [
217 | "def calc_fun(rec):\n",
218 | " s = 0\n",
219 | " for i in range(1000):\n",
220 | " s = s + (rec.width + rec.height)\n",
221 | " return s"
222 | ]
223 | },
224 | {
225 | "cell_type": "code",
226 | "execution_count": 13,
227 | "id": "91fe09c7-e52a-4f38-ae21-e4094531ca7a",
228 | "metadata": {},
229 | "outputs": [
230 | {
231 | "name": "stdout",
232 | "output_type": "stream",
233 | "text": [
234 | "41.7 µs ± 193 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)\n"
235 | ]
236 | }
237 | ],
238 | "source": [
239 | "%timeit calc_fun(rec)"
240 | ]
241 | },
242 | {
243 | "cell_type": "code",
244 | "execution_count": 14,
245 | "id": "24242c1d-7a2e-4169-a636-a41dcd803be8",
246 | "metadata": {
247 | "tags": []
248 | },
249 | "outputs": [],
250 | "source": [
251 | "def calc_fun_eff(rec):\n",
252 | " s = 1\n",
253 | " width = rec.width\n",
254 | " height = rec.height\n",
255 | " for i in range(1000):\n",
256 | " s = s + (width + height)\n",
257 | " return s"
258 | ]
259 | },
260 | {
261 | "cell_type": "code",
262 | "execution_count": 15,
263 | "id": "4ab06101-b814-484c-a113-edd4fa1b6974",
264 | "metadata": {},
265 | "outputs": [
266 | {
267 | "name": "stdout",
268 | "output_type": "stream",
269 | "text": [
270 | "28.6 µs ± 191 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)\n"
271 | ]
272 | }
273 | ],
274 | "source": [
275 | "%timeit calc_fun_eff(rec)"
276 | ]
277 | },
278 | {
279 | "cell_type": "code",
280 | "execution_count": 16,
281 | "id": "71b472a2-a35b-4a63-8bb3-4a6e8e946fab",
282 | "metadata": {},
283 | "outputs": [
284 | {
285 | "data": {
286 | "text/plain": [
287 | "0.6858513189448441"
288 | ]
289 | },
290 | "execution_count": 16,
291 | "metadata": {},
292 | "output_type": "execute_result"
293 | }
294 | ],
295 | "source": [
296 | "28.6/41.7"
297 | ]
298 | },
299 | {
300 | "cell_type": "markdown",
301 | "id": "eedce670-e847-45d8-9d89-4b7d75d635ba",
302 | "metadata": {
303 | "tags": []
304 | },
305 | "source": [
306 | "## Redundant function calls"
307 | ]
308 | },
309 | {
310 | "cell_type": "code",
311 | "execution_count": 20,
312 | "id": "57f86a4c-1ea5-4874-810c-333ef5f22ef8",
313 | "metadata": {},
314 | "outputs": [],
315 | "source": [
316 | "class Person:\n",
317 | " def __init__(self):\n",
318 | " self._name = 'saeed'\n",
319 | " self.full_name = 'saeed'\n",
320 | " \n",
321 | " @property\n",
322 | " def name(self):\n",
323 | " return self._name\n",
324 | " \n",
325 | " @name.setter\n",
326 | " def name(self, value):\n",
327 | " self._name = value\n",
328 | "\n",
329 | "p = Person()"
330 | ]
331 | },
332 | {
333 | "cell_type": "code",
334 | "execution_count": 18,
335 | "id": "f43f6d30-b7af-4b76-b89f-e6d02412fe81",
336 | "metadata": {},
337 | "outputs": [
338 | {
339 | "name": "stdout",
340 | "output_type": "stream",
341 | "text": [
342 | "43.5 ns ± 0.281 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)\n"
343 | ]
344 | }
345 | ],
346 | "source": [
347 | "%timeit p.name"
348 | ]
349 | },
350 | {
351 | "cell_type": "code",
352 | "execution_count": 19,
353 | "id": "e5537a11-82d4-43ea-9300-652e581a8f14",
354 | "metadata": {},
355 | "outputs": [
356 | {
357 | "name": "stdout",
358 | "output_type": "stream",
359 | "text": [
360 | "55.4 ns ± 0.302 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)\n"
361 | ]
362 | }
363 | ],
364 | "source": [
365 | "%timeit p.name = 'saeed saeed'"
366 | ]
367 | },
368 | {
369 | "cell_type": "code",
370 | "execution_count": 21,
371 | "id": "65306737-1a26-44f7-8a81-d081e3571bd4",
372 | "metadata": {},
373 | "outputs": [
374 | {
375 | "name": "stdout",
376 | "output_type": "stream",
377 | "text": [
378 | "20 ns ± 0.0898 ns per loop (mean ± std. dev. of 7 runs, 100,000,000 loops each)\n"
379 | ]
380 | }
381 | ],
382 | "source": [
383 | "%timeit p.full_name"
384 | ]
385 | },
386 | {
387 | "cell_type": "code",
388 | "execution_count": 22,
389 | "id": "6c225872-c8a7-466c-a197-59ebe508d56a",
390 | "metadata": {},
391 | "outputs": [
392 | {
393 | "name": "stdout",
394 | "output_type": "stream",
395 | "text": [
396 | "21.9 ns ± 0.139 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)\n"
397 | ]
398 | }
399 | ],
400 | "source": [
401 | "%timeit p.full_name = 'saeed saeed'"
402 | ]
403 | }
404 | ],
405 | "metadata": {
406 | "kernelspec": {
407 | "display_name": "Python 3 (ipykernel)",
408 | "language": "python",
409 | "name": "python3"
410 | },
411 | "language_info": {
412 | "codemirror_mode": {
413 | "name": "ipython",
414 | "version": 3
415 | },
416 | "file_extension": ".py",
417 | "mimetype": "text/x-python",
418 | "name": "python",
419 | "nbconvert_exporter": "python",
420 | "pygments_lexer": "ipython3",
421 | "version": "3.9.12"
422 | }
423 | },
424 | "nbformat": 4,
425 | "nbformat_minor": 5
426 | }
427 |
--------------------------------------------------------------------------------
/pythonics/csv/csv_example.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "id": "prospective-surge",
6 | "metadata": {},
7 | "source": [
8 | "# Read & Write CSV files"
9 | ]
10 | },
11 | {
12 | "cell_type": "markdown",
13 | "id": "diverse-organization",
14 | "metadata": {},
15 | "source": [
16 | "### Two ways\n",
17 | "* pandas\n",
18 | "* csv library"
19 | ]
20 | },
21 | {
22 | "cell_type": "markdown",
23 | "id": "historical-hands",
24 | "metadata": {},
25 | "source": [
26 | "#### Pandas"
27 | ]
28 | },
29 | {
30 | "cell_type": "code",
31 | "execution_count": 1,
32 | "id": "referenced-helicopter",
33 | "metadata": {},
34 | "outputs": [
35 | {
36 | "data": {
37 | "text/html": [
38 | "
\n",
39 | "\n",
52 | "
\n",
53 | " \n",
54 | " \n",
55 | " | \n",
56 | " First Name | \n",
57 | " Last Name | \n",
58 | " Age | \n",
59 | " Grade | \n",
60 | " Address | \n",
61 | "
\n",
62 | " \n",
63 | " \n",
64 | " \n",
65 | " | 0 | \n",
66 | " Saeed | \n",
67 | " Isa | \n",
68 | " 30 | \n",
69 | " 100 | \n",
70 | " Haifa | \n",
71 | "
\n",
72 | " \n",
73 | " | 1 | \n",
74 | " Salam | \n",
75 | " Khatib-Isa | \n",
76 | " 10 | \n",
77 | " 60 | \n",
78 | " Baghdad | \n",
79 | "
\n",
80 | " \n",
81 | " | 2 | \n",
82 | " Nasim | \n",
83 | " Ali | \n",
84 | " 60 | \n",
85 | " 98 | \n",
86 | " Qahera | \n",
87 | "
\n",
88 | " \n",
89 | " | 3 | \n",
90 | " Ahmad | \n",
91 | " Manna | \n",
92 | " 32 | \n",
93 | " 88 | \n",
94 | " Tunis | \n",
95 | "
\n",
96 | " \n",
97 | " | 4 | \n",
98 | " Rabi | \n",
99 | " Sabi | \n",
100 | " 40 | \n",
101 | " 65 | \n",
102 | " Italy | \n",
103 | "
\n",
104 | " \n",
105 | "
\n",
106 | "
"
107 | ],
108 | "text/plain": [
109 | " First Name Last Name Age Grade Address\n",
110 | "0 Saeed Isa 30 100 Haifa\n",
111 | "1 Salam Khatib-Isa 10 60 Baghdad\n",
112 | "2 Nasim Ali 60 98 Qahera\n",
113 | "3 Ahmad Manna 32 88 Tunis\n",
114 | "4 Rabi Sabi 40 65 Italy"
115 | ]
116 | },
117 | "execution_count": 1,
118 | "metadata": {},
119 | "output_type": "execute_result"
120 | }
121 | ],
122 | "source": [
123 | "# Read CSV file\n",
124 | "import pandas as pd\n",
125 | "df = pd.read_csv(\"data.csv\")\n",
126 | "df"
127 | ]
128 | },
129 | {
130 | "cell_type": "markdown",
131 | "id": "animated-import",
132 | "metadata": {},
133 | "source": [
134 | "https://youtu.be/f4e8v1NRdHs"
135 | ]
136 | },
137 | {
138 | "cell_type": "code",
139 | "execution_count": 2,
140 | "id": "plastic-wilderness",
141 | "metadata": {},
142 | "outputs": [
143 | {
144 | "data": {
145 | "text/html": [
146 | "\n",
147 | "\n",
160 | "
\n",
161 | " \n",
162 | " \n",
163 | " | \n",
164 | " FirstName | \n",
165 | " LastName | \n",
166 | " Age | \n",
167 | "
\n",
168 | " \n",
169 | " \n",
170 | " \n",
171 | " | 0 | \n",
172 | " Layan | \n",
173 | " Haj | \n",
174 | " 20 | \n",
175 | "
\n",
176 | " \n",
177 | " | 1 | \n",
178 | " Muhammed | \n",
179 | " Khalaily | \n",
180 | " 50 | \n",
181 | "
\n",
182 | " \n",
183 | " | 2 | \n",
184 | " Shdwan | \n",
185 | " Kriem | \n",
186 | " 33 | \n",
187 | "
\n",
188 | " \n",
189 | "
\n",
190 | "
"
191 | ],
192 | "text/plain": [
193 | " FirstName LastName Age\n",
194 | "0 Layan Haj 20\n",
195 | "1 Muhammed Khalaily 50\n",
196 | "2 Shdwan Kriem 33"
197 | ]
198 | },
199 | "execution_count": 2,
200 | "metadata": {},
201 | "output_type": "execute_result"
202 | }
203 | ],
204 | "source": [
205 | "# Writing csv\n",
206 | "data = [['Layan', 'Haj', 20], ['Muhammed', 'Khalaily', 50], ['Shdwan', 'Kriem', 33]]\n",
207 | "df2 = pd.DataFrame(data=data, columns=['FirstName', 'LastName', 'Age'])\n",
208 | "df2"
209 | ]
210 | },
211 | {
212 | "cell_type": "code",
213 | "execution_count": 3,
214 | "id": "animal-frost",
215 | "metadata": {},
216 | "outputs": [],
217 | "source": [
218 | "df2.to_csv('data2.csv', index=False)"
219 | ]
220 | },
221 | {
222 | "cell_type": "markdown",
223 | "id": "modern-dublin",
224 | "metadata": {},
225 | "source": [
226 | "#### CSV library"
227 | ]
228 | },
229 | {
230 | "cell_type": "code",
231 | "execution_count": 4,
232 | "id": "common-economy",
233 | "metadata": {},
234 | "outputs": [],
235 | "source": [
236 | "import csv"
237 | ]
238 | },
239 | {
240 | "cell_type": "code",
241 | "execution_count": 5,
242 | "id": "green-bristol",
243 | "metadata": {},
244 | "outputs": [
245 | {
246 | "name": "stdout",
247 | "output_type": "stream",
248 | "text": [
249 | "['First Name', ' Last Name', ' Age', ' Grade', ' Address']\n",
250 | "['Saeed', ' Isa', ' 30', ' 100', ' Haifa']\n",
251 | "['Salam', ' Khatib-Isa', ' 10', ' 60', ' Baghdad']\n",
252 | "['Nasim', ' Ali', ' 60', ' 98', ' Qahera']\n",
253 | "['Ahmad', ' Manna', ' 32', ' 88', ' Tunis']\n",
254 | "['Rabi', ' Sabi', ' 40', ' 65', ' Italy']\n"
255 | ]
256 | }
257 | ],
258 | "source": [
259 | "# Each line is list\n",
260 | "with open('data.csv', 'r') as fd:\n",
261 | " csv_reader = csv.reader(fd)\n",
262 | " for r in csv_reader:\n",
263 | " print(r)"
264 | ]
265 | },
266 | {
267 | "cell_type": "code",
268 | "execution_count": 6,
269 | "id": "associate-determination",
270 | "metadata": {},
271 | "outputs": [],
272 | "source": [
273 | "# How can we check the header ?"
274 | ]
275 | },
276 | {
277 | "cell_type": "code",
278 | "execution_count": 8,
279 | "id": "printable-juice",
280 | "metadata": {},
281 | "outputs": [
282 | {
283 | "name": "stdout",
284 | "output_type": "stream",
285 | "text": [
286 | "header: ['First Name', ' Last Name', ' Age', ' Grade', ' Address']\n",
287 | "data: ['Saeed', ' Isa', ' 30', ' 100', ' Haifa']\n",
288 | "data: ['Salam', ' Khatib-Isa', ' 10', ' 60', ' Baghdad']\n",
289 | "data: ['Nasim', ' Ali', ' 60', ' 98', ' Qahera']\n",
290 | "data: ['Ahmad', ' Manna', ' 32', ' 88', ' Tunis']\n",
291 | "data: ['Rabi', ' Sabi', ' 40', ' 65', ' Italy']\n"
292 | ]
293 | }
294 | ],
295 | "source": [
296 | "# Each line is list\n",
297 | "with open('data.csv', 'r') as fd:\n",
298 | " csv_reader = csv.reader(fd)\n",
299 | " for i, r in enumerate(csv_reader):\n",
300 | " if i == 0:\n",
301 | " print('header:', r)\n",
302 | " else:\n",
303 | " print('data:', r)"
304 | ]
305 | },
306 | {
307 | "cell_type": "code",
308 | "execution_count": 9,
309 | "id": "worse-programmer",
310 | "metadata": {},
311 | "outputs": [
312 | {
313 | "name": "stdout",
314 | "output_type": "stream",
315 | "text": [
316 | "{'First Name': 'Saeed', ' Last Name': ' Isa', ' Age': ' 30', ' Grade': ' 100', ' Address': ' Haifa'}\n",
317 | "{'First Name': 'Salam', ' Last Name': ' Khatib-Isa', ' Age': ' 10', ' Grade': ' 60', ' Address': ' Baghdad'}\n",
318 | "{'First Name': 'Nasim', ' Last Name': ' Ali', ' Age': ' 60', ' Grade': ' 98', ' Address': ' Qahera'}\n",
319 | "{'First Name': 'Ahmad', ' Last Name': ' Manna', ' Age': ' 32', ' Grade': ' 88', ' Address': ' Tunis'}\n",
320 | "{'First Name': 'Rabi', ' Last Name': ' Sabi', ' Age': ' 40', ' Grade': ' 65', ' Address': ' Italy'}\n"
321 | ]
322 | }
323 | ],
324 | "source": [
325 | "# Each line is dictionary\n",
326 | "with open('data.csv', 'r') as fd:\n",
327 | " csv_reader = csv.DictReader(fd)\n",
328 | " for r in csv_reader:\n",
329 | " print(r)"
330 | ]
331 | },
332 | {
333 | "cell_type": "code",
334 | "execution_count": 10,
335 | "id": "sudden-railway",
336 | "metadata": {},
337 | "outputs": [],
338 | "source": [
339 | "# Writing csv\n",
340 | "with open('data3.csv', 'w') as fd:\n",
341 | " csv_writer = csv.writer(fd)\n",
342 | " csv_writer.writerow(['Full Name', 'Day', 'Month'])\n",
343 | " csv_writer.writerow(['Saeed Isa', 15, 'July'])\n",
344 | " csv_writer.writerow(['Salam Isa-Khatib', 6, 'Feb'])"
345 | ]
346 | }
347 | ],
348 | "metadata": {
349 | "kernelspec": {
350 | "display_name": "Python 3",
351 | "language": "python",
352 | "name": "python3"
353 | },
354 | "language_info": {
355 | "codemirror_mode": {
356 | "name": "ipython",
357 | "version": 3
358 | },
359 | "file_extension": ".py",
360 | "mimetype": "text/x-python",
361 | "name": "python",
362 | "nbconvert_exporter": "python",
363 | "pygments_lexer": "ipython3",
364 | "version": "3.8.3"
365 | }
366 | },
367 | "nbformat": 4,
368 | "nbformat_minor": 5
369 | }
370 |
--------------------------------------------------------------------------------
/styling/styling.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Headers\n",
8 | "***"
9 | ]
10 | },
11 | {
12 | "cell_type": "markdown",
13 | "metadata": {},
14 | "source": [
15 | "# Header1"
16 | ]
17 | },
18 | {
19 | "cell_type": "markdown",
20 | "metadata": {},
21 | "source": [
22 | "## Header2"
23 | ]
24 | },
25 | {
26 | "cell_type": "markdown",
27 | "metadata": {},
28 | "source": [
29 | "### Header3"
30 | ]
31 | },
32 | {
33 | "cell_type": "markdown",
34 | "metadata": {},
35 | "source": [
36 | "#### Header4"
37 | ]
38 | },
39 | {
40 | "cell_type": "markdown",
41 | "metadata": {},
42 | "source": [
43 | "##### Header5"
44 | ]
45 | },
46 | {
47 | "cell_type": "markdown",
48 | "metadata": {},
49 | "source": [
50 | "###### Header6"
51 | ]
52 | },
53 | {
54 | "cell_type": "markdown",
55 | "metadata": {},
56 | "source": [
57 | "nomral text"
58 | ]
59 | },
60 | {
61 | "cell_type": "markdown",
62 | "metadata": {},
63 | "source": [
64 | "***\n",
65 | "# Text styling\n",
66 | "---"
67 | ]
68 | },
69 | {
70 | "cell_type": "markdown",
71 | "metadata": {},
72 | "source": [
73 | "### Bolding\n",
74 | "Bolding is done by surrounding the word/line with ** or __ : \n",
75 | "\n",
76 | "**Bolding this asterisk**\n",
77 | "\n",
78 | "__Bolding using underscore__"
79 | ]
80 | },
81 | {
82 | "cell_type": "markdown",
83 | "metadata": {},
84 | "source": [
85 | "### Italic\n",
86 | "\n",
87 | "Italic is done by surrounding the word/line with * or _ : \n",
88 | "\n",
89 | "*Italic with one asterisk*\n",
90 | "\n",
91 | "_Italic with underscore_"
92 | ]
93 | },
94 | {
95 | "cell_type": "markdown",
96 | "metadata": {},
97 | "source": [
98 | "### Italic and Bold\n",
99 | "surrounding with 3 * or 3 _ ==> ***Example***"
100 | ]
101 | },
102 | {
103 | "cell_type": "markdown",
104 | "metadata": {},
105 | "source": [
106 | "### STRIKETHROUGH\n",
107 | "surrounding with 2 ~ : ~~example~~"
108 | ]
109 | },
110 | {
111 | "cell_type": "markdown",
112 | "metadata": {},
113 | "source": [
114 | "### Break line\n",
115 | "Use \\
to break the line like this one
everything here will be next line
and new line here"
116 | ]
117 | },
118 | {
119 | "cell_type": "markdown",
120 | "metadata": {},
121 | "source": [
122 | "*** \n",
123 | "# Block quating\n",
124 | "***"
125 | ]
126 | },
127 | {
128 | "cell_type": "markdown",
129 | "metadata": {},
130 | "source": [
131 | "### BLOCK Quate\n",
132 | "use > to start writing code\n",
133 | "> this is some text for block quate\n",
134 | "\n",
135 | "> The second line of quate
\n",
136 | "> final line"
137 | ]
138 | },
139 | {
140 | "cell_type": "markdown",
141 | "metadata": {},
142 | "source": [
143 | "### Nested Block quates\n",
144 | "use > multiple times for each internal block\n",
145 | "> first blcok quate \n",
146 | ">> This is nested block quate\n",
147 | ">>> Third nested block quate\n",
148 | ">>>> Ooo! this is the fourth!!!"
149 | ]
150 | },
151 | {
152 | "cell_type": "markdown",
153 | "metadata": {},
154 | "source": [
155 | "use > multiple times for each internal block and enter between 2 lines to separate\n",
156 | "\n",
157 | "> first blcok quate \n",
158 | "\n",
159 | ">> This is nested block quate\n",
160 | "\n",
161 | ">>> Third nested block quate\n",
162 | "\n",
163 | ">>>> Ooo! this is the fourth!!!"
164 | ]
165 | },
166 | {
167 | "cell_type": "markdown",
168 | "metadata": {},
169 | "source": [
170 | "*** \n",
171 | "# Split lines\n",
172 | "***"
173 | ]
174 | },
175 | {
176 | "cell_type": "markdown",
177 | "metadata": {},
178 | "source": [
179 | "Splitting is by using 3 * or 3 - or 3 _\n",
180 | "\n",
181 | "***\n",
182 | "___\n",
183 | "\n",
184 | "---"
185 | ]
186 | },
187 | {
188 | "cell_type": "markdown",
189 | "metadata": {},
190 | "source": [
191 | "***\n",
192 | "# List \n",
193 | "### 1. Ordered and Unordered\n",
194 | "### 2. Tasks list\n",
195 | "***"
196 | ]
197 | },
198 | {
199 | "cell_type": "markdown",
200 | "metadata": {},
201 | "source": [
202 | "### Ordered list\n",
203 | "use number and .\n",
204 | "1. item1\n",
205 | "2. item2\n",
206 | "3. item3\n",
207 | "4. ..."
208 | ]
209 | },
210 | {
211 | "cell_type": "markdown",
212 | "metadata": {},
213 | "source": [
214 | "### Unordered list\n",
215 | "use -\n",
216 | "- item1 \n",
217 | "- item2\n",
218 | "- item3\n",
219 | "- ..."
220 | ]
221 | },
222 | {
223 | "cell_type": "markdown",
224 | "metadata": {},
225 | "source": [
226 | "### Tasks list\n",
227 | "\n",
228 | "use -/number and \\[ \\]\n",
229 | "\n",
230 | "- [ ] task1\n",
231 | "- [x] task2\n",
232 | "- [ ] task3\n",
233 | "\n",
234 | "or \n",
235 | "\n",
236 | "1. [ ] task1\n",
237 | "2. [ ] task2\n",
238 | "3. [x] task3\n"
239 | ]
240 | },
241 | {
242 | "cell_type": "markdown",
243 | "metadata": {},
244 | "source": [
245 | "#### Sub-lists\n",
246 | "use \\
\n",
247 | "1. Item1
\n",
248 | "a. sub-item1 1
\n",
249 | "b. sub-item1 2
\n",
250 | "c. sub-item1 3\n",
251 | "2. Item2"
252 | ]
253 | },
254 | {
255 | "cell_type": "markdown",
256 | "metadata": {},
257 | "source": [
258 | "***\n",
259 | "# Links\n",
260 | "***"
261 | ]
262 | },
263 | {
264 | "cell_type": "markdown",
265 | "metadata": {},
266 | "source": [
267 | "Add a link by using posting link\n",
268 | "\n",
269 | "https://www.anaconda.com/products/individual\n"
270 | ]
271 | },
272 | {
273 | "cell_type": "markdown",
274 | "metadata": {},
275 | "source": [
276 | "to **style** link add \\[something\\](link)\n",
277 | "\n",
278 | "[Anaconda downloads](https://www.anaconda.com/products/individual)"
279 | ]
280 | },
281 | {
282 | "cell_type": "markdown",
283 | "metadata": {},
284 | "source": [
285 | "***\n",
286 | "# Coding examples\n",
287 | "***"
288 | ]
289 | },
290 | {
291 | "cell_type": "markdown",
292 | "metadata": {},
293 | "source": [
294 | "Use single quate \\` and 3\\` as follows\n",
295 | "\n",
296 | "` some code example below`\n",
297 | "\n",
298 | "```\n",
299 | "import pandas as pd\n",
300 | "df = pd.DataFrame( )\n",
301 | "print(df.shape)\n",
302 | "```"
303 | ]
304 | },
305 | {
306 | "cell_type": "markdown",
307 | "metadata": {},
308 | "source": [
309 | "#### styling per programming language\n",
310 | "Put programming language after the first 3\\` for code styling\n",
311 | "\n",
312 | "`Some python code below`\n",
313 | "\n",
314 | "```python \n",
315 | "import pandas as pd\n",
316 | "df = pd.DataFrame( )\n",
317 | "print(df.shape)\n",
318 | "```"
319 | ]
320 | },
321 | {
322 | "cell_type": "markdown",
323 | "metadata": {},
324 | "source": [
325 | "***\n",
326 | "# Tables\n",
327 | "***"
328 | ]
329 | },
330 | {
331 | "cell_type": "markdown",
332 | "metadata": {},
333 | "source": [
334 | "use your styling capabilties :)\n",
335 | "\n",
336 | "|COLUMN1|COLUMN2|COLUMN3|\n",
337 | "|-------|-------|-------|\n",
338 | "|x |y |z |\n",
339 | "| VAL | OK | What! |\n",
340 | "| 1 | 2 | 7 |"
341 | ]
342 | },
343 | {
344 | "cell_type": "markdown",
345 | "metadata": {},
346 | "source": [
347 | "### Centering table \n",
348 | "for centered Use :-:
\n",
349 | "for left centered use — or :-
\n",
350 | "for right centered use -:
\n",
351 | "\n",
352 | "\n",
353 | "|COLUMN1|COLUMN2|COLUMN3|\n",
354 | "| :---: | :---: | :---: |\n",
355 | "|x |y |z |\n",
356 | "| VAL | OK | What! |\n",
357 | "| 1 | 2 | 7 |\n",
358 | "\n",
359 | "|COLUMN1|COLUMN2|COLUMN3|\n",
360 | "| :--- | :--- | :--- |\n",
361 | "|x |y |z |\n",
362 | "| VAL | OK | What! |\n",
363 | "| 1 | 2 | 7 |\n",
364 | "\n",
365 | "|COLUMN1|COLUMN2|COLUMN3|\n",
366 | "| ---: | ---: | ---: |\n",
367 | "|x |y |z |\n",
368 | "| VAL | OK | What! |\n",
369 | "| 1 | 2 | 7 |"
370 | ]
371 | },
372 | {
373 | "cell_type": "markdown",
374 | "metadata": {},
375 | "source": [
376 | "***\n",
377 | "# Image!!\n",
378 | "***"
379 | ]
380 | },
381 | {
382 | "cell_type": "markdown",
383 | "metadata": {},
384 | "source": [
385 | ""
386 | ]
387 | },
388 | {
389 | "cell_type": "markdown",
390 | "metadata": {},
391 | "source": [
392 | ""
393 | ]
394 | },
395 | {
396 | "cell_type": "markdown",
397 | "metadata": {},
398 | "source": [
399 | "***\n",
400 | "# HTML tricks\n",
401 | "***"
402 | ]
403 | },
404 | {
405 | "cell_type": "markdown",
406 | "metadata": {},
407 | "source": [
408 | "### Text coloring\n",
409 | "\n",
410 | "The next text is **red** using html tags\n",
411 | "\n",
412 | "or blue \n",
413 | "\n",
414 | "or ***green*** \n",
415 | "\n",
416 | "or ***pink*** \n",
417 | "\n",
418 | "or ***yellow*** \n",
419 | "\n"
420 | ]
421 | },
422 | {
423 | "cell_type": "markdown",
424 | "metadata": {},
425 | "source": [
426 | "### Text font family\n",
427 | "\n",
428 | "Changing font family ***I'M learning newww thingggssssss*** \n",
429 | "\n"
430 | ]
431 | },
432 | {
433 | "cell_type": "markdown",
434 | "metadata": {},
435 | "source": [
436 | "***\n",
437 | "# Cell styling\n",
438 | "***"
439 | ]
440 | },
441 | {
442 | "cell_type": "markdown",
443 | "metadata": {},
444 | "source": [
445 | "Highlight this TEXT with blue background color and white text color\n",
446 | "\n",
447 | "Highlight this **text** with red background color and white text color\n",
448 | "\n",
449 | "Highlight this *TEXT* with black background color and yellow text color
and nice font family text\n"
450 | ]
451 | },
452 | {
453 | "cell_type": "markdown",
454 | "metadata": {},
455 | "source": [
456 | "### Alert boxes"
457 | ]
458 | },
459 | {
460 | "cell_type": "markdown",
461 | "metadata": {},
462 | "source": [
463 | "### Success --> Green\n",
464 | "\n",
465 | "\n",
466 | "Green box means success/good things will happen/happened/happens\n",
467 | "
\n"
468 | ]
469 | },
470 | {
471 | "cell_type": "markdown",
472 | "metadata": {},
473 | "source": [
474 | "### Fail/Error/Danger --> Red\n",
475 | "\n",
476 | "\n",
477 | "Red box means something failed :( or DANGER!!! or Error \n",
478 | "
"
479 | ]
480 | },
481 | {
482 | "cell_type": "markdown",
483 | "metadata": {},
484 | "source": [
485 | "### Warning/Note --> Yellow\n",
486 | "\n",
487 | "\n",
488 | "Please note! or check this warning\n",
489 | "
"
490 | ]
491 | },
492 | {
493 | "cell_type": "markdown",
494 | "metadata": {},
495 | "source": [
496 | "### information/calm down --> blue\n",
497 | "\n",
498 | "\n",
499 | "This color is nice to calm down or for information\n",
500 | "
"
501 | ]
502 | }
503 | ],
504 | "metadata": {
505 | "kernelspec": {
506 | "display_name": "Python 3",
507 | "language": "python",
508 | "name": "python3"
509 | },
510 | "language_info": {
511 | "codemirror_mode": {
512 | "name": "ipython",
513 | "version": 3
514 | },
515 | "file_extension": ".py",
516 | "mimetype": "text/x-python",
517 | "name": "python",
518 | "nbconvert_exporter": "python",
519 | "pygments_lexer": "ipython3",
520 | "version": "3.8.3"
521 | }
522 | },
523 | "nbformat": 4,
524 | "nbformat_minor": 4
525 | }
526 |
--------------------------------------------------------------------------------
/math/math_example.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 1,
6 | "id": "amended-enforcement",
7 | "metadata": {},
8 | "outputs": [],
9 | "source": [
10 | "import math"
11 | ]
12 | },
13 | {
14 | "cell_type": "markdown",
15 | "id": "talented-representative",
16 | "metadata": {},
17 | "source": [
18 | "# Mathematical constants"
19 | ]
20 | },
21 | {
22 | "cell_type": "code",
23 | "execution_count": 3,
24 | "id": "removed-washer",
25 | "metadata": {},
26 | "outputs": [
27 | {
28 | "name": "stdout",
29 | "output_type": "stream",
30 | "text": [
31 | "Pi: 3.141592653589793\n",
32 | "E: 2.718281828459045\n",
33 | "Inf: inf\n",
34 | "Tau: 6.283185307179586\n",
35 | "NAN: nan\n"
36 | ]
37 | }
38 | ],
39 | "source": [
40 | "print('Pi:', math.pi)\n",
41 | "print('E:', math.e)\n",
42 | "print('Inf:', math.inf)\n",
43 | "print('Tau:', math.tau)\n",
44 | "print('NAN:', math.nan)"
45 | ]
46 | },
47 | {
48 | "cell_type": "markdown",
49 | "id": "quiet-whale",
50 | "metadata": {},
51 | "source": [
52 | "# Mathematical tasks"
53 | ]
54 | },
55 | {
56 | "cell_type": "code",
57 | "execution_count": 5,
58 | "id": "charming-uncle",
59 | "metadata": {},
60 | "outputs": [
61 | {
62 | "name": "stdout",
63 | "output_type": "stream",
64 | "text": [
65 | "Abs: 5678.0\n",
66 | "SQRT: 5.0\n",
67 | "Pow: 100.0\n",
68 | "Ceil: 10\n",
69 | "Floor: 9\n"
70 | ]
71 | }
72 | ],
73 | "source": [
74 | "print('Abs:', math.fabs(-5678))\n",
75 | "print('SQRT:', math.sqrt(25))\n",
76 | "print('Pow:', math.pow(10, 2))\n",
77 | "print('Ceil:', math.ceil(9.123))\n",
78 | "print('Floor:', math.floor(9.123))"
79 | ]
80 | },
81 | {
82 | "cell_type": "code",
83 | "execution_count": 6,
84 | "id": "major-worse",
85 | "metadata": {},
86 | "outputs": [
87 | {
88 | "name": "stdout",
89 | "output_type": "stream",
90 | "text": [
91 | "Sin: 0.0\n",
92 | "Cos: 1.0\n",
93 | "Tan: 0.0\n"
94 | ]
95 | }
96 | ],
97 | "source": [
98 | "print('Sin:', math.sin(0))\n",
99 | "print('Cos:', math.cos(0))\n",
100 | "print('Tan:', math.tan(0))"
101 | ]
102 | },
103 | {
104 | "cell_type": "code",
105 | "execution_count": 7,
106 | "id": "elect-updating",
107 | "metadata": {},
108 | "outputs": [
109 | {
110 | "name": "stdout",
111 | "output_type": "stream",
112 | "text": [
113 | "Logarithm: 4.605170185988092\n",
114 | "Logarithm2: 6.643856189774724\n",
115 | "Logarithm10: 2.0\n",
116 | "Exp: 148.4131591025766\n",
117 | "Factorial: 24\n"
118 | ]
119 | }
120 | ],
121 | "source": [
122 | "print('Logarithm:', math.log(100))\n",
123 | "print('Logarithm2:', math.log2(100))\n",
124 | "print('Logarithm10:', math.log10(100))\n",
125 | "print('Exp:', math.exp(5))\n",
126 | "print('Factorial:', math.factorial(4))"
127 | ]
128 | },
129 | {
130 | "cell_type": "code",
131 | "execution_count": 8,
132 | "id": "neutral-oxygen",
133 | "metadata": {},
134 | "outputs": [
135 | {
136 | "name": "stdout",
137 | "output_type": "stream",
138 | "text": [
139 | "Help on built-in module math:\n",
140 | "\n",
141 | "NAME\n",
142 | " math\n",
143 | "\n",
144 | "DESCRIPTION\n",
145 | " This module provides access to the mathematical functions\n",
146 | " defined by the C standard.\n",
147 | "\n",
148 | "FUNCTIONS\n",
149 | " acos(x, /)\n",
150 | " Return the arc cosine (measured in radians) of x.\n",
151 | " \n",
152 | " acosh(x, /)\n",
153 | " Return the inverse hyperbolic cosine of x.\n",
154 | " \n",
155 | " asin(x, /)\n",
156 | " Return the arc sine (measured in radians) of x.\n",
157 | " \n",
158 | " asinh(x, /)\n",
159 | " Return the inverse hyperbolic sine of x.\n",
160 | " \n",
161 | " atan(x, /)\n",
162 | " Return the arc tangent (measured in radians) of x.\n",
163 | " \n",
164 | " atan2(y, x, /)\n",
165 | " Return the arc tangent (measured in radians) of y/x.\n",
166 | " \n",
167 | " Unlike atan(y/x), the signs of both x and y are considered.\n",
168 | " \n",
169 | " atanh(x, /)\n",
170 | " Return the inverse hyperbolic tangent of x.\n",
171 | " \n",
172 | " ceil(x, /)\n",
173 | " Return the ceiling of x as an Integral.\n",
174 | " \n",
175 | " This is the smallest integer >= x.\n",
176 | " \n",
177 | " comb(n, k, /)\n",
178 | " Number of ways to choose k items from n items without repetition and without order.\n",
179 | " \n",
180 | " Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates\n",
181 | " to zero when k > n.\n",
182 | " \n",
183 | " Also called the binomial coefficient because it is equivalent\n",
184 | " to the coefficient of k-th term in polynomial expansion of the\n",
185 | " expression (1 + x)**n.\n",
186 | " \n",
187 | " Raises TypeError if either of the arguments are not integers.\n",
188 | " Raises ValueError if either of the arguments are negative.\n",
189 | " \n",
190 | " copysign(x, y, /)\n",
191 | " Return a float with the magnitude (absolute value) of x but the sign of y.\n",
192 | " \n",
193 | " On platforms that support signed zeros, copysign(1.0, -0.0)\n",
194 | " returns -1.0.\n",
195 | " \n",
196 | " cos(x, /)\n",
197 | " Return the cosine of x (measured in radians).\n",
198 | " \n",
199 | " cosh(x, /)\n",
200 | " Return the hyperbolic cosine of x.\n",
201 | " \n",
202 | " degrees(x, /)\n",
203 | " Convert angle x from radians to degrees.\n",
204 | " \n",
205 | " dist(p, q, /)\n",
206 | " Return the Euclidean distance between two points p and q.\n",
207 | " \n",
208 | " The points should be specified as sequences (or iterables) of\n",
209 | " coordinates. Both inputs must have the same dimension.\n",
210 | " \n",
211 | " Roughly equivalent to:\n",
212 | " sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))\n",
213 | " \n",
214 | " erf(x, /)\n",
215 | " Error function at x.\n",
216 | " \n",
217 | " erfc(x, /)\n",
218 | " Complementary error function at x.\n",
219 | " \n",
220 | " exp(x, /)\n",
221 | " Return e raised to the power of x.\n",
222 | " \n",
223 | " expm1(x, /)\n",
224 | " Return exp(x)-1.\n",
225 | " \n",
226 | " This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.\n",
227 | " \n",
228 | " fabs(x, /)\n",
229 | " Return the absolute value of the float x.\n",
230 | " \n",
231 | " factorial(x, /)\n",
232 | " Find x!.\n",
233 | " \n",
234 | " Raise a ValueError if x is negative or non-integral.\n",
235 | " \n",
236 | " floor(x, /)\n",
237 | " Return the floor of x as an Integral.\n",
238 | " \n",
239 | " This is the largest integer <= x.\n",
240 | " \n",
241 | " fmod(x, y, /)\n",
242 | " Return fmod(x, y), according to platform C.\n",
243 | " \n",
244 | " x % y may differ.\n",
245 | " \n",
246 | " frexp(x, /)\n",
247 | " Return the mantissa and exponent of x, as pair (m, e).\n",
248 | " \n",
249 | " m is a float and e is an int, such that x = m * 2.**e.\n",
250 | " If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.\n",
251 | " \n",
252 | " fsum(seq, /)\n",
253 | " Return an accurate floating point sum of values in the iterable seq.\n",
254 | " \n",
255 | " Assumes IEEE-754 floating point arithmetic.\n",
256 | " \n",
257 | " gamma(x, /)\n",
258 | " Gamma function at x.\n",
259 | " \n",
260 | " gcd(x, y, /)\n",
261 | " greatest common divisor of x and y\n",
262 | " \n",
263 | " hypot(...)\n",
264 | " hypot(*coordinates) -> value\n",
265 | " \n",
266 | " Multidimensional Euclidean distance from the origin to a point.\n",
267 | " \n",
268 | " Roughly equivalent to:\n",
269 | " sqrt(sum(x**2 for x in coordinates))\n",
270 | " \n",
271 | " For a two dimensional point (x, y), gives the hypotenuse\n",
272 | " using the Pythagorean theorem: sqrt(x*x + y*y).\n",
273 | " \n",
274 | " For example, the hypotenuse of a 3/4/5 right triangle is:\n",
275 | " \n",
276 | " >>> hypot(3.0, 4.0)\n",
277 | " 5.0\n",
278 | " \n",
279 | " isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)\n",
280 | " Determine whether two floating point numbers are close in value.\n",
281 | " \n",
282 | " rel_tol\n",
283 | " maximum difference for being considered \"close\", relative to the\n",
284 | " magnitude of the input values\n",
285 | " abs_tol\n",
286 | " maximum difference for being considered \"close\", regardless of the\n",
287 | " magnitude of the input values\n",
288 | " \n",
289 | " Return True if a is close in value to b, and False otherwise.\n",
290 | " \n",
291 | " For the values to be considered close, the difference between them\n",
292 | " must be smaller than at least one of the tolerances.\n",
293 | " \n",
294 | " -inf, inf and NaN behave similarly to the IEEE 754 Standard. That\n",
295 | " is, NaN is not close to anything, even itself. inf and -inf are\n",
296 | " only close to themselves.\n",
297 | " \n",
298 | " isfinite(x, /)\n",
299 | " Return True if x is neither an infinity nor a NaN, and False otherwise.\n",
300 | " \n",
301 | " isinf(x, /)\n",
302 | " Return True if x is a positive or negative infinity, and False otherwise.\n",
303 | " \n",
304 | " isnan(x, /)\n",
305 | " Return True if x is a NaN (not a number), and False otherwise.\n",
306 | " \n",
307 | " isqrt(n, /)\n",
308 | " Return the integer part of the square root of the input.\n",
309 | " \n",
310 | " ldexp(x, i, /)\n",
311 | " Return x * (2**i).\n",
312 | " \n",
313 | " This is essentially the inverse of frexp().\n",
314 | " \n",
315 | " lgamma(x, /)\n",
316 | " Natural logarithm of absolute value of Gamma function at x.\n",
317 | " \n",
318 | " log(...)\n",
319 | " log(x, [base=math.e])\n",
320 | " Return the logarithm of x to the given base.\n",
321 | " \n",
322 | " If the base not specified, returns the natural logarithm (base e) of x.\n",
323 | " \n",
324 | " log10(x, /)\n",
325 | " Return the base 10 logarithm of x.\n",
326 | " \n",
327 | " log1p(x, /)\n",
328 | " Return the natural logarithm of 1+x (base e).\n",
329 | " \n",
330 | " The result is computed in a way which is accurate for x near zero.\n",
331 | " \n",
332 | " log2(x, /)\n",
333 | " Return the base 2 logarithm of x.\n",
334 | " \n",
335 | " modf(x, /)\n",
336 | " Return the fractional and integer parts of x.\n",
337 | " \n",
338 | " Both results carry the sign of x and are floats.\n",
339 | " \n",
340 | " perm(n, k=None, /)\n",
341 | " Number of ways to choose k items from n items without repetition and with order.\n",
342 | " \n",
343 | " Evaluates to n! / (n - k)! when k <= n and evaluates\n",
344 | " to zero when k > n.\n",
345 | " \n",
346 | " If k is not specified or is None, then k defaults to n\n",
347 | " and the function returns n!.\n",
348 | " \n",
349 | " Raises TypeError if either of the arguments are not integers.\n",
350 | " Raises ValueError if either of the arguments are negative.\n",
351 | " \n",
352 | " pow(x, y, /)\n",
353 | " Return x**y (x to the power of y).\n",
354 | " \n",
355 | " prod(iterable, /, *, start=1)\n",
356 | " Calculate the product of all the elements in the input iterable.\n",
357 | " \n",
358 | " The default start value for the product is 1.\n",
359 | " \n",
360 | " When the iterable is empty, return the start value. This function is\n",
361 | " intended specifically for use with numeric values and may reject\n",
362 | " non-numeric types.\n",
363 | " \n",
364 | " radians(x, /)\n",
365 | " Convert angle x from degrees to radians.\n",
366 | " \n",
367 | " remainder(x, y, /)\n",
368 | " Difference between x and the closest integer multiple of y.\n",
369 | " \n",
370 | " Return x - n*y where n*y is the closest integer multiple of y.\n",
371 | " In the case where x is exactly halfway between two multiples of\n",
372 | " y, the nearest even value of n is used. The result is always exact.\n",
373 | " \n",
374 | " sin(x, /)\n",
375 | " Return the sine of x (measured in radians).\n",
376 | " \n",
377 | " sinh(x, /)\n",
378 | " Return the hyperbolic sine of x.\n",
379 | " \n",
380 | " sqrt(x, /)\n",
381 | " Return the square root of x.\n",
382 | " \n",
383 | " tan(x, /)\n",
384 | " Return the tangent of x (measured in radians).\n",
385 | " \n",
386 | " tanh(x, /)\n",
387 | " Return the hyperbolic tangent of x.\n",
388 | " \n",
389 | " trunc(x, /)\n",
390 | " Truncates the Real x to the nearest Integral toward 0.\n",
391 | " \n",
392 | " Uses the __trunc__ magic method.\n",
393 | "\n",
394 | "DATA\n",
395 | " e = 2.718281828459045\n",
396 | " inf = inf\n",
397 | " nan = nan\n",
398 | " pi = 3.141592653589793\n",
399 | " tau = 6.283185307179586\n",
400 | "\n",
401 | "FILE\n",
402 | " (built-in)\n",
403 | "\n",
404 | "\n"
405 | ]
406 | }
407 | ],
408 | "source": [
409 | "help(math)"
410 | ]
411 | }
412 | ],
413 | "metadata": {
414 | "kernelspec": {
415 | "display_name": "Python 3",
416 | "language": "python",
417 | "name": "python3"
418 | },
419 | "language_info": {
420 | "codemirror_mode": {
421 | "name": "ipython",
422 | "version": 3
423 | },
424 | "file_extension": ".py",
425 | "mimetype": "text/x-python",
426 | "name": "python",
427 | "nbconvert_exporter": "python",
428 | "pygments_lexer": "ipython3",
429 | "version": "3.8.3"
430 | }
431 | },
432 | "nbformat": 4,
433 | "nbformat_minor": 5
434 | }
435 |
--------------------------------------------------------------------------------
/re_library/re_library.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "id": "velvet-terry",
6 | "metadata": {},
7 | "source": [
8 | "# Regular Expressions - re library"
9 | ]
10 | },
11 | {
12 | "cell_type": "code",
13 | "execution_count": 1,
14 | "id": "neutral-dover",
15 | "metadata": {},
16 | "outputs": [],
17 | "source": [
18 | "import re"
19 | ]
20 | },
21 | {
22 | "cell_type": "markdown",
23 | "id": "lasting-withdrawal",
24 | "metadata": {},
25 | "source": [
26 | "## re useful functions\n",
27 | "\n",
28 | "* findall ==> Returns a list containing all matches\n",
29 | "* search ==> Returns a *Match object* if there is a match anywhere in the string\n",
30 | " * Match object - homework :)\n",
31 | "* split ==> Returns a list where the string has been split at each match\n",
32 | "* match ==> Returns a *Match object* if there is a match, otherwise None object"
33 | ]
34 | },
35 | {
36 | "cell_type": "markdown",
37 | "id": "golden-sheep",
38 | "metadata": {},
39 | "source": [
40 | "## Simple and Basic pattern\n",
41 | "\n",
42 | "### Ordinary characters"
43 | ]
44 | },
45 | {
46 | "cell_type": "code",
47 | "execution_count": null,
48 | "id": "international-terminology",
49 | "metadata": {},
50 | "outputs": [],
51 | "source": [
52 | "txt = 'Saeed'\n",
53 | "pattern = 'Saeed'\n",
54 | "if re.match(pattern, txt):\n",
55 | " print('Yes!!! match')\n",
56 | "else:\n",
57 | " print('Noo!!! does not match')"
58 | ]
59 | },
60 | {
61 | "cell_type": "markdown",
62 | "id": "mighty-behalf",
63 | "metadata": {},
64 | "source": [
65 | "## Special Characters"
66 | ]
67 | },
68 | {
69 | "cell_type": "markdown",
70 | "id": "verified-pipeline",
71 | "metadata": {},
72 | "source": [
73 | "## . \n",
74 | "##### A period, Matches **any single** character except the newline character"
75 | ]
76 | },
77 | {
78 | "cell_type": "code",
79 | "execution_count": null,
80 | "id": "stone-zambia",
81 | "metadata": {},
82 | "outputs": [],
83 | "source": [
84 | "txt = \"Saeed\"\n",
85 | "pattern = \"S.e.d\"\n",
86 | "m = re.findall(pattern, txt)\n",
87 | "print(m)"
88 | ]
89 | },
90 | {
91 | "cell_type": "markdown",
92 | "id": "smart-firewall",
93 | "metadata": {},
94 | "source": [
95 | "***\n",
96 | "## ^ \n",
97 | "##### A caret, Matches the **start** of the string."
98 | ]
99 | },
100 | {
101 | "cell_type": "code",
102 | "execution_count": null,
103 | "id": "serial-mention",
104 | "metadata": {},
105 | "outputs": [],
106 | "source": [
107 | "txt = \"Saeed loves programming\"\n",
108 | "pattern = \"^Saeed\"\n",
109 | "m = re.findall(pattern, txt)\n",
110 | "print(m)"
111 | ]
112 | },
113 | {
114 | "cell_type": "code",
115 | "execution_count": null,
116 | "id": "metallic-antique",
117 | "metadata": {},
118 | "outputs": [],
119 | "source": [
120 | "# Won't work\n",
121 | "txt = \"Saeed loves programming\"\n",
122 | "pattern = \"^loves\" \n",
123 | "m = re.findall(pattern, txt)\n",
124 | "print(m)"
125 | ]
126 | },
127 | {
128 | "cell_type": "markdown",
129 | "id": "amazing-pressing",
130 | "metadata": {},
131 | "source": [
132 | "***\n",
133 | "## $ \n",
134 | "##### Matches the end of string"
135 | ]
136 | },
137 | {
138 | "cell_type": "code",
139 | "execution_count": null,
140 | "id": "mental-surprise",
141 | "metadata": {},
142 | "outputs": [],
143 | "source": [
144 | "txt = \"Saeed loves programming\"\n",
145 | "pattern = \"programming$\" \n",
146 | "m = re.findall(pattern, txt)\n",
147 | "print(m)"
148 | ]
149 | },
150 | {
151 | "cell_type": "code",
152 | "execution_count": null,
153 | "id": "innovative-cambodia",
154 | "metadata": {},
155 | "outputs": [],
156 | "source": [
157 | "txt = \"Saeed loves programming\"\n",
158 | "pattern = \"ing$\"\n",
159 | "m = re.findall(pattern, txt)\n",
160 | "print(m)"
161 | ]
162 | },
163 | {
164 | "cell_type": "code",
165 | "execution_count": null,
166 | "id": "turned-moscow",
167 | "metadata": {},
168 | "outputs": [],
169 | "source": [
170 | "txt = \"Saeed loves programming\"\n",
171 | "pattern = \"Saeed$\" \n",
172 | "m = re.findall(pattern, txt)\n",
173 | "print(m)"
174 | ]
175 | },
176 | {
177 | "cell_type": "markdown",
178 | "id": "smoking-monroe",
179 | "metadata": {},
180 | "source": [
181 | "***\n",
182 | "## [19bG] \n",
183 | "##### Matches 1 or 9 or b or G\n",
184 | "## [a-zA-Z0-9]\n",
185 | "##### Matches any letter from (a to z) or (A to Z) or (0 to 9)."
186 | ]
187 | },
188 | {
189 | "cell_type": "code",
190 | "execution_count": null,
191 | "id": "packed-eating",
192 | "metadata": {},
193 | "outputs": [],
194 | "source": [
195 | "txt = \"Saeed is 30 years old\"\n",
196 | "pattern = \"[S3of]\" \n",
197 | "m = re.findall(pattern, txt)\n",
198 | "print(m)"
199 | ]
200 | },
201 | {
202 | "cell_type": "code",
203 | "execution_count": null,
204 | "id": "nervous-railway",
205 | "metadata": {},
206 | "outputs": [],
207 | "source": [
208 | "txt = \"Saeed is 30 years old\"\n",
209 | "pattern = \"[1-9]\" \n",
210 | "m = re.findall(pattern, txt)\n",
211 | "print(m)"
212 | ]
213 | },
214 | {
215 | "cell_type": "code",
216 | "execution_count": null,
217 | "id": "failing-municipality",
218 | "metadata": {},
219 | "outputs": [],
220 | "source": [
221 | "txt = \"Saeed is 30 years old\"\n",
222 | "pattern = \"[a-f0-4A-T]aeed\" \n",
223 | "m = re.findall(pattern, txt)\n",
224 | "print(m)"
225 | ]
226 | },
227 | {
228 | "cell_type": "markdown",
229 | "id": "average-snapshot",
230 | "metadata": {},
231 | "source": [
232 | "## using caret ^ in [ ] will look for complementary set"
233 | ]
234 | },
235 | {
236 | "cell_type": "code",
237 | "execution_count": null,
238 | "id": "cellular-bankruptcy",
239 | "metadata": {},
240 | "outputs": [],
241 | "source": [
242 | "txt = \"4 years\"\n",
243 | "pattern = \"[^9] years\" \n",
244 | "m = re.findall(pattern, txt)\n",
245 | "print(m)"
246 | ]
247 | },
248 | {
249 | "cell_type": "code",
250 | "execution_count": null,
251 | "id": "polyphonic-battlefield",
252 | "metadata": {},
253 | "outputs": [],
254 | "source": [
255 | "txt = \"4 years\"\n",
256 | "pattern = \"[^4] years\" \n",
257 | "m = re.findall(pattern, txt)\n",
258 | "print(m)"
259 | ]
260 | },
261 | {
262 | "cell_type": "markdown",
263 | "id": "comic-large",
264 | "metadata": {},
265 | "source": [
266 | "***\n",
267 | "## \\ \n",
268 | "##### Backslash - 2 options\n",
269 | "* Option1: special characters, such as (\\t, \\s, ...)\n",
270 | "* Option2: not special character, treated like any other character or removes special meaning (\\\\\\s, \\\\\\t, ...)"
271 | ]
272 | },
273 | {
274 | "cell_type": "code",
275 | "execution_count": null,
276 | "id": "central-witness",
277 | "metadata": {},
278 | "outputs": [],
279 | "source": [
280 | "# Option 1 - treating \\ with special charachter (\\s mean space)\n",
281 | "txt = \"Subscribe saeed channel\"\n",
282 | "pattern = \"Subscribe\\saeed\" \n",
283 | "m = re.findall(pattern, txt)\n",
284 | "print(m)\n"
285 | ]
286 | },
287 | {
288 | "cell_type": "code",
289 | "execution_count": null,
290 | "id": "super-costs",
291 | "metadata": {},
292 | "outputs": [],
293 | "source": [
294 | "txt = \"Subscribe saeed channel\"\n",
295 | "pattern = \"Subscribe\\ssaeed\" \n",
296 | "m = re.findall(pattern, txt)\n",
297 | "print(m)"
298 | ]
299 | },
300 | {
301 | "cell_type": "code",
302 | "execution_count": null,
303 | "id": "inside-investigator",
304 | "metadata": {},
305 | "outputs": [],
306 | "source": [
307 | "# Option 2 - treating \\ like any other character\n",
308 | "txt = \"Subscribe [s]aeed channel\"\n",
309 | "pattern = \"Subscribe \\[s\\]aeed\"\n",
310 | "m = re.findall(pattern, txt)\n",
311 | "print(m)"
312 | ]
313 | },
314 | {
315 | "cell_type": "markdown",
316 | "id": "composite-debate",
317 | "metadata": {},
318 | "source": [
319 | "***\n",
320 | "## more special characters\n",
321 | "* \\t - Matches tab\n",
322 | "* \\n - Matches newline\n",
323 | "* \\A - Matches only at the start of the string\n",
324 | "* \\Z - Matches only at the end of the string\n"
325 | ]
326 | },
327 | {
328 | "cell_type": "code",
329 | "execution_count": null,
330 | "id": "unauthorized-grave",
331 | "metadata": {},
332 | "outputs": [],
333 | "source": [
334 | "# reminder ^ sign \n",
335 | "txt = \"Saeed loves programming\"\n",
336 | "pattern = \"\\ASaeed\" \n",
337 | "m = re.findall(pattern, txt)\n",
338 | "print(m)"
339 | ]
340 | },
341 | {
342 | "cell_type": "code",
343 | "execution_count": null,
344 | "id": "median-arlington",
345 | "metadata": {},
346 | "outputs": [],
347 | "source": [
348 | "# reminder $ sign\n",
349 | "txt = \"Saeed loves programming\"\n",
350 | "pattern = \"ming\\Z\" \n",
351 | "m = re.findall(pattern, txt)\n",
352 | "print(m)"
353 | ]
354 | },
355 | {
356 | "cell_type": "markdown",
357 | "id": "architectural-county",
358 | "metadata": {},
359 | "source": [
360 | "***\n",
361 | "## Next video\n",
362 | "* \\w, \\W, \\s, \\S, \\d, \\D, \n",
363 | "* Repetions: *, + , ?, {}\n",
364 | "* Examples\n",
365 | "***"
366 | ]
367 | },
368 | {
369 | "cell_type": "markdown",
370 | "id": "light-tuner",
371 | "metadata": {},
372 | "source": [
373 | "***\n",
374 | "## \\w & \\W\n",
375 | "##### \\w: Matches any single letter, digit, or underscore\n",
376 | "##### \\W: Matches any character not part of \\w (complementary set)"
377 | ]
378 | },
379 | {
380 | "cell_type": "code",
381 | "execution_count": 2,
382 | "id": "alone-rhythm",
383 | "metadata": {},
384 | "outputs": [
385 | {
386 | "name": "stdout",
387 | "output_type": "stream",
388 | "text": [
389 | "['Saeed loves programming']\n"
390 | ]
391 | }
392 | ],
393 | "source": [
394 | "txt = \"Saeed loves programming\"\n",
395 | "pattern = \"Saeed loves \\wrogramming\" \n",
396 | "# similar to [0-9a-zA-Z_]\n",
397 | "m = re.findall(pattern, txt)\n",
398 | "print(m)"
399 | ]
400 | },
401 | {
402 | "cell_type": "code",
403 | "execution_count": 3,
404 | "id": "southeast-crowd",
405 | "metadata": {},
406 | "outputs": [
407 | {
408 | "name": "stdout",
409 | "output_type": "stream",
410 | "text": [
411 | "['Saeed loves %rogramming']\n"
412 | ]
413 | }
414 | ],
415 | "source": [
416 | "txt = \"Saeed loves %rogramming\"\n",
417 | "pattern = \"Saeed loves \\Wrogramming\" \n",
418 | "# similar to [^0-9a-zA-Z_]\n",
419 | "m = re.findall(pattern, txt)\n",
420 | "print(m)"
421 | ]
422 | },
423 | {
424 | "cell_type": "markdown",
425 | "id": "scenic-mountain",
426 | "metadata": {},
427 | "source": [
428 | "***\n",
429 | "## \\d & \\D\n",
430 | "##### \\d: Matches decimal digit 0-9\n",
431 | "##### \\D: Matches any character that is not a digit (complementary set)"
432 | ]
433 | },
434 | {
435 | "cell_type": "code",
436 | "execution_count": 4,
437 | "id": "balanced-spank",
438 | "metadata": {},
439 | "outputs": [
440 | {
441 | "name": "stdout",
442 | "output_type": "stream",
443 | "text": [
444 | "['4 years']\n"
445 | ]
446 | }
447 | ],
448 | "source": [
449 | "txt = \"4 years\"\n",
450 | "pattern = r\"\\d years\" \n",
451 | "# similar to [0-9]\n",
452 | "m = re.findall(pattern, txt)\n",
453 | "print(m)"
454 | ]
455 | },
456 | {
457 | "cell_type": "code",
458 | "execution_count": 6,
459 | "id": "julian-equilibrium",
460 | "metadata": {},
461 | "outputs": [
462 | {
463 | "name": "stdout",
464 | "output_type": "stream",
465 | "text": [
466 | "['% years']\n"
467 | ]
468 | }
469 | ],
470 | "source": [
471 | "txt = \"% years\" \n",
472 | "pattern = r\"\\D years\"\n",
473 | "# similar to [^0-9]\n",
474 | "m = re.findall(pattern, txt)\n",
475 | "print(m)"
476 | ]
477 | },
478 | {
479 | "cell_type": "markdown",
480 | "id": "simplified-actor",
481 | "metadata": {},
482 | "source": [
483 | "***\n",
484 | "## \\s & \\S\n",
485 | "##### \\s: Matches a single whitespace character like: space, newline, tab, return\n",
486 | "##### \\S: Matches any character that is not a single whitespace character (complementary set)"
487 | ]
488 | },
489 | {
490 | "cell_type": "code",
491 | "execution_count": 7,
492 | "id": "permanent-badge",
493 | "metadata": {},
494 | "outputs": [
495 | {
496 | "name": "stdout",
497 | "output_type": "stream",
498 | "text": [
499 | "['Saeed loves']\n"
500 | ]
501 | }
502 | ],
503 | "source": [
504 | "txt = \"Saeed loves programming\"\n",
505 | "pattern = \"Saeed\\sloves\" \n",
506 | "m = re.findall(pattern, txt)\n",
507 | "print(m)"
508 | ]
509 | },
510 | {
511 | "cell_type": "code",
512 | "execution_count": 10,
513 | "id": "lucky-directive",
514 | "metadata": {},
515 | "outputs": [
516 | {
517 | "name": "stdout",
518 | "output_type": "stream",
519 | "text": [
520 | "['Saeed9loves']\n"
521 | ]
522 | }
523 | ],
524 | "source": [
525 | "txt = \"Saeed-loves programming\"\n",
526 | "pattern = \"Saeed\\Sloves\" \n",
527 | "m = re.findall(pattern, txt)\n",
528 | "print(m)"
529 | ]
530 | },
531 | {
532 | "cell_type": "markdown",
533 | "id": "offshore-seeker",
534 | "metadata": {},
535 | "source": [
536 | "## Repeitions"
537 | ]
538 | },
539 | {
540 | "cell_type": "markdown",
541 | "id": "spoken-error",
542 | "metadata": {},
543 | "source": [
544 | "## +\n",
545 | "##### Checks if the preceding character appears **one or more** times starting from that position"
546 | ]
547 | },
548 | {
549 | "cell_type": "code",
550 | "execution_count": 11,
551 | "id": "outdoor-phone",
552 | "metadata": {},
553 | "outputs": [
554 | {
555 | "name": "stdout",
556 | "output_type": "stream",
557 | "text": [
558 | "['programmmmmmmming']\n"
559 | ]
560 | }
561 | ],
562 | "source": [
563 | "txt = \"programmmmmmmming\"\n",
564 | "pattern = \"program+ing\" \n",
565 | "m = re.findall(pattern, txt)\n",
566 | "print(m)"
567 | ]
568 | },
569 | {
570 | "cell_type": "code",
571 | "execution_count": 12,
572 | "id": "liquid-rough",
573 | "metadata": {},
574 | "outputs": [
575 | {
576 | "name": "stdout",
577 | "output_type": "stream",
578 | "text": [
579 | "['programmmmmmmming']\n"
580 | ]
581 | }
582 | ],
583 | "source": [
584 | "# will this work ?\n",
585 | "txt = \"programmmmmmmming\"\n",
586 | "pattern = \"progra\\w+ing\"\n",
587 | "m = re.findall(pattern, txt)\n",
588 | "print(m)"
589 | ]
590 | },
591 | {
592 | "cell_type": "code",
593 | "execution_count": 13,
594 | "id": "streaming-aruba",
595 | "metadata": {},
596 | "outputs": [
597 | {
598 | "name": "stdout",
599 | "output_type": "stream",
600 | "text": [
601 | "['programmmmmmmming']\n"
602 | ]
603 | }
604 | ],
605 | "source": [
606 | "# will this work ?\n",
607 | "txt = \"programmmmmmmming\"\n",
608 | "pattern = \"progra[a-z]+ing\" \n",
609 | "m = re.findall(pattern, txt)\n",
610 | "print(m)"
611 | ]
612 | },
613 | {
614 | "cell_type": "code",
615 | "execution_count": 14,
616 | "id": "junior-ensemble",
617 | "metadata": {},
618 | "outputs": [
619 | {
620 | "name": "stdout",
621 | "output_type": "stream",
622 | "text": [
623 | "[]\n"
624 | ]
625 | }
626 | ],
627 | "source": [
628 | "# This will not work!\n",
629 | "txt = \"programmmmmmmming\"\n",
630 | "pattern = \"progras+ing\" \n",
631 | "m = re.findall(pattern, txt)\n",
632 | "print(m)"
633 | ]
634 | },
635 | {
636 | "cell_type": "markdown",
637 | "id": "solved-killing",
638 | "metadata": {},
639 | "source": [
640 | "## *\n",
641 | "##### Checks if the preceding character appears **zero or more** times starting from that position"
642 | ]
643 | },
644 | {
645 | "cell_type": "code",
646 | "execution_count": 15,
647 | "id": "forbidden-grace",
648 | "metadata": {},
649 | "outputs": [
650 | {
651 | "name": "stdout",
652 | "output_type": "stream",
653 | "text": [
654 | "['programmmmmmmming']\n"
655 | ]
656 | }
657 | ],
658 | "source": [
659 | "txt = \"programmmmmmmming\"\n",
660 | "pattern = \"program*ing\" \n",
661 | "m = re.findall(pattern, txt)\n",
662 | "print(m)"
663 | ]
664 | },
665 | {
666 | "cell_type": "code",
667 | "execution_count": 16,
668 | "id": "entitled-night",
669 | "metadata": {},
670 | "outputs": [
671 | {
672 | "name": "stdout",
673 | "output_type": "stream",
674 | "text": [
675 | "['programmmmmmmming']\n"
676 | ]
677 | }
678 | ],
679 | "source": [
680 | "txt = \"programmmmmmmming\"\n",
681 | "pattern = \"program*f*ing\" \n",
682 | "m = re.findall(pattern, txt)\n",
683 | "print(m)"
684 | ]
685 | },
686 | {
687 | "cell_type": "markdown",
688 | "id": "composite-glance",
689 | "metadata": {},
690 | "source": [
691 | "## ?\n",
692 | "##### Checks if the preceding character appears **exactly zero or one** time starting from that position."
693 | ]
694 | },
695 | {
696 | "cell_type": "code",
697 | "execution_count": 17,
698 | "id": "broadband-audience",
699 | "metadata": {},
700 | "outputs": [
701 | {
702 | "name": "stdout",
703 | "output_type": "stream",
704 | "text": [
705 | "['programming']\n"
706 | ]
707 | }
708 | ],
709 | "source": [
710 | "txt = \"programming\"\n",
711 | "pattern = \"programm?ing\" \n",
712 | "m = re.findall(pattern, txt)\n",
713 | "print(m)"
714 | ]
715 | },
716 | {
717 | "cell_type": "code",
718 | "execution_count": 18,
719 | "id": "colored-pencil",
720 | "metadata": {},
721 | "outputs": [
722 | {
723 | "name": "stdout",
724 | "output_type": "stream",
725 | "text": [
726 | "['programming']\n"
727 | ]
728 | }
729 | ],
730 | "source": [
731 | "txt = \"programming\"\n",
732 | "pattern = \"programmf?ing\" \n",
733 | "m = re.findall(pattern, txt)\n",
734 | "print(m)"
735 | ]
736 | },
737 | {
738 | "cell_type": "markdown",
739 | "id": "gorgeous-commitment",
740 | "metadata": {},
741 | "source": [
742 | "## {}\n",
743 | "#### {x} Repeat exactly x number of times.\n",
744 | "#### {x,} Repeat at least x times or more.\n",
745 | "#### {x, y} Repeat at least x times but no more than y times."
746 | ]
747 | },
748 | {
749 | "cell_type": "code",
750 | "execution_count": 19,
751 | "id": "relevant-johnson",
752 | "metadata": {},
753 | "outputs": [
754 | {
755 | "name": "stdout",
756 | "output_type": "stream",
757 | "text": [
758 | "['programmmmming']\n"
759 | ]
760 | }
761 | ],
762 | "source": [
763 | "txt = \"programmmmming\"\n",
764 | "pattern = \"programm{2,}ing\" \n",
765 | "m = re.findall(pattern, txt)\n",
766 | "print(m)"
767 | ]
768 | },
769 | {
770 | "cell_type": "markdown",
771 | "id": "fitting-intro",
772 | "metadata": {},
773 | "source": [
774 | "## Examples"
775 | ]
776 | },
777 | {
778 | "cell_type": "code",
779 | "execution_count": 20,
780 | "id": "married-brazil",
781 | "metadata": {},
782 | "outputs": [
783 | {
784 | "name": "stdout",
785 | "output_type": "stream",
786 | "text": [
787 | "['saeed.isa90@gmail.com']\n"
788 | ]
789 | }
790 | ],
791 | "source": [
792 | "txt = 'Please contact me at: saeed.isa90@gmail.com'\n",
793 | "pattern1 = '[a-zA-Z0-9\\.\\_]+@[a-zA-Z0-9]+.com'\n",
794 | "m = re.findall(pattern1, txt)\n",
795 | "print(m)"
796 | ]
797 | },
798 | {
799 | "cell_type": "code",
800 | "execution_count": 21,
801 | "id": "ranging-graph",
802 | "metadata": {},
803 | "outputs": [
804 | {
805 | "name": "stdout",
806 | "output_type": "stream",
807 | "text": [
808 | "['saeed.isa90@gmail.com']\n"
809 | ]
810 | }
811 | ],
812 | "source": [
813 | "txt = 'Please contact me at: saeed.isa90@gmail.com'\n",
814 | "pattern2 = '[\\w\\.]+@[\\w]+.com'\n",
815 | "m = re.findall(pattern2, txt)\n",
816 | "print(m)"
817 | ]
818 | },
819 | {
820 | "cell_type": "code",
821 | "execution_count": 22,
822 | "id": "pleasant-genre",
823 | "metadata": {},
824 | "outputs": [
825 | {
826 | "name": "stdout",
827 | "output_type": "stream",
828 | "text": [
829 | "['101010', '202020', '404040', '505050']\n"
830 | ]
831 | }
832 | ],
833 | "source": [
834 | "txt = '101010 202020 Saeed 404040 505050 Isa'\n",
835 | "pattern1 = '[0-9]+'\n",
836 | "m = re.findall(pattern1, txt)\n",
837 | "print(m)"
838 | ]
839 | },
840 | {
841 | "cell_type": "code",
842 | "execution_count": 23,
843 | "id": "welcome-confusion",
844 | "metadata": {},
845 | "outputs": [
846 | {
847 | "name": "stdout",
848 | "output_type": "stream",
849 | "text": [
850 | "['101010', '202020', '404040', '505050']\n"
851 | ]
852 | }
853 | ],
854 | "source": [
855 | "txt = '101010 202020 Saeed 404040 505050 Isa'\n",
856 | "pattern2 = '[\\d]+'\n",
857 | "m = re.findall(pattern2, txt)\n",
858 | "print(m)"
859 | ]
860 | }
861 | ],
862 | "metadata": {
863 | "kernelspec": {
864 | "display_name": "Python 3",
865 | "language": "python",
866 | "name": "python3"
867 | },
868 | "language_info": {
869 | "codemirror_mode": {
870 | "name": "ipython",
871 | "version": 3
872 | },
873 | "file_extension": ".py",
874 | "mimetype": "text/x-python",
875 | "name": "python",
876 | "nbconvert_exporter": "python",
877 | "pygments_lexer": "ipython3",
878 | "version": "3.8.3"
879 | }
880 | },
881 | "nbformat": 4,
882 | "nbformat_minor": 5
883 | }
884 |
--------------------------------------------------------------------------------