├── Lab ├── Mypackage │ ├── __init__.py │ ├── Listpackage │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── listops.cpython-311.pyc │ │ │ └── __init__.cpython-311.pyc │ │ └── listops.py │ ├── __pycache__ │ │ ├── Shapes.cpython-311.pyc │ │ └── __init__.cpython-311.pyc │ └── Shapes.py ├── 7_volume.py ├── 7_list_func.py ├── 1_divisbility.py ├── 3_array1.py ├── 15_flask │ ├── templates │ │ ├── failed.html │ │ ├── passed.html │ │ └── books.html │ ├── app2.py │ └── app1.py ├── 2_dictionary.py ├── 2_tuples.py ├── 2_list_comprehension.py ├── 3_array2.py ├── 8_sum.py ├── 4_iterable_sum.py ├── 2_lists.py ├── 8_list_multiplication.py ├── 4_moving_avg.py ├── 1_reverse.py ├── 12_pie_chart.py ├── 4_vandermonde.py ├── 12_histogram.py ├── 12_bargraph.py ├── 6_operator_overload.py ├── 9_file_handling.py ├── 5_vehicle.py ├── 14_scipy.py ├── 5_employee.py ├── 6_bank.py ├── 11_python_mysql.py ├── 13_pandas.py └── 10_calculatorGUI.py ├── README.md └── QB ├── Lambda ├── add_or_mul.py ├── values_of_string_is_6.py ├── num_or_not_using_lamba.py ├── sorttuple.py ├── nthelement.py └── marks_of_students.py ├── Pandas ├── dataframe.py ├── dataframe_obj_combine.py ├── dataframe_row.py ├── dataframe_prefix_suffix.py ├── dataframe_specific_row.py ├── dataframe_missing.py ├── dataframe_combine.py ├── dataframe_label.py ├── dataframe_3rows.py ├── merge_datasets.py ├── dataframe_mean.py ├── dataframe_greater_than.py ├── dataframe_cell_index.py ├── dataframe_select_rows.py ├── dataframe_insert_column.py ├── dataframe_append.py ├── dataframe_inner_join.py └── dataframe_left_join.py ├── Numpy ├── reverse_array.py ├── determinant.py ├── row_values.py ├── checkboard_pattern.py ├── outer_product.py ├── matrix_multiplication.py ├── centi_to_fahren.py ├── diagonal_sum.py ├── list_to_tuple.py ├── set_difference.py ├── frobenius.py ├── singular_val_decomp.py └── einstein_summation.py ├── GUI ├── tkinter_unresizable.py ├── tkinter_spinbox.py ├── tkinter_fontactions.py ├── tkinter_radiobutton.py ├── tkinter_text.py ├── tkinter_progressbar.py └── tkinter_exit.py ├── Random ├── random_seeded.py ├── random_list.py ├── zero_division.py └── random_hex.py ├── Decimal ├── decimal_float.py ├── round_off.py ├── rounding.py ├── shallow_copy.py └── deep_copy.py ├── Types ├── compiled.py └── user_defined.py ├── ClassesAndObjects ├── sortDictionaryByValue.py ├── integerToRomanNumeral.py ├── validParentheses.py ├── employeeData.py ├── Inventory.py ├── restaurant.py └── bankAccount.py ├── Matplotlib ├── barcahrt_using_dataframe.py ├── piechart_popularity.py ├── scatterplot.py ├── piecharttitle_popularity.py ├── men&women_togehter.py ├── error_bars_m&w.py ├── barchart_hori_popularity.py ├── barchart_popularity.py └── multidimensional_data.py └── file_handling.py /Lab/Mypackage/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Lab/Mypackage/Listpackage/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Python codes for Sem 4 2 | -------------------------------------------------------------------------------- /QB/Lambda/add_or_mul.py: -------------------------------------------------------------------------------- 1 | r = lambda a : a + 10 2 | print(r(10)) 3 | r = lambda x, y : x * y 4 | print(r(12, 4)) 5 | -------------------------------------------------------------------------------- /Lab/7_volume.py: -------------------------------------------------------------------------------- 1 | from Mypackage.Shapes import * 2 | 3 | sphere = Sphere(3) 4 | sphere.volume() 5 | 6 | cube = Cube(3) 7 | cube.volume() -------------------------------------------------------------------------------- /QB/Pandas/dataframe.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | df = pd.DataFrame({'X':[78,85,96,80,86], 'Y':[84,94,89,83,86],'Z':[86,97,96,72,83]}) 3 | print(df) -------------------------------------------------------------------------------- /Lab/7_list_func.py: -------------------------------------------------------------------------------- 1 | from Mypackage.Listpackage.listops import * 2 | 3 | compare([9, 10, 1, 0], [5, 6, 7, 8]) 4 | 5 | merge([1, 2, 3, 4], [5, 6, 7, 8]) -------------------------------------------------------------------------------- /Lab/Mypackage/__pycache__/Shapes.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akshayrathod205/Python_Sem-IV/HEAD/Lab/Mypackage/__pycache__/Shapes.cpython-311.pyc -------------------------------------------------------------------------------- /Lab/Mypackage/__pycache__/__init__.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akshayrathod205/Python_Sem-IV/HEAD/Lab/Mypackage/__pycache__/__init__.cpython-311.pyc -------------------------------------------------------------------------------- /QB/Numpy/reverse_array.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | x = np.arange(12, 38) 4 | print("Original array:") 5 | print(x) 6 | 7 | print("Reverse array:") 8 | x = x[ : : -1] 9 | print(x) -------------------------------------------------------------------------------- /Lab/Mypackage/Listpackage/__pycache__/listops.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akshayrathod205/Python_Sem-IV/HEAD/Lab/Mypackage/Listpackage/__pycache__/listops.cpython-311.pyc -------------------------------------------------------------------------------- /Lab/Mypackage/Listpackage/__pycache__/__init__.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akshayrathod205/Python_Sem-IV/HEAD/Lab/Mypackage/Listpackage/__pycache__/__init__.cpython-311.pyc -------------------------------------------------------------------------------- /QB/Numpy/determinant.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | a = np.array([[1, 2], [3, 4]]) 4 | print("Original array") 5 | print(a) 6 | 7 | result = np.linalg.det(a) 8 | print("Determinant: ", result) -------------------------------------------------------------------------------- /QB/Numpy/row_values.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | x = np.zeros((5, 5)) 4 | print("Original array: ") 5 | print(x) 6 | 7 | print("Row values ranging from 0 to 4") 8 | x += np.arange(5) 9 | print(x) -------------------------------------------------------------------------------- /QB/GUI/tkinter_unresizable.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | 3 | parent = tk.Tk() 4 | 5 | parent.title("Window") 6 | 7 | parent.resizable(0,0) #Not resizable windows 8 | 9 | parent.mainloop() 10 | -------------------------------------------------------------------------------- /QB/Numpy/checkboard_pattern.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | x = np.ones((3, 3)) 4 | print("Checboard pattern:") 5 | x = np.zeros((8, 8), dtype=int) 6 | x[1::2, ::2] = 1 7 | x[::2, 1::2] = 1 8 | print(x) -------------------------------------------------------------------------------- /QB/Numpy/outer_product.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | p = [[1, 0], [0, 1]] 4 | q = [[1, 2], [3, 4]] 5 | print("Original:") 6 | print(p) 7 | print(q) 8 | 9 | result = np.outer(p, q) 10 | print(result) -------------------------------------------------------------------------------- /Lab/1_divisbility.py: -------------------------------------------------------------------------------- 1 | start_num = 2000 2 | end_num = 3200 3 | count = start_num 4 | while count <= end_num: 5 | if count % 7 == 0 and not count % 5 == 0: 6 | print(count,'', sep = '-', end = '') 7 | count += 1 8 | -------------------------------------------------------------------------------- /QB/Numpy/matrix_multiplication.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | p = [[1, 0], [0, 1]] 4 | q = [[1, 2], [3, 4]] 5 | print("Original:") 6 | print(p) 7 | print(q) 8 | 9 | result = np.dot(p, q) 10 | print(result) -------------------------------------------------------------------------------- /Lab/3_array1.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | sample = np.array([[2, 4, 6, 8, 6], [23, 56, 45, 10, 83], [98, 12 ,34, 78, 78], [21, 63, 78, 84, 53]]) 3 | print(sample) 4 | 5 | new_array = sample[::2, 1::2] 6 | print(new_array) 7 | -------------------------------------------------------------------------------- /Lab/15_flask/templates/failed.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Failed 5 | 6 | 7 |

Failed

8 |

The result is: {{ result }}

9 | 10 | 11 | -------------------------------------------------------------------------------- /Lab/15_flask/templates/passed.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Passed 5 | 6 | 7 |

Passed

8 |

The result is: {{ result }}

9 | 10 | 11 | -------------------------------------------------------------------------------- /QB/Random/random_seeded.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | print("Seeded random number") 4 | print(random.Random().random()) 5 | print(random.Random(2).random()) 6 | 7 | print("Float between 0 and 1, excluding 1") 8 | print(random.random()) -------------------------------------------------------------------------------- /QB/Lambda/values_of_string_is_6.py: -------------------------------------------------------------------------------- 1 | 2 | weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] 3 | days = filter(lambda day: day if len(day)==6 else '', weekdays) 4 | 5 | for d in days: 6 | print(d) -------------------------------------------------------------------------------- /QB/Numpy/centi_to_fahren.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | fvalues = [0, 12, 45.21, 34, 99.91, 32] 3 | f = np.array(fvalues) 4 | print("Values in Fahrenheit:") 5 | print(f) 6 | print("Values in Centigrade:") 7 | print(np.round((5*f/9 - 5*32/9), 2)) -------------------------------------------------------------------------------- /QB/Numpy/diagonal_sum.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) 4 | print("Original array") 5 | print(a) 6 | 7 | result = np.trace(a) 8 | print("Condition number of matrix:") 9 | print(result) 10 | -------------------------------------------------------------------------------- /QB/Numpy/list_to_tuple.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | my_list = [1, 2, 3, 4, 5, 6, 7, 8] 4 | print("List to array:") 5 | print(np.asarray(my_list)) 6 | my_tuple = ([8, 4, 6], [1, 2, 3]) 7 | print("Tuple to array:") 8 | print(np.asarray(my_tuple)) -------------------------------------------------------------------------------- /Lab/2_dictionary.py: -------------------------------------------------------------------------------- 1 | websites = { 2 | 1: "www.yahoo.com", 3 | 2: "www.tsec.edu", 4 | 3: "www.asp.net", 5 | 4: "www.abcd.in" 6 | } 7 | website_suffixes = tuple(url.split(".")[-1] for url in websites.values()) 8 | print(website_suffixes) 9 | -------------------------------------------------------------------------------- /Lab/Mypackage/Listpackage/listops.py: -------------------------------------------------------------------------------- 1 | def compare(l1, l2): 2 | for i in range(len(l1)): 3 | if l1[i] >= l2[i]: 4 | return False 5 | return True 6 | 7 | def merge(l1, l2): 8 | l1.extend(l2) 9 | print(l1) 10 | 11 | -------------------------------------------------------------------------------- /QB/Numpy/set_difference.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | a = np.array([0, 10, 20, 40, 60, 80]) 3 | print("Array1: ", a) 4 | b = [10, 30, 40, 50, 70] 5 | print("Array2: ", b) 6 | print("Unique values in array1 that are not in array2:") 7 | print(np.setdiff1d(a, b)) 8 | -------------------------------------------------------------------------------- /QB/GUI/tkinter_spinbox.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | root = tk.Tk() 3 | text_var = tk.DoubleVar() 4 | spin_box = tk.Spinbox( 5 | root, 6 | from_=0.6, 7 | to=50.0, 8 | increment=.01, 9 | textvariable=text_var 10 | ) 11 | spin_box.pack() 12 | root.mainloop() 13 | -------------------------------------------------------------------------------- /QB/Numpy/frobenius.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) 4 | print("Original array") 5 | print(a) 6 | 7 | print("Frobenius norm and condition number:") 8 | print(np.linalg.norm(a, 'fro')) 9 | print(np.linalg.cond(a, 'fro')) -------------------------------------------------------------------------------- /Lab/2_tuples.py: -------------------------------------------------------------------------------- 1 | tuple = (4, 5, 6, 2, 3, 4, 5, 1, 2, 6, 4) 2 | data = { 3 | 1: tuple.count(1), 4 | 2: tuple.count(2), 5 | 3: tuple.count(3), 6 | 4: tuple.count(4), 7 | 5: tuple.count(5), 8 | 6: tuple.count(6) 9 | } 10 | print(data) 11 | -------------------------------------------------------------------------------- /Lab/2_list_comprehension.py: -------------------------------------------------------------------------------- 1 | list = ['x', 'y' ,'z'] 2 | pattern1 = [] 3 | pattern2 = [] 4 | [pattern1.append(list[i]*j) for i in range(len(list)) for j in range(1,4)] 5 | [pattern2.append(list[i]*j) for j in range(1,4) for i in range(len(list))] 6 | print(pattern1) 7 | print(pattern2) 8 | -------------------------------------------------------------------------------- /Lab/3_array2.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | print("Creating a 8X3 matrix") 4 | sample = np.arange(10, 34, 1) 5 | sample = sample.reshape(8 ,3) 6 | print(sample) 7 | 8 | print("Dividing the array into 4 sub arrays") 9 | subArray = np.split(sample, 4) 10 | print(subArray) 11 | -------------------------------------------------------------------------------- /QB/Lambda/num_or_not_using_lamba.py: -------------------------------------------------------------------------------- 1 | 2 | num = lambda q: q.replace('.','',1).isdigit() 3 | is_num = lambda r: num(r[1:]) if r[0]=='-' else num(r) 4 | 5 | 6 | print(is_num('26587') ,"\n", is_num('-12547') ,"\n", is_num('00') ,"\n", is_num('A001') ,"\n", is_num('-24587.11')) 7 | 8 | -------------------------------------------------------------------------------- /QB/Decimal/decimal_float.py: -------------------------------------------------------------------------------- 1 | import decimal 2 | 3 | print("Decimal from float") 4 | pi = decimal.Decimal(3.14159) 5 | print(pi) 6 | print(pi.as_tuple()) 7 | 8 | print("Decimal from string") 9 | num_str = decimal.Decimal("-123.25") 10 | print(num_str) 11 | print(num_str.as_tuple()) -------------------------------------------------------------------------------- /QB/Lambda/sorttuple.py: -------------------------------------------------------------------------------- 1 | 2 | subject_marks = [('English', 88), ('Science', 90), ('Maths', 97), ('Social sciences', 82)] 3 | print("Original list of tuples:") 4 | print(subject_marks) 5 | 6 | subject_marks.sort(key = lambda x: x[1]) 7 | print("\nSorting the List of Tuples:") 8 | print(subject_marks) -------------------------------------------------------------------------------- /QB/Pandas/dataframe_obj_combine.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | 3 | df1 = pd.DataFrame({'A': [None, 0, None], 'B': [3, 4, 5]}) 4 | df2 = pd.DataFrame({'A': [1, 1, 3], 'B': [3, None, 3]}) 5 | 6 | result = df1.combine_first(df2) 7 | result1 = df2.combine_first(df1) 8 | print(result) 9 | print(result1) -------------------------------------------------------------------------------- /QB/Pandas/dataframe_row.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | d = {'col1': [1, 4, 3, 4, 5], 'col2': [4, 5, 6, 7, 8], 'col3': [7, 8, 9, 0, 1]} 4 | df = pd.DataFrame(data=d) 5 | print("Original") 6 | print(df) 7 | 8 | print("Rows for column value = 4") 9 | print(df.loc[df['col1'] == 4]) -------------------------------------------------------------------------------- /QB/Pandas/dataframe_prefix_suffix.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | df = pd.DataFrame({'W':[68,75,86,80,66], 'X':[78,85,96,80,86], 'Y':[84,94,89,83,86], 'Z':[86,97,96,72,83]}) 3 | print(df) 4 | 5 | print("Add prefix") 6 | print(df.add_prefix("OO_")) 7 | 8 | print("Add suffix") 9 | print(df.add_suffix("_OO")) -------------------------------------------------------------------------------- /Lab/8_sum.py: -------------------------------------------------------------------------------- 1 | a = 30 2 | b = '12.5' 3 | try: 4 | result = a + b 5 | print(f"Sum: {result}") 6 | 7 | except TypeError: 8 | try: 9 | result = a + float(b) 10 | print(f"Sum: {result}") 11 | 12 | except ValueError: 13 | print("Something went wrong") -------------------------------------------------------------------------------- /QB/Random/random_list.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | print("List of random integers") 4 | population = range(0, 100) 5 | num_list = random.sample(population, 10) 6 | print(num_list) 7 | 8 | no_elements = 5 9 | print(f"Randomly select {no_elements} item(s) from list") 10 | result = random.sample(num_list, no_elements) 11 | print(result) -------------------------------------------------------------------------------- /QB/Decimal/round_off.py: -------------------------------------------------------------------------------- 1 | from decimal import Decimal 2 | 3 | def round_off(x): 4 | x_decimal = Decimal(str(x)) 5 | remainder = x_decimal.remainder_near(Decimal('0.10')) 6 | if abs(remainder) == Decimal('0.05'): 7 | return x_decimal 8 | else: 9 | return x_decimal - remainder 10 | 11 | print(round_off(4.78)) -------------------------------------------------------------------------------- /QB/Pandas/dataframe_specific_row.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | d = {'col1': [1, 4, 3, 4, 5], 'col2': [4, 5, 6, 7, 8], 'col3': [7, 8, 9, 0, 1]} 4 | df = pd.DataFrame(data=d) 5 | print("Original") 6 | print(df) 7 | 8 | print("Value of Row 1") 9 | print(df.iloc[0]) 10 | 11 | print("Value of Row 4") 12 | print(df.iloc[3]) -------------------------------------------------------------------------------- /QB/Types/compiled.py: -------------------------------------------------------------------------------- 1 | import types 2 | 3 | print("Check whether value is compiled code") 4 | code = compile("print('Hello World')", "sample", "exec") 5 | print(isinstance(code, types.CodeType)) 6 | print(isinstance("print(abs(-111))", types.MethodType)) 7 | 8 | print("Check whether value is in module") 9 | print(isinstance(types, types.MethodType)) -------------------------------------------------------------------------------- /QB/GUI/tkinter_fontactions.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | parent = tk.Tk() 3 | parent.title("FONT") 4 | label = tk.Label(parent,text = "Welcome to Python tkinter Basic exercises-", font =("Bold",10)) 5 | label.grid(column=0,row=0) 6 | my_label = tk.Label(parent, text="Hello", font=("Arial Bold", 70)) 7 | my_label.grid(column=0, row=10) 8 | parent.mainloop() 9 | -------------------------------------------------------------------------------- /QB/Pandas/dataframe_missing.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | 4 | sdata = {"c1":[120, 130 ,140, 150, np.nan, 170], "c2":[7, np.nan, 10, np.nan, 5.5, 16.5]} 5 | df = pd.DataFrame(sdata) 6 | df.index = pd.date_range('2023-01-04', periods=6) 7 | 8 | print("Original") 9 | print(df) 10 | 11 | print("After interpolate") 12 | print(df.interpolate()) -------------------------------------------------------------------------------- /QB/Numpy/singular_val_decomp.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | a = np.array([[1, 0, 0, 0, 2], [0, 0, 3, 0, 0], [0, 0, 0, 0, 0], [0, 2, 0, 0, 0]], dtype=np.float64) 3 | print("Original array:") 4 | print(a) 5 | 6 | U, s, V = np.linalg.svd(a, full_matrices=False) 7 | q, r = np.linalg.qr(a) 8 | print("Factor of array by Singular Value Decompostion") 9 | print("U =\n", U, "s = \n", s, "V = \n", V) -------------------------------------------------------------------------------- /Lab/4_iterable_sum.py: -------------------------------------------------------------------------------- 1 | def sum_iterable(*args): 2 | s = 0 3 | for iterable in args: 4 | if type(iterable) == dict: 5 | for item in iterable: 6 | s += iterable[item] 7 | else: 8 | for item in iterable: 9 | s += item 10 | return s 11 | 12 | a = sum_iterable([40, 30, 20, 10], [20, 10]) 13 | print(a) 14 | -------------------------------------------------------------------------------- /QB/ClassesAndObjects/sortDictionaryByValue.py: -------------------------------------------------------------------------------- 1 | import operator 2 | d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} 3 | print('Original dictionary : ',d) 4 | sorted_d = sorted(d.items(), key=operator.itemgetter(1)) 5 | print('Dictionary in ascending order by value : ',sorted_d) 6 | sorted_d = dict( sorted(d.items(), key=operator.itemgetter(1),reverse=True)) 7 | print('Dictionary in descending order by value : ',sorted_d) 8 | -------------------------------------------------------------------------------- /QB/GUI/tkinter_radiobutton.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | parent = tk.Tk() 3 | parent.title("Radiobutton ") 4 | parent.geometry('350x200') 5 | radio1 = tk.Radiobutton(parent, text='First', value=1) 6 | radio2 = tk.Radiobutton(parent, text='Second', value=2) 7 | radio3 = tk.Radiobutton(parent, text='Third', value=3) 8 | radio1.grid(column=0, row=0) 9 | radio2.grid(column=1, row=0) 10 | parent.mainloop() -------------------------------------------------------------------------------- /QB/Types/user_defined.py: -------------------------------------------------------------------------------- 1 | import types 2 | 3 | class C: 4 | def x(): 5 | return 1 6 | def y(): 7 | return 1 8 | def b(): 9 | return 2 10 | 11 | print(isinstance(C().x, types.MethodType)) 12 | print(isinstance(C().y, types.MethodType)) 13 | print(isinstance(b, types.MethodType)) 14 | print(isinstance(max, types.MethodType)) 15 | print(isinstance(abs, types.MethodType)) -------------------------------------------------------------------------------- /Lab/2_lists.py: -------------------------------------------------------------------------------- 1 | list = [] 2 | even_sum = 0 3 | odd_sum = 0 4 | n = int(input("Enter number of elements in list: ")) 5 | print("Enter the elements: ") 6 | for i in range(n): 7 | list.append(int(input())) 8 | if list[i] % 2 == 0: 9 | even_sum += list[i] 10 | else: 11 | odd_sum += list[i] 12 | 13 | sum = (even_sum, odd_sum) 14 | print("Sum of even and odd numbers respectively: ", sum) 15 | -------------------------------------------------------------------------------- /QB/GUI/tkinter_text.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | root=tk.Tk() 3 | root.title("Text widhget") 4 | mytext=tk.Text(root) 5 | mytext.insert('1.0',"Python excercise") 6 | mytext.insert('1.20','Practicing') 7 | 8 | def remove(): 9 | mytext.delete('1.0') 10 | mytext.delete('end - 2 chars') 11 | 12 | btn = tk.Button(root, text='Click', command=remove) 13 | btn.place(x=50, y=50) 14 | 15 | mytext.pack() 16 | 17 | root.mainloop() 18 | -------------------------------------------------------------------------------- /QB/Pandas/dataframe_combine.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | sr1 = pd.Series(['php', 'python', 'java', 'c#', 'c++']) 3 | sr2 = pd.Series([1, 2, 3, 4, 5]) 4 | print("Original") 5 | print(sr1) 6 | print(sr2) 7 | 8 | print("Combine data frames") 9 | df = pd.DataFrame(sr1, sr2).reset_index() 10 | print(df.head()) 11 | 12 | print("Using pandas, give specific name to column") 13 | df = pd.DataFrame({'col1': sr1, 'col2': sr2}) 14 | print(df.head(5)) -------------------------------------------------------------------------------- /QB/Random/zero_division.py: -------------------------------------------------------------------------------- 1 | def division(x,y): 2 | try: 3 | div = x/y 4 | print(f"{x}/{y} = {div}") 5 | except ZeroDivisionError as e: 6 | print("Exception occurred!:", e) 7 | except Exception as e: 8 | print("Exception occurred!:", e) 9 | finally: 10 | print("Working on division function.") 11 | 12 | a = int(input("Enter number a: ")) 13 | b = int(input("Enter number b: ")) 14 | division(a,b) -------------------------------------------------------------------------------- /Lab/8_list_multiplication.py: -------------------------------------------------------------------------------- 1 | numbers = [1, 2, 3, 4] 2 | multiplier = [5, 6, 7, 8] 3 | result = [] 4 | try: 5 | for i in range(len(numbers)): 6 | result.append(multiplier[i] * numbers[i]) 7 | 8 | except IndexError: 9 | print("Multiplier list exhausted") 10 | 11 | except NameError: 12 | print("List does not exist") 13 | 14 | finally: 15 | if len(result) > 0: 16 | print("Multiplication for two lists is done") 17 | print(result) -------------------------------------------------------------------------------- /QB/GUI/tkinter_progressbar.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | from tkinter.ttk import Progressbar 3 | from tkinter import ttk 4 | parent = tk.Tk() 5 | parent.title("Progressbar") 6 | parent.geometry('350x200') 7 | style = ttk.Style() 8 | style.theme_use('default') 9 | style.configure("black.Horizontal.TProgressbar", background='green') 10 | bar = Progressbar(parent, length=220, style='black.Horizontal.TProgressbar') 11 | bar['value'] = 80 12 | bar.grid(column=0, row=0) 13 | parent.mainloop() -------------------------------------------------------------------------------- /QB/Lambda/nthelement.py: -------------------------------------------------------------------------------- 1 | def extract_nth_element(test_list, n): 2 | result = list(map (lambda x:(x[n]), test_list)) 3 | return result 4 | 5 | students = [('Pranav Patil', 98, 99), ('Akshay Rathod', 97, 96), ('Shashank Gupta', 91, 94), ('Deep Prajapati', 94, 98)] 6 | print ("Original list:") 7 | print(students) 8 | for n in range(0,3): 9 | print("\nExtract nth element ( n =",n,") from the said list of tuples:") 10 | print(extract_nth_element(students, n)) 11 | 12 | -------------------------------------------------------------------------------- /QB/Numpy/einstein_summation.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | a = np.array([1, 2, 3]) 4 | b = np.array([0, 1, 0]) 5 | print("Original") 6 | print(a) 7 | print(b) 8 | 9 | result = np.einsum("n, n", a, b) 10 | print("Einstein Summation: ",result) 11 | 12 | x = np.arange(9).reshape(3, 3) 13 | y = np.arange(3, 12).reshape(3, 3) 14 | print("Original Higher Dimension: ") 15 | print(x) 16 | print(y) 17 | 18 | result1 = np.einsum("mk, kn", x, y) 19 | print("Einstein Summation: ") 20 | print(result1) -------------------------------------------------------------------------------- /Lab/4_moving_avg.py: -------------------------------------------------------------------------------- 1 | def moving_avg(*args): 2 | arr = [] 3 | for i in args: 4 | arr += i 5 | window = 3 6 | val = len(arr) - window + 1 7 | for i in range(val): 8 | y = 0 9 | x = [] 10 | for j in range(i, i + window): 11 | y += arr[j] 12 | x.append(arr) 13 | print('y', i + 1, ' = ', y / window) 14 | x.clear() 15 | 16 | a = moving_avg([3, 5, 7, 2, 8, 10, 11, 65, 72, 81, 99, 100, 150]) 17 | print(a) 18 | -------------------------------------------------------------------------------- /Lab/1_reverse.py: -------------------------------------------------------------------------------- 1 | # Reverse a string using extended slice 2 | def reverse1(str): 3 | return str[::-1] 4 | 5 | # Reverse a string using loop 6 | def reverse2(str): 7 | reverse_str = "" 8 | for i in str: 9 | reverse_str = i + reverse_str 10 | return reverse_str 11 | 12 | first_name = input('Enter your first name: ') 13 | last_name = input('Enter your last name: ') 14 | print(reverse1(first_name), " ", reverse1(last_name)) 15 | print(reverse2(first_name), " ", reverse2(last_name)) 16 | -------------------------------------------------------------------------------- /QB/Decimal/rounding.py: -------------------------------------------------------------------------------- 1 | import decimal 2 | 3 | print("Round to floor") 4 | decimal.getcontext().prec = 4 5 | decimal.getcontext().rounding = decimal.ROUND_FLOOR 6 | print(decimal.Decimal(20) / decimal.Decimal(17)) 7 | 8 | print("Round to ceiling") 9 | decimal.getcontext().rounding = decimal.ROUND_CEILING 10 | print(decimal.Decimal(20) / decimal.Decimal(17)) 11 | 12 | print("Round to half even") 13 | decimal.getcontext().rounding = decimal.ROUND_HALF_EVEN 14 | print(decimal.Decimal(20) / decimal.Decimal(9)) -------------------------------------------------------------------------------- /QB/Matplotlib/barcahrt_using_dataframe.py: -------------------------------------------------------------------------------- 1 | from pandas import DataFrame 2 | import matplotlib.pyplot as plt 3 | import numpy as np 4 | a=np.array([[4,8,5,7,6],[2,3,4,2,6],[4,7,4,7,8],[2,6,4,8,6],[2,4,3,3,2]]) 5 | df=DataFrame(a, columns=['a','b','c','d','e'], index=[2,4,6,8,10]) 6 | df.plot(kind='bar') 7 | # Turn on the grid 8 | plt.minorticks_on() 9 | plt.grid(which='major', linestyle='-', linewidth='0.5', color='green') 10 | plt.grid(which='minor', linestyle=':', linewidth='0.5', color='black') 11 | plt.show() -------------------------------------------------------------------------------- /QB/Matplotlib/piechart_popularity.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | # Data to plot 3 | languages = 'Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++' 4 | popuratity = [22.2, 17.6, 8.8, 8, 7.7, 6.7] 5 | colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b"] 6 | # explode 1st slice 7 | explode = (0.1, 0, 0, 0,0,0) 8 | # Plot 9 | plt.pie(popuratity, explode=explode, labels=languages, colors=colors, 10 | autopct='%1.1f%%', shadow=True, startangle=140) 11 | plt.axis('equal') 12 | plt.show() -------------------------------------------------------------------------------- /QB/Pandas/dataframe_label.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Trevor', 'Franklin', 'Patrick'], 4 | 'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19], 5 | 'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1], 6 | 'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']} 7 | labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] 8 | 9 | df = pd.DataFrame(exam_data, index=labels) 10 | print(df) 11 | -------------------------------------------------------------------------------- /QB/Matplotlib/scatterplot.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import pandas as pd 3 | math_marks = [88, 92, 80, 89, 100, 80, 60, 100, 80, 34] 4 | science_marks = [35, 79, 79, 48, 100, 88, 32, 45, 20, 30] 5 | marks_range = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] 6 | plt.scatter(marks_range, math_marks, label='Math marks', color='r') 7 | plt.scatter(marks_range, science_marks, label='Science marks', color='g') 8 | plt.title('Scatter Plot') 9 | plt.xlabel('Marks Range') 10 | plt.ylabel('Marks Scored') 11 | plt.legend() 12 | plt.show() -------------------------------------------------------------------------------- /QB/ClassesAndObjects/integerToRomanNumeral.py: -------------------------------------------------------------------------------- 1 | class Roman: 2 | def intToRoman(self, num): 3 | val = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] 4 | roman = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'] 5 | 6 | roman_num = '' 7 | i = 0 8 | while num > 0: 9 | 10 | for _ in range(num // val[i]): 11 | roman_num += roman[i] 12 | num -= val[i] 13 | i+= 1 14 | return roman_num 15 | 16 | print(Roman().intToRoman(4001)) -------------------------------------------------------------------------------- /Lab/12_pie_chart.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | 3 | # Data 4 | countries = ['United States', 'China', 'Great Britain', 'Russia', 'Germany', 'Japan'] 5 | gold_medals = [57, 48, 39, 25, 20, 10] 6 | 7 | # Plotting the pie chart 8 | fig, ax = plt.subplots(figsize=(8, 8)) 9 | ax.pie(gold_medals, labels=countries, autopct='%1.1f%%', startangle=90, shadow=True) 10 | 11 | # Adding title and legend 12 | ax.set_title('Gold Medals Obtained by Countries in Olympics 2012') 13 | ax.legend(countries, title='Countries', loc='upper right') 14 | 15 | plt.show() 16 | -------------------------------------------------------------------------------- /Lab/4_vandermonde.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | def vm(m,asc=True): 4 | ls=[] 5 | 6 | if asc==True: 7 | for item in m: 8 | ll=[] 9 | for i in range(len(m)): 10 | ll.append(item**i) 11 | ls.append(ll) 12 | print(np.array(ls)) 13 | else: 14 | for item in m: 15 | ll=[] 16 | for i in range(len(m)-1,-1,-1): 17 | ll.append(item**i) 18 | ls.append(ll) 19 | print(np.array(ls)) 20 | 21 | a = vm([1,2,3,4,5]) 22 | -------------------------------------------------------------------------------- /QB/Pandas/dataframe_3rows.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Trevor', 'Franklin', 'Patrick'], 4 | 'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19], 5 | 'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1], 6 | 'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']} 7 | labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] 8 | 9 | df = pd.DataFrame(exam_data, index=labels) 10 | print("First 3 rows are:") 11 | print(df.iloc[:3]) -------------------------------------------------------------------------------- /QB/Pandas/merge_datasets.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | 3 | data1 = pd.DataFrame({'key1': ['K0', 'K0', 'K1', 'K2'], 4 | 'key2': ['K0', 'K1', 'K0', 'K1'], 5 | 'P': ['P0', 'P1', 'P2', 'P3'], 6 | 'Q': ['Q0', 'Q1', 'Q2', 'Q3']}) 7 | data2 = pd.DataFrame({'key1': ['K0', 'K1', 'K1', 'K2'], 8 | 'key2': ['K0', 'K0', 'K0', 'K0'], 9 | 'R': ['R0', 'R1', 'R2', 'R3'], 10 | 'S': ['S0', 'S1', 'S2', 'S3']}) 11 | print("Original DataFrames:") 12 | print(data1) 13 | print(data2) 14 | 15 | print("Merged data: ") 16 | merged_data = pd.merge(data1, data2, on=['key1', 'key2']) 17 | print(merged_data) -------------------------------------------------------------------------------- /QB/GUI/tkinter_exit.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | 3 | def write_text(): 4 | lbl = tk.Label(parent) 5 | lbl.config(text = "Greetings User") 6 | lbl.place(x=160,y=90) 7 | print("Tkinter is easy to create GUI!") 8 | 9 | parent = tk.Tk() 10 | frame = tk.Frame(parent) 11 | frame.pack() 12 | 13 | text_disp= tk.Button(frame,text="Hello",command=write_text) 14 | text_disp.pack(side=tk.LEFT) 15 | 16 | exit_button = tk.Button(frame,text="Exit",fg="green",command=parent.destroy) 17 | exit_button.pack(side=tk.RIGHT) 18 | 19 | parent.geometry("400x400") 20 | parent.mainloop() -------------------------------------------------------------------------------- /QB/ClassesAndObjects/validParentheses.py: -------------------------------------------------------------------------------- 1 | class py_solution: 2 | def is_valid_parenthese(self, str1): 3 | stack, pchar = [], {"(": ")", "{": "}", "[": "]"} 4 | for parenthese in str1: 5 | if parenthese in pchar: 6 | stack.append(parenthese) 7 | elif len(stack) == 0 or pchar[stack.pop()] != parenthese: 8 | return False 9 | return len(stack) == 0 10 | print(py_solution().is_valid_parenthese("(){}[]")) 11 | print(py_solution().is_valid_parenthese("()[{)}")) 12 | print(py_solution().is_valid_parenthese("()")) -------------------------------------------------------------------------------- /QB/Pandas/dataframe_mean.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Trevor', 'Franklin', 'Patrick'], 4 | 'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19], 5 | 'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1], 6 | 'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']} 7 | labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] 8 | 9 | df = pd.DataFrame(exam_data, index=labels) 10 | print("Mean score for all different students:") 11 | print(df['score'].mean()) -------------------------------------------------------------------------------- /QB/Pandas/dataframe_greater_than.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Trevor', 'Franklin', 'Patrick'], 4 | 'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19], 5 | 'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1], 6 | 'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']} 7 | labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] 8 | 9 | df = pd.DataFrame(exam_data, index=labels) 10 | print("Number of attempts greater than 2:") 11 | print(df[df['attempts'] > 2]) 12 | -------------------------------------------------------------------------------- /QB/Pandas/dataframe_cell_index.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Trevor', 'Franklin', 'Patrick'], 4 | 'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19], 5 | 'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1], 6 | 'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']} 7 | labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] 8 | df = pd.DataFrame(exam_data) 9 | print(df) 10 | 11 | print("Set a value for particular cell") 12 | df.at[8, 'score'] = 10.2 13 | print(df) 14 | -------------------------------------------------------------------------------- /QB/Pandas/dataframe_select_rows.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Trevor', 'Franklin', 'Patrick'], 4 | 'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19], 5 | 'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1], 6 | 'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']} 7 | labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] 8 | 9 | df = pd.DataFrame(exam_data, index=labels) 10 | print("Rows between 15 and 20 (inclusive)") 11 | print(df[df['score'].between(15, 20)]) -------------------------------------------------------------------------------- /Lab/12_histogram.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import numpy as np 3 | 4 | # Generate random data points 5 | np.random.seed(123) # For reproducibility 6 | data = np.random.randint(0, 100, 1000) 7 | 8 | # Define histogram bins 9 | bins = np.arange(0, 101, 5) # Bin edges from 0 to 100 with step of 5 10 | 11 | # Plotting the histogram 12 | fig, ax = plt.subplots(figsize=(10, 6)) 13 | ax.hist(data, bins=bins, edgecolor='black') 14 | 15 | # Adding labels and title 16 | ax.set_xlabel('Range') 17 | ax.set_ylabel('Frequency') 18 | ax.set_title('Histogram of Randomly Generated Data\nwith Ranges [0-5, 5-10, 10-15, ... 95-100]') 19 | 20 | plt.show() 21 | -------------------------------------------------------------------------------- /Lab/15_flask/templates/books.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Books 5 | 6 | 7 |

Books in Library

8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | {% for book in books %} 16 | 17 | 18 | 19 | 20 | 21 | 22 | {% endfor %} 23 |
NumberTitleAuthorPublication
{{ book.number }}{{ book.title }}{{ book.author }}{{ book.publication }}
24 | 25 | 26 | -------------------------------------------------------------------------------- /Lab/Mypackage/Shapes.py: -------------------------------------------------------------------------------- 1 | from abc import ABC, abstractmethod 2 | 3 | class Shapes(ABC): 4 | @abstractmethod 5 | def volume(): 6 | pass 7 | 8 | class Sphere(Shapes): 9 | def __init__(self, radius): 10 | super().__init__() 11 | self.radius = radius 12 | 13 | def volume(self): 14 | volume = ((4/3) * (self.radius ** 3)) 15 | print(f"Volume: {volume}") 16 | 17 | class Cube(Shapes): 18 | def __init__(self, side): 19 | super().__init__() 20 | self.side = side 21 | 22 | def volume(self): 23 | volume = self.side ** 3 24 | print(f"Volume: {volume}") -------------------------------------------------------------------------------- /QB/Matplotlib/piecharttitle_popularity.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | # Plot data 3 | languages = 'Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++' 4 | popuratity = [22.2, 17.6, 8.8, 8, 7.7, 6.7] 5 | #colors = ['red', 'gold', 'yellowgreen', 'blue', 'lightcoral', 'lightskyblue'] 6 | colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b"] 7 | # explode 1st slice 8 | explode = (0.1, 0, 0, 0, 0, 0) 9 | # Plot 10 | plt.pie(popuratity, explode=explode, labels=languages, colors=colors, 11 | autopct='%1.1f%%', shadow=True, startangle=140) 12 | plt.title("PopularitY of Programming Language\n" + "Worldwide, Oct 2022 compared to a year ago", bbox={'facecolor':'0.8', 'pad':5}) 13 | plt.show() -------------------------------------------------------------------------------- /QB/Decimal/shallow_copy.py: -------------------------------------------------------------------------------- 1 | import copy 2 | 3 | nums_x = [1, [2, 3, 4]] 4 | print("Original list: ", nums_x) 5 | nums_y = copy.copy(nums_x) 6 | print("\nCopy of the said list:") 7 | print(nums_y) 8 | print("\nChange the value of an element of the original list:") 9 | nums_x[1][1] = 10 10 | print(nums_x) 11 | print("\nCopy of the said list:") 12 | print(nums_y) 13 | 14 | nums_x = {"a":1, "b":2, 'cc':{"c":3}} 15 | print("Original dictionary: ", nums_x) 16 | nums_y = copy.copy(nums_x) 17 | print("\nCopy of the said list:") 18 | print(nums_y) 19 | print("\nChange the value of an element of the original dictionary:") 20 | nums_x["cc"]["c"] = 10 21 | print(nums_x) 22 | print("\nSecond dictionary:") 23 | print(nums_y) -------------------------------------------------------------------------------- /QB/Pandas/dataframe_insert_column.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Trevor', 'Franklin', 'Patrick'], 4 | 'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19], 5 | 'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1], 6 | 'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']} 7 | labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] 8 | 9 | df = pd.DataFrame(exam_data, index=labels) 10 | print("Origrinal:") 11 | print(df) 12 | 13 | color = ['Red','Blue','Orange','Red','White','White','Blue','Green','Green','Red'] 14 | df['color'] = color 15 | 16 | print("New Dataframe: ") 17 | print(df) -------------------------------------------------------------------------------- /QB/Lambda/marks_of_students.py: -------------------------------------------------------------------------------- 1 | students = [] 2 | sec_name = [] 3 | second_low = 0 4 | n = int(input("Input number of students: ")) 5 | for _ in range(n): 6 | s_name = input("Name: ") 7 | score = float(input("Score: ")) 8 | students.append([s_name,score]) 9 | print("\nNames and Grades of all students:") 10 | print(students) 11 | order =sorted(students, key = lambda x: int(x[1])) 12 | for i in range(n): 13 | if order[i][1] != order[0][1]: 14 | second_low = order[i][1] 15 | break 16 | print("\nSecond lowest grade: ",second_low) 17 | sec_student_name = [x[0] for x in order if x[1] == second_low] 18 | sec_student_name.sort() 19 | print("\nNames:") 20 | for s_name in sec_student_name: 21 | print(s_name) -------------------------------------------------------------------------------- /QB/Pandas/dataframe_append.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Trevor', 'Franklin', 'Patrick'], 4 | 'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19], 5 | 'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1], 6 | 'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']} 7 | labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] 8 | 9 | df = pd.DataFrame(exam_data, index=labels) 10 | print("Original:") 11 | print(df) 12 | 13 | df.loc['k'] = ['Suresh', 15.5, 1, 'yes'] 14 | print("New Dataframe:") 15 | print(df) 16 | 17 | df = df.drop('k') 18 | print("Data frame after deleting row 'k'") 19 | print(df) -------------------------------------------------------------------------------- /QB/Decimal/deep_copy.py: -------------------------------------------------------------------------------- 1 | import copy 2 | nums_x = [1, [2, 3, 4]] 3 | print("Original list: ", nums_x) 4 | nums_y = copy.deepcopy(nums_x) 5 | print("\nDeep copy of the said list:") 6 | print(nums_y) 7 | print("\nChange the value of an element of the original list:") 8 | nums_x[1][1] = 10 9 | print(nums_x) 10 | print("\nDeep copy of the said list:") 11 | print(nums_y) 12 | 13 | nums_x = {"a":1, "b":2, 'cc':{"c":3}} 14 | print("Original dictionary: ", nums_x) 15 | nums_y = copy.deepcopy(nums_x) 16 | print("\nDeep copy of the said list:") 17 | print(nums_y) 18 | print("\nChange the value of an element of the original dictionary:") 19 | nums_x["cc"]["c"] = 10 20 | print(nums_x) 21 | print("\nSecond dictionary (Deep copy):") 22 | print(nums_y) 23 | -------------------------------------------------------------------------------- /Lab/15_flask/app2.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, redirect, jsonify 2 | 3 | app = Flask(__name__) 4 | 5 | @app.route('/books') 6 | def books(): 7 | return 'Here are some books' 8 | 9 | 10 | @app.route('/result/') 11 | def result(marks): 12 | if marks < 50: 13 | return redirect('/failed') 14 | else: 15 | return redirect('/passed') 16 | 17 | 18 | @app.route('/failed') 19 | def failed(): 20 | message = 'Sorry, you failed the exam!' 21 | return jsonify({'message': message}) 22 | 23 | @app.route('/passed') 24 | def passed(): 25 | message = 'Congratulations, you passed the exam!' 26 | return jsonify({'message': message}) 27 | 28 | 29 | if __name__ == '__main__': 30 | app.run(debug=True) 31 | -------------------------------------------------------------------------------- /QB/Pandas/dataframe_inner_join.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | 3 | student_data1 = pd.DataFrame({ 4 | 'student_id': ['S1', 'S2', 'S3', 'S4', 'S5'], 5 | 'name': ['Danniella Fenton', 'Ryder Storey', 'Bryce Jensen', 'Ed Bernal', 'Kwame Morningstar'], 6 | 'marks': [200, 210, 190, 222, 199]}) 7 | student_data2 = pd.DataFrame({ 8 | 'student_id': ['S4', 'S5', 'S6', 'S7', 'S8'], 9 | 'name': ['Scarlette Fisher', 'Carla Williamson', 'Dante Morse', 'Kaiser William', 'Macy Meadows'], 10 | 'marks': [201, 200, 198, 219, 201]}) 11 | print("Original DataFrames:") 12 | print(student_data1) 13 | print(student_data2) 14 | 15 | merged_data = pd.merge(student_data1, student_data2, on='student_id', how='inner') 16 | print("Merged Data (inner join):") 17 | print(merged_data) -------------------------------------------------------------------------------- /QB/Matplotlib/men&women_togehter.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | # data to plot 4 | n_groups = 5 5 | men_means = (22, 30, 33, 30, 26) 6 | women_means = (25, 32, 30, 35, 29) 7 | # create plot 8 | fig, ax = plt.subplots() 9 | index = np.arange(n_groups) 10 | bar_width = 0.35 11 | opacity = 0.8 12 | rects1 = plt.bar(index, men_means, bar_width, 13 | alpha=opacity, 14 | color='g', 15 | label='Men') 16 | rects2 = plt.bar(index + bar_width, women_means, bar_width, 17 | alpha=opacity, 18 | color='r', 19 | label='Women') 20 | plt.xlabel('Person') 21 | plt.ylabel('Scores') 22 | plt.title('Scores by person') 23 | plt.xticks(index + bar_width, ('G1', 'G2', 'G3', 'G4', 'G5')) 24 | plt.legend() 25 | plt.tight_layout() 26 | plt.show() 27 | -------------------------------------------------------------------------------- /QB/Pandas/dataframe_left_join.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | 3 | data1 = pd.DataFrame({'key1': ['K0', 'K0', 'K1', 'K2'], 4 | 'key2': ['K0', 'K1', 'K0', 'K1'], 5 | 'P': ['P0', 'P1', 'P2', 'P3'], 6 | 'Q': ['Q0', 'Q1', 'Q2', 'Q3']}) 7 | data2 = pd.DataFrame({'key1': ['K0', 'K1', 'K1', 'K2'], 8 | 'key2': ['K0', 'K0', 'K0', 'K0'], 9 | 'R': ['R0', 'R1', 'R2', 'R3'], 10 | 'S': ['S0', 'S1', 'S2', 'S3']}) 11 | print("Original DataFrames:") 12 | print(data1) 13 | print(data2) 14 | 15 | print("\nMerged Data (keys from data1):") 16 | merged_data = pd.merge(data1, data2, how='left', on=['key1', 'key2']) 17 | print(merged_data) 18 | 19 | print("\nMerged Data (keys from data2):") 20 | merged_data = pd.merge(data2, data1, how='left', on=['key1', 'key2']) 21 | print(merged_data) -------------------------------------------------------------------------------- /QB/Matplotlib/error_bars_m&w.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | N = 5 4 | menMeans = (22, 30, 35, 35, 26) 5 | womenMeans = (25, 32, 30, 35, 29) 6 | menStd = (4, 3, 4, 1, 5) 7 | womenStd = (3, 5, 2, 3, 3) 8 | # the x locations for the groups 9 | ind = np.arange(N) 10 | # the width of the bars 11 | width = 0.35 12 | p1 = plt.bar(ind, menMeans, width, yerr=menStd, color='red') 13 | p2 = plt.bar(ind, womenMeans, width, 14 | bottom=menMeans, yerr=womenStd, color='green') 15 | plt.ylabel('Scores') 16 | plt.xlabel('Groups') 17 | plt.title('Scores by group\n' + 'and gender') 18 | plt.xticks(ind, ('Group1', 'Group2', 'Group3', 'Group4', 'Group5')) 19 | plt.yticks(np.arange(0, 81, 10)) 20 | plt.legend((p1[0], p2[0]), ('Men', 'Women')) 21 | plt.show() -------------------------------------------------------------------------------- /QB/Random/random_hex.py: -------------------------------------------------------------------------------- 1 | import random 2 | import string 3 | 4 | print("Random Color Hex") 5 | print("#{:06x}".format(random.randint(0, 0xFFFFFF))) 6 | 7 | print("Random alphabetical string") 8 | max_length = 255 9 | s = "" 10 | for i in range(random.randint(1, max_length)): 11 | s += random.choice(string.ascii_letters) 12 | print(s) 13 | 14 | print("Random value bteween 2 integers (inclusive)") 15 | print(random.randint(-4, 10)) 16 | 17 | print("Random multiple of 7 between 0 and 70") 18 | print(random.randint(0, 10) * 7) 19 | 20 | print("Generate a random alphabetical character:") 21 | print(random.choice(string.ascii_letters)) 22 | 23 | print("\nGenerate a random alphabetical string of a fixed length:") 24 | str1 = "" 25 | for i in range(10): 26 | str1 += random.choice(string.ascii_letters) 27 | print(str1) -------------------------------------------------------------------------------- /QB/Matplotlib/barchart_hori_popularity.py: -------------------------------------------------------------------------------- 1 | #Write a Python programming to display a horizontal bar chart of the popularity of programming Languages. 2 | #Programming languages: Java, Python, PHP, JavaScript, C#, C++ 3 | #Popularity: 22.2, 17.6, 8.8, 8, 7.7, 6.7 4 | import matplotlib.pyplot as plt 5 | x = ['Java', 'Python', 'PHP', 'JS', 'C#', 'C++'] 6 | popularity = [22.2, 17.6, 8.8, 8, 7.7, 6.7] 7 | x_pos = [i for i, _ in enumerate(x)] 8 | plt.barh(x_pos, popularity, color=['green','red']) 9 | plt.xlabel("Popularity") 10 | plt.ylabel("Languages") 11 | plt.title("Popularity of Programming Language\n" + "Worldwide, Oct 2022 compared to a year ago") 12 | plt.yticks(x_pos, x) 13 | # Turn on the grid 14 | plt.minorticks_on() 15 | plt.grid(which='major', linestyle='-', linewidth='0.5', color='red') 16 | # Customize the minor grid 17 | plt.grid(which='minor', linestyle=':', linewidth='0.5', color='black') 18 | plt.show() 19 | -------------------------------------------------------------------------------- /QB/Matplotlib/barchart_popularity.py: -------------------------------------------------------------------------------- 1 | #Write a Python programming to display a bar chart of the popularity of programming Languages. 2 | #Sample data: 3 | #Programming languages: Java, Python, PHP, JavaScript, C#, C++ 4 | #Popularity: 22.2, 17.6, 8.8, 8, 7.7, 6.7 5 | import matplotlib.pyplot as plt 6 | x = ['Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++'] 7 | popularity = [22.2, 17.6, 8.8, 8, 7.7, 6.7] 8 | x_pos = [i for i, _ in enumerate(x)] 9 | plt.bar(x_pos, popularity, color='blue') 10 | plt.xlabel("Languages") 11 | plt.ylabel("Popularity") 12 | plt.title("PopularitY of Programming Language\n" + "Worldwide, Oct 2017 compared to a year ago") 13 | plt.xticks(x_pos, x) 14 | # Turn on the grid 15 | plt.minorticks_on() 16 | plt.grid(which='major', linestyle='-', linewidth='0.5', color='red') 17 | # Customize the minor grid 18 | plt.grid(which='minor', linestyle=':', linewidth='0.5', color='black') 19 | plt.show() 20 | -------------------------------------------------------------------------------- /Lab/12_bargraph.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | 3 | # Data 4 | countries = ['United States', 'China', 'Great Britain', 'Russia', 'Germany', 'Japan'] 5 | gold_medals = [57, 48, 39, 25, 20, 10] 6 | silver_medals = [28, 30, 21, 25, 18, 16] 7 | 8 | # Plotting the bar graph 9 | fig, ax = plt.subplots(figsize=(10, 6)) 10 | width = 0.35 # width of the bars 11 | ind = range(len(countries)) 12 | 13 | # Adjusting x-axis positions for silver bars 14 | silver_ind = [x + width for x in ind] 15 | 16 | gold_bars = ax.bar(ind, gold_medals, width, label='Gold Medals') 17 | silver_bars = ax.bar(silver_ind, silver_medals, width, label='Silver Medals') # Adjusting x-axis positions 18 | 19 | # Adding labels and title 20 | ax.set_xlabel('Countries') 21 | ax.set_ylabel('Medal Count') 22 | ax.set_title('Gold and Silver Medals by Country') 23 | ax.set_xticks([i + width/2 for i in ind]) # Centering x-ticks 24 | ax.set_xticklabels(countries) 25 | ax.legend() 26 | 27 | plt.show() 28 | -------------------------------------------------------------------------------- /Lab/6_operator_overload.py: -------------------------------------------------------------------------------- 1 | class Point: 2 | def __init__(self, x, y): 3 | self.x = x 4 | self.y = y 5 | 6 | def __add__(self, obj): 7 | x = self.x + obj.x 8 | y = self.y + obj.y 9 | return Point(x, y) 10 | 11 | def __sub__(self, obj): 12 | x = self.x - obj.x 13 | y = self.y - obj.y 14 | return Point(x, y) 15 | 16 | def __lt__(self, obj): 17 | if(((self.x ** 2 + self.y ** 2) ** 0.5) < ((obj.x ** 2 + obj.y ** 2) ** 0.5)): 18 | return True 19 | else: 20 | return False 21 | 22 | def __gt__(self, obj): 23 | if(((self.x ** 2 + self.y ** 2) ** 0.5) > ((obj.x ** 2 + obj.y ** 2) ** 0.5)): 24 | return True 25 | else: 26 | return False 27 | 28 | def __str__(self): 29 | return (f"X co-ordinate: {self.x} Y co-ordinate: {self.y}") 30 | 31 | p1 = Point(1, 1) 32 | p2 = Point(2, 2) 33 | p3 = p1 + p2 34 | print(p3) -------------------------------------------------------------------------------- /Lab/9_file_handling.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | filename = 'bookdata.txt' 4 | 5 | if not os.path.exists(filename): 6 | with open(filename, 'w') as f: 7 | print(f"{filename} does not exist. An empty file has been created.") 8 | num_books = 0 9 | while num_books < 3: 10 | book = {} 11 | book['title'] = input("Enter book title: ") 12 | book['author'] = input("Enter book author: ") 13 | book['type'] = input("Enter book type: ") 14 | book['publication'] = input("Enter book publication: ") 15 | book['price'] = input("Enter book price: ") 16 | f.write(str(book) + '\n') 17 | num_books += 1 18 | 19 | with open(filename, 'r') as f: 20 | book_list = [] 21 | for line in f: 22 | book = eval(line.strip()) 23 | book_list.append(book) 24 | print("Book Details:") 25 | for book in book_list: 26 | print(f"Title: {book['title']}") 27 | print(f"Author: {book['author']}") 28 | print(f"Type: {book['type']}") 29 | print(f"Publication: {book['publication']}") 30 | print(f"Price: {book['price']}") 31 | -------------------------------------------------------------------------------- /Lab/5_vehicle.py: -------------------------------------------------------------------------------- 1 | class Vehicle: 2 | def __init__(self, mileage, max_speed, name): 3 | self.mileage = mileage 4 | self.max_speed = max_speed 5 | self.name = name 6 | 7 | def seating_capacity(self): 8 | pass 9 | 10 | def fare(self): 11 | return (self.seating_capacity() * 20) + (self.seating_capacity() * 20 * 0.1) 12 | 13 | def vehicle_info(self): 14 | print(f"Vehicle Name: {self.name}") 15 | print(f"Mileage: {self.mileage}") 16 | print(f"Max Speed: {self.max_speed}") 17 | print(f"Seating Capacity: {self.seating_capacity()}") 18 | print(f"Fare: {self.fare()}") 19 | 20 | class Bus(Vehicle): 21 | def __init__(self, mileage, max_speed, name): 22 | super().__init__(mileage, max_speed, name) 23 | 24 | def seating_capacity(self): 25 | return 40 26 | 27 | class Car(Vehicle): 28 | def __init__(self, mileage, max_speed, name): 29 | super().__init__(mileage, max_speed, name) 30 | 31 | def seating_capacity(self): 32 | return 4 33 | 34 | bus = Bus(10, 100, "Volvo") 35 | bus.vehicle_info() -------------------------------------------------------------------------------- /Lab/14_scipy.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy import linalg 3 | 4 | # 1. Solve the system of linear equations 5 | # Define the coefficients matrix and the constants vector 6 | A = np.array([[9, 6, -5, 2], 7 | [4, 5, -7, 3], 8 | [-3, -4, 2, -5], 9 | [6, 1, 9, -1]]) 10 | b = np.array([17, 10, 20, 23]) 11 | 12 | # Solve the system of linear equations 13 | x = linalg.solve(A, b) 14 | print("Solution of the system of linear equations:") 15 | print(x) 16 | print() 17 | 18 | # 2. Perform the following operations on a matrix 19 | # Define matrix A and matrix B 20 | A = np.array([[5, 3, 2], 21 | [6, 9, -3], 22 | [1, 7, 4]]) 23 | B = np.array([[3, -1], 24 | [2, -5]]) 25 | 26 | # a. Find Inverse of matrix A 27 | A_inv = linalg.inv(A) 28 | print("Inverse of matrix A:") 29 | print(A_inv) 30 | print() 31 | 32 | # b. Find Kronecker product of A with B 33 | A_kron_B = np.kron(A, B) 34 | print("Kronecker product of matrix A and matrix B:") 35 | print(A_kron_B) 36 | print() 37 | 38 | # c. Find determinant of matrix A 39 | A_det = linalg.det(A) 40 | print("Determinant of matrix A:") 41 | print(A_det) 42 | -------------------------------------------------------------------------------- /Lab/15_flask/app1.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template, redirect, jsonify, request 2 | 3 | app = Flask(__name__) 4 | 5 | # Data for books in the library (dummy data) 6 | books = [ 7 | {"number": 1, "title": "Book 1", "author": "Author 1", "publication": "Publication 1", "isbn": "123456789"}, 8 | {"number": 2, "title": "Book 2", "author": "Author 2", "publication": "Publication 2", "isbn": "987654321"}, 9 | {"number": 3, "title": "Book 3", "author": "Author 3", "publication": "Publication 3", "isbn": "456789123"} 10 | ] 11 | 12 | @app.route('/') 13 | def home(): 14 | return "Welcome to the Library!" 15 | 16 | @app.route('/books', methods=['GET']) 17 | def view_books(): 18 | return render_template('books.html', books=books) 19 | 20 | @app.route('/books/search', methods=['GET']) 21 | def search_books(): 22 | isbn = request.args.get('isbn') 23 | book = None 24 | for b in books: 25 | if b['isbn'] == isbn: 26 | book = b 27 | break 28 | if book: 29 | return jsonify(book) 30 | else: 31 | return jsonify({"error": "Book not found"}) 32 | 33 | if __name__ == '__main__': 34 | app.run(debug=True) 35 | -------------------------------------------------------------------------------- /QB/ClassesAndObjects/employeeData.py: -------------------------------------------------------------------------------- 1 | class Employee: 2 | def __init__(self, name, emp_id, salary, department): 3 | self.name = name 4 | self.id = emp_id 5 | self.salary = salary 6 | self.department = department 7 | def calculate_salary(self, salary, hours_worked): 8 | overtime = 0 9 | if hours_worked > 50: 10 | overtime = hours_worked - 50 11 | self.salary = self.salary + (overtime * (self.salary / 50)) 12 | def assign_department(self, emp_department): 13 | self.department = emp_department 14 | def print_employee_details(self): 15 | print("\nName: ", self.name) 16 | print("ID: ", self.id) 17 | print("Salary: ", self.salary) 18 | print("Department: ", self.department) 19 | print("----------------------") 20 | employee1 = Employee("ADAMS", "E7876", 50000, "ACCOUNTING") 21 | employee2 = Employee("JONES", "E7499", 45000, "RESEARCH") 22 | employee3 = Employee("MARTIN", "E7900", 50000, "SALES") 23 | employee4 = Employee("SMITH", "E7698", 55000, "OPERATIONS") 24 | print("Original Employee Details:") 25 | employee1.print_employee_details() 26 | employee2.print_employee_details() 27 | employee3.print_employee_details() 28 | employee4.print_employee_details() -------------------------------------------------------------------------------- /QB/Matplotlib/multidimensional_data.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | people = ('G1','G2','G3','G4','G5','G6','G7','G8') 4 | segments = 4 5 | # multi-dimensional data 6 | data = [[ 3.40022085, 7.70632498, 6.4097905, 10.51648577, 7.5330039, 7 | 7.1123587, 12.77792868, 3.44773477], 8 | [ 11.24811149, 5.03778215, 6.65808464, 12.32220677, 7.45964195, 9 | 6.79685302, 7.24578743, 3.69371847], 10 | [ 3.94253354, 4.74763549, 11.73529246, 4.6465543, 12.9952182, 11 | 4.63832778, 11.16849999, 8.56883433], 12 | [ 4.24409799, 12.71746612, 11.3772169, 9.00514257, 10.47084185, 13 | 10.97567589, 3.98287652, 8.80552122]] 14 | percentages = (np.random.randint(5,20, (len(people), segments))) 15 | y_pos = np.arange(len(people)) 16 | fig = plt.figure(figsize=(10,8)) 17 | ax = fig.add_subplot(111) 18 | colors ='rgwm' 19 | patch_handles = [] 20 | # left alignment of data starts at zero 21 | left = np.zeros(len(people)) 22 | for i, d in enumerate(data): 23 | patch_handles.append(ax.barh(y_pos, d, 24 | color=colors[i%len(colors)], align='center', 25 | left=left)) 26 | left += d 27 | # search all of the bar segments and annotate 28 | for j in range(len(patch_handles)): 29 | for i, patch in enumerate(patch_handles[j].get_children()): 30 | bl = patch.get_xy() 31 | x = 0.5*patch.get_width() + bl[0] 32 | y = 0.5*patch.get_height() + bl[1] 33 | ax.text(x,y, "%d%%" % (percentages[i,j]), ha='center') 34 | ax.set_yticks(y_pos) 35 | ax.set_yticklabels(people) 36 | ax.set_xlabel('Scores') 37 | plt.show() -------------------------------------------------------------------------------- /Lab/5_employee.py: -------------------------------------------------------------------------------- 1 | class Employee: 2 | def __init__(self, fname, lname, age, basic): 3 | self.fname = fname 4 | self.lname = lname 5 | self.age = age 6 | self.basic = basic 7 | self.email = fname + "." + lname + "@gmail.com" 8 | 9 | def display(self): 10 | print(f"Name: {self.fname} {self.lname}") 11 | print(f"Age: {self.age} \nSalary: {self.basic}") 12 | print(f"Email: {self.email}") 13 | 14 | class Developer(Employee): 15 | def __init__(self, fname, lname, age, basic, lang): 16 | super().__init__(fname, lname, age, basic) 17 | self.lang = lang 18 | 19 | def display(self): 20 | super().display() 21 | print(f"Language: {self.lang}") 22 | 23 | class Manager(Employee): 24 | def __init__(self, fname, lname, age, basic): 25 | super().__init__(fname, lname, age, basic) 26 | self.subordinates = [] 27 | 28 | def addEmployee(self, newEmp): 29 | self.subordinates.append(newEmp) 30 | print(f"{newEmp.fname} {newEmp.lname} added as a subordinate") 31 | 32 | def display(self): 33 | super().display() 34 | if not self.subordinates: 35 | print("No subordinates") 36 | else: 37 | for newEmp in self.subordinates: 38 | print(f"Subordinates: {newEmp.fname} {newEmp.lname}") 39 | 40 | emp2 = Developer("Jay", "Mor", 21, 10000, "Python") 41 | emp1 = Manager("Ram", "Shah", 20, 40000) 42 | emp2.display() 43 | emp1.addEmployee(emp2) 44 | emp1.display() 45 | -------------------------------------------------------------------------------- /QB/ClassesAndObjects/Inventory.py: -------------------------------------------------------------------------------- 1 | class Inventory: 2 | def __init__(self): 3 | self.inventory = {} 4 | def add_item(self, item_id, item_name, stock_count, price): 5 | self.inventory[item_id] = {"item_name": item_name, "stock_count": stock_count, "price": price} 6 | def update_item(self, item_id, stock_count, price): 7 | if item_id in self.inventory: 8 | self.inventory[item_id]["stock_count"] = stock_count 9 | self.inventory[item_id]["price"] = price 10 | else: 11 | print("Item not found in inventory.") 12 | def check_item_details(self, item_id): 13 | if item_id in self.inventory: 14 | item = self.inventory[item_id] 15 | return f"Product Name: {item['item_name']}, Stock Count: {item['stock_count']}, Price: {item['price']}" 16 | else: 17 | return "Item not found in inventory." 18 | inventory = Inventory() 19 | inventory.add_item("I001", "Laptop", 100, 500.00) 20 | inventory.add_item("I002", "Mobile", 110, 450.00) 21 | inventory.add_item("I003", "Desktop", 120, 500.00) 22 | inventory.add_item("I004", "Tablet", 90, 550.00) 23 | print("Item Details:") 24 | print(inventory.check_item_details("I001")) 25 | print(inventory.check_item_details("I002")) 26 | print(inventory.check_item_details("I003")) 27 | print(inventory.check_item_details("I004")) 28 | print("\nUpdate the price of item code - 'I001':") 29 | inventory.update_item("I001", 100, 505.00) 30 | print(inventory.check_item_details("I001")) 31 | print("\nUpdate the stock of item code - 'I003':") 32 | inventory.update_item("I003", 115, 500.00) 33 | print(inventory.check_item_details("I003")) -------------------------------------------------------------------------------- /QB/ClassesAndObjects/restaurant.py: -------------------------------------------------------------------------------- 1 | class Restaurant: 2 | def __init__(self): 3 | self.menu_items = {} 4 | self.book_table = [] 5 | self.customer_orders = [] 6 | def add_item_to_menu(self, item, price): 7 | self.menu_items[item] = price 8 | def book_tables(self, table_number): 9 | self.book_table.append(table_number) 10 | def customer_order(self, table_number, order): 11 | order_details = {'table_number': table_number, 'order': order} 12 | self.customer_orders.append(order_details) 13 | def print_menu_items(self): 14 | for item, price in self.menu_items.items(): 15 | print("{}: {}".format(item, price)) 16 | def print_table_reservations(self): 17 | for table in self.book_table: 18 | print("Table {}".format(table)) 19 | def print_customer_orders(self): 20 | for order in self.customer_orders: 21 | print("Table {}: {}".format(order['table_number'], order['order'])) 22 | restaurant = Restaurant() 23 | # Add items 24 | restaurant.add_item_to_menu("Cheeseburger", 9.99) 25 | restaurant.add_item_to_menu("Caesar Salad", 8) 26 | restaurant.add_item_to_menu("Grilled Salmon", 19.99) 27 | restaurant.add_item_to_menu("French Fries", 3.99) 28 | restaurant.add_item_to_menu("Fish & Chips:", 15) # Book table 29 | restaurant.book_tables(1) 30 | restaurant.book_tables(2) 31 | restaurant.book_tables(3) # Order items 32 | restaurant.customer_order(1, "Cheeseburger") 33 | restaurant.customer_order(1, "Grilled Salmon") 34 | restaurant.customer_order(2, "Fish & Chips") 35 | restaurant.customer_order(2, "Grilled Salmon") 36 | print("\nPopular dishes in the restaurant along with their prices:") 37 | restaurant.print_menu_items() 38 | print("\nTable reserved in the Restaurant:") 39 | restaurant.print_table_reservations() 40 | print("\nPrint customer orders:") 41 | restaurant.print_customer_orders() -------------------------------------------------------------------------------- /QB/ClassesAndObjects/bankAccount.py: -------------------------------------------------------------------------------- 1 | class BankAccount: 2 | def __init__(self, account_number, date_of_opening, balance, customer_name): 3 | self.account_number = account_number 4 | self.date_of_opening = date_of_opening 5 | self.balance = balance 6 | self.customer_name = customer_name 7 | def deposit(self, amount): 8 | self.balance += amount 9 | print(f"${amount} has been deposited in your account.") 10 | def withdraw(self, amount): 11 | if amount > self.balance: 12 | print("Insufficient balance.") 13 | else: 14 | self.balance -= amount 15 | print(f"${amount} has been withdrawn from your account.") 16 | def check_balance(self): 17 | print(f"Current balance is ${self.balance}.") 18 | def print_customer_details(self): 19 | print("Name:", self.customer_name) 20 | print("Account Number:", self.account_number) 21 | print("Date of opening:", self.date_of_opening) 22 | print(f"Balance: ${self.balance}\n") # Input customer details 23 | ac_no_1 = BankAccount(2345, "01-01-2011", 1000, "Toninho Takeo") 24 | ac_no_2 = BankAccount(1234, "11-03-2011", 2000, "Astrid Rugile") 25 | ac_no_3 = BankAccount(2312, "12-01-2009", 3000, "Orli Kerenza") 26 | ac_no_4 = BankAccount(1395, "01-01-2011", 3000, "Luciana Chika") 27 | ac_no_5 = BankAccount(6345, "01-05-2011", 4000, "Toninho Takeo") 28 | print("Customer Details:") 29 | ac_no_1.print_customer_details() 30 | ac_no_2.print_customer_details() 31 | ac_no_3.print_customer_details() 32 | ac_no_4.print_customer_details() 33 | ac_no_5.print_customer_details() 34 | print("=============================") 35 | ac_no_4.print_customer_details() 36 | # Current balance is $3000. 37 | # $1000 has been deposited in your account. 38 | ac_no_4.deposit(1000) 39 | ac_no_4.check_balance() 40 | # Your current balance $4000. 41 | # You want to withdraw $5000 42 | ac_no_4.withdraw(5000) # Output: 43 | # Insufficient balance. 44 | #The customer withdraw $3400. 45 | ac_no_4.withdraw(3400) 46 | ac_no_4.check_balance() -------------------------------------------------------------------------------- /QB/file_handling.py: -------------------------------------------------------------------------------- 1 | # to read an entire text file 2 | def file_read(fname): 3 | txt = open(fname) 4 | print(txt.read()) 5 | 6 | file_read('test.txt') 7 | 8 | #--------------------------------------------------------------------------------- 9 | 10 | #to read a file line by line and store it into a list 11 | def file_read(fname): 12 | with open(fname) as f: 13 | #Content_list is the list that contains the read lines. 14 | content_list = f.readlines() 15 | print(content_list) 16 | 17 | file_read('\\test.txt\\') 18 | 19 | #--------------------------------------------------------------------------------- 20 | # to count the number of lines in a text file 21 | def file_lengthy(fname): 22 | with open(fname) as f: 23 | for i, l in enumerate(f): 24 | pass 25 | return i + 1 26 | print("Number of lines in the file: ",file_lengthy("test.txt")) 27 | 28 | #--------------------------------------------------------------------------------- 29 | # to copy the contents of a file to another file 30 | from shutil import copyfile 31 | copyfile('test.py', 'abc.py') 32 | 33 | #--------------------------------------------------------------------------------- 34 | 35 | #takes a text file as input and returns the number of words of a given text file 36 | def count_words(filepath): 37 | with open(filepath) as f: 38 | data = f.read() 39 | data.replace(",", " ") 40 | return len(data.split(" ")) 41 | 42 | print(count_words("words.txt")) 43 | 44 | #--------------------------------------------------------------------------------- 45 | # to create a file where all letters of English alphabet are listed by specified number of letters on each line. 46 | 47 | import string 48 | def letters_file_line(n): 49 | with open("words1.txt", "w") as f: 50 | alphabet = string.ascii_uppercase 51 | letters = [alphabet[i:i + n] + "\n" for i in range(0, len(alphabet), n)] 52 | f.writelines(letters) 53 | 54 | letters_file_line(3) 55 | 56 | #--------------------------------------------------------------------------------- 57 | -------------------------------------------------------------------------------- /Lab/6_bank.py: -------------------------------------------------------------------------------- 1 | from abc import ABC, abstractmethod 2 | 3 | class Bank(ABC): 4 | @abstractmethod 5 | def calculate(self): 6 | pass 7 | 8 | @abstractmethod 9 | def update(self): 10 | pass 11 | 12 | def display(self): 13 | print(f"Employee Class: {self.emp_class}") 14 | print(f"Salary: {self.calculate()}") 15 | print(f"Years of Service: {self.years_of_service}") 16 | 17 | class Customer(Bank): 18 | def __init__(self, account_type, balance): 19 | self.account_type = account_type.lower() 20 | self.balance = balance 21 | 22 | def calculate(self): 23 | if self.account_type == 'savings': 24 | self.balance += self.balance * 0.04 25 | elif self.account_type == 'current': 26 | self.balance += self.balance * 0.06 27 | else: 28 | return 0 29 | 30 | def update(self): 31 | if self.balance > 100000: 32 | self.balance += self.balance * 0.05 33 | 34 | def display(self): 35 | print(f"Account Type: {self.account_type}") 36 | print(f"Balance: {self.balance}") 37 | 38 | class Employee(Bank): 39 | def __init__(self, emp_class, basic_salary, years_of_service): 40 | self.emp_class = emp_class 41 | self.basic_salary = basic_salary 42 | self.years_of_service = years_of_service 43 | 44 | def calculate(self): 45 | if self.emp_class == 1: 46 | gross_salary = self.basic_salary + (self.basic_salary * 0.1215) + (self.basic_salary * 0.3) 47 | return gross_salary 48 | elif self.emp_class == 2: 49 | gross_salary = self.basic_salary + (self.basic_salary * 0.115) + (self.basic_salary * 0.3) 50 | return gross_salary 51 | else: 52 | return 0 53 | 54 | def update(self): 55 | if self.years_of_service > 15: 56 | self.basic_salary += self.basic_salary * 0.2 57 | 58 | customer = Customer("Savings", 500000) 59 | customer.display() 60 | customer.calculate() 61 | customer.update() 62 | customer.display() 63 | 64 | emp1 = Employee(1, 30000, 20) 65 | emp1.calculate() 66 | emp1.update() 67 | emp1.display() 68 | -------------------------------------------------------------------------------- /Lab/11_python_mysql.py: -------------------------------------------------------------------------------- 1 | import mysql.connector as sql 2 | 3 | try: 4 | connection=sql.connect( 5 | user="root", 6 | password="Root@1234", 7 | host="localhost", 8 | port="5500", 9 | database="books" 10 | ) 11 | if(connection.is_connected()): 12 | print("Connection established") 13 | 14 | except Exception as e: 15 | print("Connection cannot be established") 16 | 17 | cursor = connection.cursor() 18 | 19 | query="create table booksdata(\ 20 | id int primary key auto_increment,\ 21 | title varchar(30),\ 22 | author varchar(30),\ 23 | publication varchar(50),\ 24 | yearofpublication int,\ 25 | price int\ 26 | );" 27 | 28 | try: 29 | cursor.execute(query) 30 | connection.commit() 31 | except Exception as e: 32 | print(e) 33 | 34 | insert_query="insert into booksdata(title,author,publication,yearofpublication,price) values (%s,%s,%s,%s,%s)" 35 | 36 | values=[('Cryptography','A','AX',2000,1000), ('Alchemist','B','BX',2014,1200), ('Deep Thinking','C','CX',2003,3000), ('Data Structures', 'D', 'DX', 2022, 800)] 37 | try: 38 | cursor.executemany(insert_query,values) 39 | connection.commit() 40 | 41 | except Exception as e: 42 | print("Table insertion not done") 43 | 44 | data_query="select * from booksdata" 45 | 46 | try: 47 | cursor.execute(data_query) 48 | d1 = cursor.fetchall() 49 | print("Data:\n") 50 | 51 | for i in d1: 52 | print(i) 53 | 54 | except Exception as e: 55 | print(e) 56 | 57 | search_query1="select * from booksdata where publication='TMH' " 58 | 59 | try: 60 | cursor.execute(search_query1) 61 | s1 = cursor.fetchall() 62 | print("\n\n\n searched pika is :") 63 | 64 | for i in s1: 65 | print(i) 66 | except Exception as e: 67 | print(e) 68 | 69 | search_query1="select * from booksdata where yearofpublication between 2001 and 2020 " 70 | 71 | try: 72 | cursor.execute(search_query1) 73 | s1 = cursor.fetchall() 74 | print("\n\n\n searched pika is :") 75 | 76 | for i in s1: 77 | print(i) 78 | except Exception as e: 79 | print(e) 80 | 81 | update_query="update booksdata set price=600 where title='crpytography'" 82 | 83 | try: 84 | cursor.execute(update_query) 85 | print("Data updated successfully") 86 | connection.commit() 87 | except Exception as e: 88 | print(e) 89 | 90 | delete_query="delete from booksdata where yearofpublication < 1980" 91 | 92 | try: 93 | cursor.execute(delete_query) 94 | print("Data deleted successfully") 95 | connection.commit() 96 | except Exception as e: 97 | print(e) -------------------------------------------------------------------------------- /Lab/13_pandas.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | 3 | data = { 4 | 'ISBN': ['978-0451524935', '978-0141439617', '978-0486275482', '978-0486404528', '978-0486424786', '978-0486292748', '978-0486280554', '978-0486424564', '978-0486280530', '978-0486280974'], 5 | 'Title': ['Pride and Prejudice', 'Wuthering Heights', 'The Adventures of Tom Sawyer', 'The Importance of Being Earnest', 'The Picture of Dorian Gray', 'The War of the Worlds', 'The Time Machine', 'The Hound of the Baskervilles', 'The Invisible Man', 'Frankenstein'], 6 | 'Author': ['Jane Austen', 'Emily Bronte', 'Mark Twain', 'Oscar Wilde', 'Oscar Wilde', 'H.G. Wells', 'H.G. Wells', 'Arthur Conan Doyle', 'H.G. Wells', 'Mary Shelley'], 7 | 'Publication': ['Penguin Classics', 'Penguin Classics', 'Dover Publications', 'Dover Publications', 'Dover Publications', 'Dover Publications', 'Dover Publications', 'Dover Publications', 'Dover Publications', 'Dover Publications'], 8 | 'Year Published': [1813, 1847, 1876, 1895, 1890, 1898, 1895, 1902, 1897, 1818], 9 | 'Price': [10.99, 9.99, 4.00, 3.00, 4.00, 5.00, 5.00, 4.00, 4.00, 5.00], 10 | 'Copies sold of first edition': [5000, 4000, 6000, 3000, 2000, 8000, 7000, 4000, 6000, 4000], 11 | 'Copies sold in second edition': [3000, 2000, 4000, 2000, 1000, 5000, 4000, 3000, 4000, 2000], 12 | 'Copies sold in third edition': [2000, 1000, 2000, 1000, 500, 3000, 2000, 1000, 2000, 1000] 13 | } 14 | 15 | df = pd.DataFrame(data) 16 | 17 | # Display the number of rows and columns in dataframe 18 | print("Number of rows and columns:", df.shape) 19 | 20 | # Give the descriptive statistics of the created dataset. 21 | print("Descriptive statistics:\n", df.describe()) 22 | 23 | # Display distinct publication names for the dataset. 24 | print("Distinct publication names:\n", df['Publication'].unique()) 25 | 26 | # Display the book title and author names published by “Metro Publication” 27 | print("Books published by Metro Publication:\n", df.loc[df['Publication'] == 'Metro Publication', ['Title', 'Author']]) 28 | 29 | # Rename columns “Copies sold in first edition”, “Copies sold in second edition” and “Copies sold in third edition” to FE, SE and TE respectively 30 | df = df.rename(columns={'Copies sold of first edition': 'FE', 'Copies sold in second edition': 'SE', 'Copies sold in third edition': 'TE'}) 31 | 32 | # To add a column “Average sale” to the dataframe derived as (average of FE, SE and TE) * Price: 33 | df['Average sale'] = ((df['FE'] + df['SE'] + df['TE']) / 3) * df['Price'] 34 | 35 | # 7. Display the details of books grouped by author 36 | grouped_books = df.groupby('Author') 37 | print(grouped_books.apply(lambda x: x[['Title', 'Publication', 'Year Published', 'Price']])) 38 | 39 | # 8. For each group obtained in above query display maximum value of Average sale 40 | print(grouped_books['Price'].max()) 41 | 42 | # Removing duplicates from index 43 | # df = df.reset_index().drop_duplicates(subset=['Author', 'Publication']).set_index('Author') 44 | df = df.drop_duplicates(subset=['Author', 'Publication']) 45 | 46 | # Reshaping the dataframe 47 | reshaped_books = df.pivot(index='Author', columns='Publication', values='Title') 48 | print(reshaped_books) 49 | -------------------------------------------------------------------------------- /Lab/10_calculatorGUI.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | 3 | window = Tk() 4 | window.geometry("347x423") 5 | window.title("Calculator") 6 | 7 | def btn_click(item): 8 | global expression 9 | expression = expression + str(item) 10 | input_text.set(expression) 11 | 12 | def btn_clear(): 13 | global expression 14 | expression = "" 15 | input_text.set("") 16 | 17 | def btn_equal(): 18 | global expression 19 | result = str(eval(expression)) 20 | input_text.set(result) 21 | expression = "" 22 | 23 | expression = "" 24 | input_text = StringVar() 25 | 26 | input_frame = Frame(window, width = 312, height = 50, bd = 0, highlightbackground = "black", highlightcolor = "black", highlightthickness = 1) 27 | input_frame.pack(side = TOP) 28 | 29 | input_field = Entry(input_frame, font = ('arial', 18, 'bold'), textvariable = input_text, width = 50, bg = "#eee", bd = 0, justify = RIGHT) 30 | input_field.grid(row = 0, column = 0) 31 | input_field.pack(ipady = 10) 32 | 33 | btns_frame = Frame(window, width = 312, height = 272.5, bg = "grey") 34 | btns_frame.pack() 35 | 36 | clear = Button(btns_frame, text = "C", fg = "black", width = 32, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: btn_clear()).grid(row = 0, column = 0, columnspan = 3, padx = 1, pady = 1) 37 | divide = Button(btns_frame, text = "/", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: btn_click("/")).grid(row = 0, column = 3, padx = 1, pady = 1) 38 | 39 | seven = Button(btns_frame, text = "7", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(7)).grid(row = 1, column = 0, padx = 1, pady = 1) 40 | eight = Button(btns_frame, text = "8", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(8)).grid(row = 1, column = 1, padx = 1, pady = 1) 41 | nine = Button(btns_frame, text = "9", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(9)).grid(row = 1, column = 2, padx = 1, pady = 1) 42 | multiply = Button(btns_frame, text = "*", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: btn_click("*")).grid(row = 1, column = 3, padx = 1, pady = 1) 43 | 44 | four = Button(btns_frame, text = "4", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(4)).grid(row = 2, column = 0, padx = 1, pady = 1) 45 | five = Button(btns_frame, text = "5", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(5)).grid(row = 2, column = 1, padx = 1, pady = 1) 46 | six = Button(btns_frame, text = "6", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(6)).grid(row = 2, column = 2, padx = 1, pady = 1) 47 | minus = Button(btns_frame, text = "-", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: btn_click("-")).grid(row = 2, column = 3, padx = 1, pady = 1) 48 | 49 | one = Button(btns_frame, text = "1", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(1)).grid(row = 3, column = 0, padx = 1, pady = 1) 50 | two = Button(btns_frame, text = "2", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(2)).grid(row = 3, column = 1, padx = 1, pady = 1) 51 | three = Button(btns_frame, text = "3", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(3)).grid(row = 3, column = 2, padx = 1, pady = 1) 52 | plus = Button(btns_frame, text = "+", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: btn_click("+")).grid(row = 3, column = 3, padx = 1, pady = 1) 53 | 54 | zero = Button(btns_frame, text = "0", fg = "black", width = 21, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(0)).grid(row = 4, column = 0, columnspan = 2, padx = 1, pady = 1) 55 | point = Button(btns_frame, text = ".", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: btn_click(".")).grid(row = 4, column = 2, padx = 1, pady = 1) 56 | equals = Button(btns_frame, text = "=", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: btn_equal()).grid(row = 4, column = 3, padx = 1, pady = 1) 57 | 58 | 59 | window.mainloop() --------------------------------------------------------------------------------