├── .gitignore ├── Analysis of Algorithms (AOA) ├── 01. insertionSort.cpp ├── 02. selectionSort.cpp ├── 03. quickSort.cpp ├── 04. mergeSort.cpp ├── 05. DijkstraAlgorithm.cpp ├── 06. Fractional Knapsack.cpp ├── 08. n-queen.cpp ├── 09. subsetProblem.cpp └── 10. KMP Algorithm.cpp ├── Database Management System (DBMS) ├── Airport_Management_System_EER.png ├── README.md ├── Relational_Schema.png └── queries.txt ├── Microprocessor (MP) ├── 1902112_Tushar_MP.pdf └── MP Practicals │ ├── 1902112_C23_01.docx │ ├── 1902112_C23_02.docx │ ├── 1902112_C23_03.docx │ ├── 1902112_C23_04.docx │ ├── 1902112_C23_05.docx │ ├── 1902112_C23_06.docx │ ├── 1902112_C23_07.docx │ ├── 1902112_C23_08.docx │ ├── 1902112_C23_09.docx │ └── 1902112_C23_10.docx ├── Operating System (OS) ├── BankersAlgorithm │ └── BankersAlgorithms.java ├── DiskSchedulingPolicies │ └── DiskSchedulingPolicy.java ├── MemoryAllocationInOS │ └── MemoryAllocation.java ├── PDFs │ ├── 01. Basic Linux Commands.pdf │ └── 02. Shell Programming.pdf ├── PageReplacementAlgorithms │ ├── PageReplacementFIFO.java │ └── PageReplacementLRU.java ├── PagingSimulator │ └── PagingSimulator.cpp ├── SchedulingAlgorithms │ ├── FCFS.java │ └── ShortestJobFirst.java └── ShellScripts │ ├── 01_Add2.sh │ ├── 02_EvenOdd.sh │ ├── 03_Sum.sh │ ├── 04_EligiblityForVoting.sh │ ├── 05_DisplayingFiles.sh │ ├── 06_Factorial.sh │ └── 07_LoginCheck.sh ├── Python ├── Experiment_04.ipynb ├── PhoneBook.txt ├── Q6.py ├── assignment_01.ipynb ├── assignment_02.ipynb ├── customer_details.txt ├── employees.csv ├── experiment_01.ipynb ├── experiment_02.ipynb ├── experiment_03.ipynb ├── experiment_05.ipynb ├── experiment_06.ipynb ├── experiment_07.ipynb ├── experiment_08.py ├── experiment_09.py ├── experiment_10 │ └── FirstProject │ │ ├── FirstProject │ │ ├── __init__.py │ │ ├── asgi.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ │ ├── db.sqlite3 │ │ ├── manage.py │ │ └── myapp │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── apps.py │ │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ │ ├── models.py │ │ ├── templates │ │ └── myapp │ │ │ └── index.html │ │ ├── tests.py │ │ ├── urls.py │ │ └── views.py ├── experiment_11.ipynb ├── experiment_12.ipynb ├── my_package │ ├── Account │ │ ├── __init__.py │ │ └── salary.py │ ├── Employee │ │ ├── __init__.py │ │ ├── profile.py │ │ └── qualification.py │ └── __init__.py └── testfile.txt └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Compiled Object files 5 | *.slo 6 | *.lo 7 | *.o 8 | *.obj 9 | 10 | # Precompiled Headers 11 | *.gch 12 | *.pch 13 | 14 | # Compiled Dynamic libraries 15 | *.so 16 | *.dylib 17 | *.dll 18 | 19 | # Fortran module files 20 | *.mod 21 | *.smod 22 | 23 | # Compiled Static libraries 24 | *.lai 25 | *.la 26 | *.a 27 | *.lib 28 | 29 | # Executables 30 | *.exe 31 | *.out 32 | *.app 33 | 34 | # VSCode 35 | .vscode 36 | 37 | # ipynb 38 | .jovianrc 39 | .ipynb_checkpoints 40 | __pycache__ 41 | 42 | # Java 43 | *.class 44 | -------------------------------------------------------------------------------- /Analysis of Algorithms (AOA)/01. insertionSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | void insertionSort(vector a) 7 | { 8 | int n = a.size(); 9 | for(int j = 1; j < n; ++j) 10 | { 11 | int key = a[j]; 12 | int i = j - 1; 13 | while(i >= 0 && a[i] > key) 14 | { 15 | a[i + 1] = a[i]; 16 | i -= 1; 17 | } 18 | a[i + 1] = key; 19 | cout << "Iteration " << j << ": "; 20 | for(auto it: a) 21 | cout << it << " "; 22 | cout << endl; 23 | } 24 | cout << "\nAfter Insertion Sort: "; 25 | for(auto it: a) 26 | cout << it << " "; 27 | cout << endl; 28 | } 29 | 30 | int main() 31 | { 32 | int n; 33 | cout << "Enter the length of the array: "; 34 | cin >> n; 35 | vector a(n); 36 | cout << "Enter " << n << " elements: "; 37 | for(int i = 0; i < n; ++i) { 38 | cin >> a[i]; 39 | } 40 | insertionSort(a); 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /Analysis of Algorithms (AOA)/02. selectionSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | void selectionSort(vector a) 7 | { 8 | int n = a.size(); 9 | for(int i = 0; i < n - 1; ++i) 10 | { 11 | int index = i, minimumElement = a[i]; 12 | for(int j = i + 1; j < n; ++j) 13 | { 14 | if(minimumElement > a[j]) 15 | { 16 | minimumElement = a[j]; 17 | index = j; 18 | } 19 | } 20 | swap(a[index], a[i]); 21 | cout << "Iteration " << i << ": "; 22 | for(auto it: a) 23 | cout << it << " "; 24 | cout << endl; 25 | } 26 | cout << "\nAfter Selection Sort: "; 27 | for(auto it: a) 28 | cout << it << " "; 29 | cout << endl; 30 | } 31 | 32 | int main() 33 | { 34 | int n; 35 | cout << "Enter the length of the array: "; 36 | cin >> n; 37 | vector a(n); 38 | cout << "Enter " << n << " elements: "; 39 | for(int i = 0; i < n; ++i) { 40 | cin >> a[i]; 41 | } 42 | selectionSort(a); 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /Analysis of Algorithms (AOA)/03. quickSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int cnt, siz; 7 | 8 | int partition(int a[], int i, int j) { 9 | int p = a[i]; // p is the pivot 10 | int m = i; // S1 and S2 are initially empty 11 | for (int k = i+1; k <= j; k++) { // explore the unknown region 12 | if (a[k] < p) { // case 2 13 | m++; 14 | swap(a[k], a[m]); // C++ STL algorithm std::swap 15 | } // notice that we do nothing in case 1: a[k] >= p 16 | } 17 | swap(a[i], a[m]); // final step, swap pivot with a[m] 18 | 19 | cout << "Pivot Index: " << m << "\t\t|\t"; 20 | cout << "Iteration " << cnt++ << ": "; 21 | for(int i = 0 ; i < siz; ++i) 22 | cout << a[i] << " "; 23 | cout << endl; 24 | return m; // return the index of pivot 25 | } 26 | 27 | 28 | void quickSort(int a[], int low, int high) { 29 | if (low < high) { 30 | int m = partition(a, low, high); // O(N) 31 | // a[low..high] ~> a[low..m–1], pivot, a[m+1..high] 32 | quickSort(a, low, m-1); // recursively sort left subarray 33 | // a[m] = pivot is already sorted after partition 34 | quickSort(a, m+1, high); // then sort right subarray 35 | } 36 | } 37 | 38 | int main() 39 | { 40 | int n; 41 | cout << "Enter the length of the array: "; 42 | cin >> n; 43 | siz = n; 44 | int a[n]; 45 | cout << "Enter " << n << " elements: "; 46 | for(int i = 0; i < n; ++i) { 47 | cin >> a[i]; 48 | } 49 | cout << endl; 50 | quickSort(a, 0, n - 1); 51 | cout << "\nAfter Quick Sort: "; 52 | for(auto it: a) 53 | cout << it << " "; 54 | cout << endl; 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /Analysis of Algorithms (AOA)/04. mergeSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | int siz, cnt; 6 | // Merges two subarrays of arr[]. 7 | // First subarray is arr[l..m] 8 | // Second subarray is arr[m+1..r] 9 | void merge(int arr[], int l, int m, int r) 10 | { 11 | int n1 = m - l + 1; 12 | int n2 = r - m; 13 | 14 | // Create temp arrays 15 | int L[n1], R[n2]; 16 | 17 | // Copy data to temp arrays L[] and R[] 18 | for (int i = 0; i < n1; i++) 19 | L[i] = arr[l + i]; 20 | for (int j = 0; j < n2; j++) 21 | R[j] = arr[m + 1 + j]; 22 | 23 | // Merge the temp arrays back into arr[l..r] 24 | // Initial index of first subarray 25 | int i = 0; 26 | // Initial index of second subarray 27 | int j = 0; 28 | // Initial index of merged subarray 29 | int k = l; 30 | 31 | while (i < n1 && j < n2) { 32 | if (L[i] <= R[j]) { 33 | arr[k] = L[i]; 34 | i++; 35 | } 36 | else { 37 | arr[k] = R[j]; 38 | j++; 39 | } 40 | k++; 41 | } 42 | 43 | // Copy the remaining elements of 44 | // L[], if there are any 45 | while (i < n1) { 46 | arr[k] = L[i]; 47 | i++; 48 | k++; 49 | } 50 | 51 | // Copy the remaining elements of 52 | // R[], if there are any 53 | while (j < n2) { 54 | arr[k] = R[j]; 55 | j++; 56 | k++; 57 | } 58 | 59 | cout << "Iteration: " << cnt++ << ": "; 60 | for(int i = 0; i < siz; ++i) 61 | cout << arr[i] << " "; 62 | cout << endl; 63 | } 64 | 65 | // l is for left index and r is right index of the sub-array of arr to be sorted; 66 | void mergeSort(int arr[],int l,int r){ 67 | if(l>=r){ 68 | //returns recursively 69 | return; 70 | } 71 | int m =l+ (r-l)/2; 72 | mergeSort(arr,l,m); 73 | mergeSort(arr,m+1,r); 74 | merge(arr,l,m,r); 75 | } 76 | 77 | int main() 78 | { 79 | int n; 80 | cout << "Enter the length of the array: "; 81 | cin >> n; 82 | siz = n; 83 | int a[n]; 84 | cout << "Enter " << n << " elements: "; 85 | for(int i = 0; i < n; ++i) { 86 | cin >> a[i]; 87 | } 88 | cout << endl; 89 | mergeSort(a, 0, n - 1); 90 | cout << "\nAfter Merge Sort: "; 91 | for(auto it: a) 92 | cout << it << " "; 93 | cout << endl; 94 | return 0; 95 | } 96 | -------------------------------------------------------------------------------- /Analysis of Algorithms (AOA)/05. DijkstraAlgorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define vertex 7 /*It is the total no of verteices in the graph*/ 4 | 5 | /*A method to find the vertex with minimum distance which is not yet included in Dset*/ 6 | int minimumDist(int dist[], bool Dset[]) 7 | { 8 | /*initialize min with the maximum possible value as infinity does not exist */ 9 | int min=INT_MAX,index; 10 | for(int v=0;v 2 | #include 3 | 4 | using namespace std; 5 | 6 | typedef struct { 7 | int v; 8 | int w; 9 | float d; 10 | } Item; 11 | 12 | void input(Item items[],int sizeOfItems) { 13 | cout << "Enter total "<< sizeOfItems <<" item's values and weight" << 14 | endl; 15 | for(int i = 0; i < sizeOfItems; i++) { 16 | cout << "Enter "<< i+1 << " Value: "; 17 | cin >> items[i].v; 18 | cout << "Enter "<< i+1 << " Weight: "; 19 | cin >> items[i].w; 20 | } 21 | } 22 | 23 | void display(Item items[], int sizeOfItems) { 24 | int i; 25 | cout << "values: "; 26 | for(i = 0; i < sizeOfItems; i++) { 27 | cout << items[i].v << "\t"; 28 | } 29 | cout << endl << "weight: "; 30 | for (i = 0; i < sizeOfItems; i++) { 31 | cout << items[i].w << "\t"; 32 | } 33 | cout << endl; 34 | } 35 | 36 | bool compare(Item i1, Item i2) { 37 | return (i1.d > i2.d); 38 | } 39 | 40 | float knapsack(Item items[], int sizeOfItems, int W) { 41 | int i, j, pos; 42 | Item mx, temp; 43 | float totalValue = 0, totalWeight = 0; 44 | 45 | for (i = 0; i < sizeOfItems; i++) { 46 | items[i].d = items[i].v / items[i].w; 47 | } 48 | 49 | sort(items, items+sizeOfItems, compare); 50 | for(i=0; i>n; 70 | Item items[n]; 71 | input(items, n); 72 | cout << "Entered data \n"; 73 | display(items,n); 74 | cout<< "Enter Knapsack weight \n"; 75 | cin >> W; 76 | float mxVal = knapsack(items, n, W); 77 | cout << "Max value for "<< W <<" weight is "<< mxVal; 78 | } 79 | -------------------------------------------------------------------------------- /Analysis of Algorithms (AOA)/08. n-queen.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define N 5 4 | void printBoard(int board[N][N]) { 5 | for (int i = 0; i < N; i++) { 6 | for (int j = 0; j < N; j++) 7 | cout << board[i][j] << " "; 8 | cout << endl; 9 | } 10 | } 11 | bool isValid(int board[N][N], int row, int col) { 12 | for (int i = 0; i < col; i++) //check whether there is queen in the left or not 13 | if (board[row][i]) 14 | return false; 15 | for (int i=row, j=col; i>=0 && j>=0; i--, j--) 16 | if (board[i][j]) //check whether there is queen in the left upper diagonal or not 17 | return false; 18 | for (int i=row, j=col; j>=0 && i= N) //when N queens are placed successfully 25 | return true; 26 | for (int i = 0; i < N; i++) { //for each row, check placing of queen is possible or not 27 | if (isValid(board, i, col) ) { 28 | board[i][col] = 1; //if validate, place the queen at place (i, col) 29 | if ( solveNQueen(board, col + 1)) //Go for the other columns recursively 30 | return true; 31 | board[i][col] = 0; //When no place is vacant remove that queen 32 | } 33 | } 34 | return false; //when no possible order is found 35 | } 36 | bool checkSolution() { 37 | int board[N][N]; 38 | for(int i = 0; i 2 | #define TRUE 1 3 | #define FALSE 0 4 | 5 | int inc[50], w[50], sum, n; 6 | 7 | int promising(int i, int wt, int total) 8 | { 9 | return (((wt + total) >= sum) && ((wt == sum) || (wt + w[i + 1] <= sum))); 10 | } 11 | 12 | void sumOfSubset(int i, int wt, int total) 13 | { 14 | int j; 15 | if (promising(i, wt, total)) 16 | { 17 | if (wt == sum) 18 | { 19 | printf("\n{\t"); 20 | for (j = 0; j <= i; j++) 21 | if (inc[j]) 22 | printf("%d\t", w[j]); 23 | printf("}\n"); 24 | } 25 | else 26 | { 27 | inc[i + 1] = TRUE; 28 | sumOfSubset(i + 1, wt + w[i + 1], total - w[i + 1]); 29 | inc[i + 1] = FALSE; 30 | sumOfSubset(i + 1, wt, total - w[i + 1]); 31 | } 32 | } 33 | } 34 | 35 | int main() 36 | { 37 | int i, j, n, temp, total = 0; 38 | printf("Enter number of elements in the set : "); 39 | scanf("%d", &n); 40 | printf("Enter %d number to add to the set : ", n); 41 | for (i = 0; i < n; i++) 42 | { 43 | scanf("%d", &w[i]); 44 | total += w[i]; 45 | } 46 | printf("Input the sum value to create sub set : "); 47 | scanf("%d", &sum); 48 | //sort in ascending order 49 | for (i = 0; i <= n; i++) 50 | for (j = 0; j < n - 1; j++)if (w[j] > w[j + 1]) 51 | { 52 | temp = w[j]; 53 | w[j] = w[j + 1]; 54 | w[j + 1] = temp; 55 | } 56 | printf("\nThe given %d numbers in ascending order: \n", n); 57 | for (i = 0; i < n; i++) 58 | printf("%d\t", w[i]); 59 | if ((total < sum)) 60 | printf("\nSubset cannot be made."); 61 | else 62 | { 63 | for (i = 0; i < n; i++) 64 | inc[i] = 0; 65 | printf("\nThe solutions is/are:"); 66 | sumOfSubset(-1, 0, total); 67 | } 68 | return 0; 69 | } 70 | -------------------------------------------------------------------------------- /Analysis of Algorithms (AOA)/10. KMP Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | void KMP(char *str, char *word, int *ptr) 6 | { 7 | int i = 0, j = 0; 8 | while ((i + j) < strlen(str)) 9 | { 10 | if (word[j] == str[i + j]) 11 | { 12 | if (j == (strlen(word) - 1)) 13 | { 14 | printf("%s located at the index %d\n", word, i); 15 | return; 16 | } 17 | j = j + 1; 18 | } 19 | else 20 | { 21 | i = i + j - ptr[j]; 22 | if (ptr[j] > -1) 23 | { 24 | j = ptr[j]; 25 | } 26 | else 27 | { 28 | j = 0; 29 | } 30 | } 31 | } 32 | } 33 | 34 | void findOverlap(char *word, int *ptr) 35 | { 36 | int i = 2, j = 0, len = strlen(word); 37 | ptr[0] = -1; 38 | ptr[1] = 0; 39 | while (i < len) 40 | { 41 | if (word[i - 1] == word[j]) 42 | { 43 | j = j + 1; 44 | ptr[i] = j; 45 | i = i + 1; 46 | } 47 | else if (j > 0) 48 | { 49 | j = ptr[j]; 50 | } 51 | else 52 | { 53 | ptr[i] = 0; 54 | i = i + 1; 55 | } 56 | } 57 | return; 58 | } 59 | 60 | int main() 61 | { 62 | char word[256], str[1024]; 63 | int *ptr, i; 64 | printf("Enter Text :--> "); 65 | fgets(str, 1024, stdin); 66 | str[strlen(str) - 1] = '\0'; 67 | printf("Enter Pattern :--> "); 68 | fgets(word, 256, stdin); 69 | word[strlen(word) - 1] = '\0'; 70 | ptr = (int *)calloc(1, sizeof(int) * (strlen(word))); 71 | findOverlap(word, ptr); 72 | KMP(str, word, ptr); 73 | return 0; 74 | } 75 | -------------------------------------------------------------------------------- /Database Management System (DBMS)/Airport_Management_System_EER.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tusharnankani/sem4-assignments/3ae356e346583a736e5863a73c34de2a706ea45f/Database Management System (DBMS)/Airport_Management_System_EER.png -------------------------------------------------------------------------------- /Database Management System (DBMS)/README.md: -------------------------------------------------------------------------------- 1 | # Assignment 1 2 | 3 | ## Extended Entity Relationship (EER) Diagram 4 | 5 | ![](Airport_Management_System_EER.png) 6 | 7 | # _Relational Schema_ 8 | 9 | ![](Relational_Schema.png) 10 | -------------------------------------------------------------------------------- /Database Management System (DBMS)/Relational_Schema.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tusharnankani/sem4-assignments/3ae356e346583a736e5863a73c34de2a706ea45f/Database Management System (DBMS)/Relational_Schema.png -------------------------------------------------------------------------------- /Database Management System (DBMS)/queries.txt: -------------------------------------------------------------------------------- 1 | //Create all Tables: 2 | CREATE TABLE AIRPORT( 3 | AIRPORT_NAME VARCHAR(20) NOT NULL, 4 | CITY VARCHAR(20), 5 | STATE VARCHAR(20), 6 | PRIMARY KEY (AIRPORT_NAME) 7 | ); 8 | CREATE TABLE AIRLINE( 9 | AIRLINE_ID INT NOT NULL, 10 | AIRLINE_NAME VARCHAR(10), 11 | AIRPORT_NAME VARCHAR(10), 12 | FOREIGN KEY (AIRPORT_NAME) REFERENCES AIRPORT(AIRPORT_NAME) 13 | ); 14 | CREATE TABLE CONTAINS( 15 | AIRPORT_NAME VARCHAR(20), 16 | AIRLINE_ID INT, 17 | FOREIGN KEY (AIRPORT_NAME) REFERENCES AIRPORT(AIRPORT_NAME), 18 | FOREIGN KEY (AIRLINE_ID) REFERENCES AIRLINE(AIRLINE_ID) 19 | ); 20 | 21 | CREATE TABLE FLIGHT( 22 | FLIGHT_NO INT NOT NULL, 23 | SOURCE VARCHAR(20) NOT NULL, 24 | DESTINATION VARCHAR(20) NOT NULL, 25 | D_TIME TIME, 26 | A_TIME TIME, 27 | DURATION INT NOT NULL, 28 | AIRLINE_ID INT, 29 | FOREIGN KEY (AIRLINE_ID) REFERENCES AIRLINE(AIRLINE_ID) 30 | ); 31 | CREATE TABLE EMPLOYEE( 32 | E_ID INT, 33 | NAME VARCHAR(20), 34 | ADDRESS VARCHAR(20), 35 | SEX VARCHAR(10), 36 | SALARY INT, 37 | AGE INT, 38 | AIRPORT_NAME VARCHAR(20), 39 | FOREIGN KEY (AIRPORT_NAME) REFERENCES AIRPORT(AIRPORT_NAME) 40 | ); 41 | CREATE TABLE EMP_PHONE_NO( 42 | E_ID INT, 43 | PHONE_NO VARCHAR(11), 44 | FOREIGN KEY (E_ID) REFERENCES EMPLOYEE(E_ID) 45 | ); 46 | 47 | 48 | CREATE TABLE PASSENGER( 49 | PASSPORT_NO VARCHAR(20) NOT NULL, 50 | NAME VARCHAR(20) NOT NULL, 51 | ADDRESS VARCHAR(20), 52 | SEX VARCHAR(5), 53 | DOB DATE, 54 | AGE INT, 55 | FLIGHT_NO INT, 56 | TICKET_NO VARCHAR(20), 57 | FOREIGN KEY (FLIGHT_NO) REFERENCES FLIGHT(FLIGHT_NO), 58 | FOREIGN KEY (TICKET_NO) REFERENCES TICKET(TICKET_NO) 59 | ); 60 | CREATE TABLE SERVES( 61 | E_ID INT, 62 | PASSPORT_NO VARCHAR(20), 63 | FOREIGN KEY (E_ID) REFERENCES EMPLOYEE(E_ID), 64 | FOREIGN KEY (PASSPORT_NO) REFERENCES PASSENGER(PASSPORT_NO) 65 | ); 66 | CREATE TABLE PASSENGER_PHONE_NO( 67 | PASSPORT_NO VARCHAR(20), 68 | PHONE_NO VARCHAR(11), 69 | FOREIGN KEY (PASSPORT_NO) REFERENCES PASSENGER(PASSPORT_NO) 70 | ); 71 | 72 | CREATE TABLE TICKET( 73 | TICKET_NO VARCHAR(20) NOT NULL, 74 | AIRLINE_NAME VARCHAR(20) NOT NULL, 75 | PRICE INT NOT NULL, 76 | SEAT_NO VARCHAR(20), 77 | CLASS VARCHAR(5), 78 | D_TIME TIME, 79 | A_TIME TIME, 80 | DURATION INT, 81 | DESTINATION VARCHAR(20), 82 | SOURCE VARCHAR(20), 83 | PASSPORT_NO VARCHAR(20), 84 | PASSENGER_NAME VARCHAR(20), 85 | FOREIGN KEY (PASSPORT_NO) REFERENCES PASSENGER(PASSPORT_NO), 86 | FOREIGN KEY (PASSENGER_NAME) REFERENCES PASSENGER(NAME) 87 | ); 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | // EXP3 ALTER COMMANDS: 97 | CREATE TABLE AIRPORT( 98 | AIRPORT_NAME VARCHAR(20), 99 | CITY VARCHAR(20), 100 | STATE VARCHAR(20) 101 | ); 102 | CREATE TABLE AIRLINE( 103 | AIRLINE_ID INTEGER NOT NULL, 104 | AIRLINE_NAME VARCHAR(10), 105 | AIRPORT_NAME VARCHAR(10) 106 | ); 107 | ALTER TABLE AIRPORT ADD PRIMARY KEY (AIRPORT_NAME); 108 | ALTER TABLE AIRLINE ADD CONSTRAINT FK_NAME FOREIGN KEY (AIRPORT_NAME) REFERENCES AIRPORT(AIRPORT_NAME); 109 | ALTER TABLE AIRPORT DROP COLUMN STATE; 110 | ALTER TABLE AIRPORT ADD STATE VARCHAR(20); 111 | ALTER TABLE AIRPORT MODIFY AIRPORT_NAME VARCHAR(20) NOT NULL; 112 | ALTER TABLE AIRPORT RENAME COLUMN AIRPORT_NAME TO AIR_NAME; 113 | ALTER TABLE AIRPORT RENAME TO AIRPORT_DETAILS; 114 | ALTER TABLE AIRPORT_DETAILS RENAME TO AIRPORT; 115 | ALTER TABLE AIRPORT ADD CHECK (CITY = ‘Mumbai’); 116 | 117 | INSERT INTO AIRPORT VALUES (‘Shivaji’, ‘Mumbai’, ‘Maharashtra’); 118 | INSERT INTO AIRPORT VALUES (‘Shivaji’, ‘Delhi’, ‘Maharashtra’); 119 | 120 | SELECT * FROM AIRPORT; 121 | TRUNCATE TABLE AIRPORT; 122 | DROP TABLE AIRPORT; 123 | DROP TABLE AIRLINE; 124 | 125 | // EXP 4 INSERT INSTRUCTIONS: 126 | INSERT INTO EMPLOYEE VALUES(1,'parth','mumbai','M','40000','19','mumbai') 127 | INSERT INTO EMPLOYEE VALUES(1,'ramesh','mumbai','M','30000','20','mumbai') 128 | INSERT INTO EMPLOYEE VALUES(2,'shikha','pune','F','30000','19','pune') 129 | INSERT INTO EMPLOYEE VALUES(2,'raj','pune','M','25000','20','pune') 130 | INSERT INTO EMPLOYEE VALUES(3,'ram','delhi','M','20000','23','delhi') 131 | INSERT INTO EMPLOYEE VALUES(3,'rani','delhi','F','22000','19','delhi') 132 | 133 | select * from EMPLOYEE 134 | 135 | 136 | INSERT INTO EMP_PHONE_NO VALUES(1,'1111111111'); 137 | INSERT INTO EMP_PHONE_NO VALUES(3,'3333333333'); 138 | INSERT INTO EMP_PHONE_NO VALUES(6,'6666666666'); 139 | 140 | 141 | INSERT INTO AIRPORT VALUES('mumbai', 'mumbai'); 142 | INSERT INTO AIRPORT VALUES('delhi', 'delhi'); 143 | INSERT INTO AIRPORT VALUES('pune', 'pune'); 144 | 145 | 146 | 147 | 148 | 149 | INSERT INTO AIRPORT VALUES('mumbai', 'mumbai'); 150 | INSERT INTO AIRPORT VALUES('delhi', 'delhi'); 151 | INSERT INTO AIRPORT VALUES('pune', 'pune'); 152 | 153 | 154 | 155 | 156 | 157 | 158 | // EXP 6 NESTED QUERIES (PLEASE CHECK) 159 | CREATE TABLE AIRPORT( 160 | AIRPORT_NAME VARCHAR(20) NOT NULL, 161 | CITY VARCHAR(20), 162 | STATE VARCHAR(20), 163 | PRIMARY KEY (AIRPORT_NAME), 164 | 165 | ); 166 | 167 | INSERT INTO AIRPORT VALUES('mumbai', 'mumbai', 'maharashtra'); 168 | INSERT INTO AIRPORT VALUES('delhi', 'delhi', 'delhi'); 169 | INSERT INTO AIRPORT VALUES('pune', 'pune', 'maharashtra'); 170 | 171 | CREATE TABLE AIRLINE( 172 | AIRLINE_ID INT NOT NULL, 173 | AIRLINE_NAME VARCHAR(20), 174 | AIRPORT_NAME VARCHAR(20), 175 | PRIMARY KEY (AIRLINE_ID), 176 | FOREIGN KEY (AIRPORT_NAME) REFERENCES AIRPORT(AIRPORT_NAME) 177 | ); 178 | 179 | INSERT INTO AIRLINE VALUES(123,'Mumbai Airlines','mumbai'); 180 | INSERT INTO AIRLINE VALUES(124,'Delhi Airlines','delhi'); 181 | 182 | CREATE TABLE FLIGHT( 183 | FLIGHT_NO VARCHAR(10) NOT NULL, 184 | F_SOURCE VARCHAR(20) NOT NULL, 185 | DESTINATION VARCHAR(20) NOT NULL, 186 | D_TIME VARCHAR(5), 187 | A_TIME VARCHAR(5), 188 | F_DURATION INTEGER NOT NULL, 189 | AIRLINE_ID INT NOT NULL, 190 | PRIMARY KEY (FLIGHT_NO), 191 | FOREIGN KEY (AIRLINE_ID) REFERENCES AIRLINE(AIRLINE_ID) 192 | ); 193 | 194 | INSERT INTO FLIGHT VALUES('12345','Mumbai','Delhi', '1500', '2100', 360,123); 195 | INSERT INTO FLIGHT VALUES('12356','Delhi', 'Mumbai', '1800', '2100', 180,124); 196 | INSERT INTO FLIGHT VALUES('12389','Delhi', 'Mumbai', '0100', '0330', 150,124); 197 | 198 | CREATE TABLE EMPLOYEE( 199 | E_ID INT, 200 | NAME VARCHAR(20), 201 | ADDRESS VARCHAR(20), 202 | SEX VARCHAR(10), 203 | SALARY INT, 204 | AGE INT, 205 | AIRPORT_NAME VARCHAR(20), 206 | FOREIGN KEY (AIRPORT_NAME) REFERENCES AIRPORT(AIRPORT_NAME), 207 | PRIMARY KEY (E_ID) 208 | ); 209 | INSERT INTO EMPLOYEE VALUES(1,'parth','mumbai','M','40000','19','mumbai'); 210 | INSERT INTO EMPLOYEE VALUES(2,'ramesh','mumbai','M','30000','20','mumbai'); 211 | INSERT INTO EMPLOYEE VALUES(3,'shikha','pune','F','30000','19','pune'); 212 | INSERT INTO EMPLOYEE VALUES(4,'raj','pune','M','25000','20','pune'); 213 | INSERT INTO EMPLOYEE VALUES(5,'ram','delhi','M','20000','23','delhi'); 214 | INSERT INTO EMPLOYEE VALUES(6,'rani','delhi','F','22000','19','delhi'); 215 | 216 | CREATE TABLE EMP_PHONE_NO( 217 | E_ID INT, 218 | PHONE_NO VARCHAR(11), 219 | FOREIGN KEY (E_ID) REFERENCES EMPLOYEE(E_ID) 220 | ); 221 | SELECT * FROM EMP_PHONE_NO; 222 | INSERT INTO EMP_PHONE_NO VALUES(1,'1111111111'); 223 | INSERT INTO EMP_PHONE_NO VALUES(1,'3333333333'); 224 | INSERT INTO EMP_PHONE_NO VALUES(6,'6666666666'); 225 | INSERT INTO EMP_PHONE_NO VALUES(5,'5555555555'); 226 | 227 | 228 | CREATE TABLE TICKET( 229 | TICKET_NO INT NOT NULL, 230 | AIRLINE_NAME VARCHAR(20) NOT NULL, 231 | PRICE INT NOT NULL, 232 | SEAT_NO VARCHAR(20), 233 | CLASS VARCHAR(20), 234 | D_TIME VARCHAR(5), 235 | A_TIME VARCHAR(5), 236 | DURATION INT, 237 | DESTINATION VARCHAR(20), 238 | SOURCE VARCHAR(20), 239 | PRIMARY KEY(TICKET_NO) 240 | ); 241 | INSERT INTO TICKET VALUES(786, 'SpiceJet', 6000, 'A-2' , 'First Class', '1500', '2100', 360, 'Delhi', 'Mumbai'); 242 | INSERT INTO TICKET VALUES(777, 'Mumbai Airlines', 4000, 'H-42' , 'Second Class','1800', '2100', 180, 'Delhi', 'Mumbai'); 243 | 244 | CREATE TABLE PASSENGER( 245 | PASSPORT_NO INT NOT NULL, 246 | NAME VARCHAR(20) NOT NULL, 247 | ADDRESS VARCHAR(20), 248 | SEX VARCHAR(5), 249 | DOB DATE, 250 | AGE INT, 251 | FLIGHT_NO VARCHAR(20) NOT NULL, 252 | TICKET_NO INT NOT NULL, 253 | FOREIGN KEY (FLIGHT_NO) REFERENCES FLIGHT(FLIGHT_NO), 254 | FOREIGN KEY (TICKET_NO) REFERENCES TICKET(TICKET_NO), 255 | PRIMARY KEY (PASSPORT_NO) 256 | ); 257 | INSERT INTO PASSENGER VALUES(12346,'Parth','A22','Male',date'2002-03-28',5,'12356',786); 258 | INSERT INTO PASSENGER VALUES(8965, 'Tushar', 'B22', 'Male', date'2001-08-12', 19, '12345', 777); 259 | INSERT INTO PASSENGER VALUES(4928, 'Raj', 'D45', 'Male', date'1972-06-13', 64, '12345', 786); 260 | 261 | 262 | CREATE TABLE PASSENGER_PHONE_NO( 263 | PASSPORT_NO int, 264 | PHONE_NO VARCHAR(11), 265 | FOREIGN KEY (PASSPORT_NO) REFERENCES PASSENGER(PASSPORT_NO) 266 | ); 267 | INSERT INTO PASSENGER_PHONE_NO VALUES(12346,'1111111111'); 268 | INSERT INTO PASSENGER_PHONE_NO VALUES(12346,'3333333333'); 269 | INSERT INTO PASSENGER_PHONE_NO VALUES(8965,'6666666666'); 270 | 271 | 272 | 273 | 1. SELECT NAME AND SALARY OF EMPLOYEE HAVING PHONE NUMBER: 274 | 275 | SELECT E.NAME, E.SALARY 276 | FROM EMPLOYEE E 277 | WHERE E_ID IN 278 | (SELECT EP.E_ID 279 | FROM EMP_PHONE_NO EP 280 | WHERE EP.E_ID=E.E_ID); 281 | 282 | 2. SELECT NAME AND SALARY AND ID IN WHICH E_ID IS BETWEEN 1 TO 5 having phone number: 283 | 284 | select E.E_ID, E.NAME, E.SALARY 285 | from EMPLOYEE E 286 | where E.E_ID in 287 | (select EP.E_ID 288 | from EMP_PHONE_NO EP 289 | where EP.E_ID in (1,5)); 290 | 291 | 292 | 3. SELECT NAME BASED ON AIRPORT_NAME WHERE CITY IS MUMBAI: 293 | 294 | select E.NAME, E.E_ID 295 | from EMPLOYEE E 296 | where E.AIRPORT_NAME in 297 | (select A.AIRPORT_NAME 298 | from AIRPORT A 299 | where A.CITY='mumbai'); 300 | 301 | 302 | 4. SELECT NAME AND SEX WHERE EMPLOYEE ID IS GREATER THAN 3 AND HAVING PHONE NUMBER 303 | 304 | SELECT E.E_ID, E.NAME, E.SEX 305 | FROM EMPLOYEE E 306 | WHERE E.E_ID IN (SELECT EP.E_ID 307 | FROM EMP_PHONE_NO EP 308 | WHERE E.E_ID = EP.E_ID AND EP.E_ID>=3); 309 | 310 | 5.SELECT EMPLOYEE NAME, ID HAVING MULTIPLE PHONE NUMBERS: 311 | 312 | SELECT E.NAME, E.E_ID 313 | FROM EMPLOYEE E 314 | WHERE E.E_ID IN 315 | (SELECT EP.E_ID 316 | FROM EMP_PHONE_NO EP 317 | GROUP BY EP.E_ID 318 | HAVING COUNT(*) > 1); 319 | 320 | 6. SELECT NAME, ADDRESS, AGE, SEX WHERE CITY IS Mumbai or Delhi 321 | 322 | SELECT E.NAME, E.ADDRESS, E.AGE, E.SEX 323 | FROM EMPLOYEE E 324 | WHERE E.AIRPORT_NAME IN 325 | (SELECT A.AIRPORT_NAME 326 | FROM AIRPORT A 327 | WHERE A.CITY in ('mumbai', 'delhi')); 328 | 329 | 7. SELECT NAME, PASSPORT NUMBER OF PASSENGERS WHERE AIRLINE_NAME IS Mumbai Airlines 330 | 331 | SELECT P.NAME, P.PASSPORT_NO 332 | FROM PASSENGER P 333 | WHERE P.TICKET_NO IN 334 | (SELECT T.TICKET_NO 335 | FROM TICKET T 336 | WHERE T.AIRLINE_NAME = 'Mumbai Airlines'); 337 | 338 | 8. SELECT NAME, PASSPORT NUMBER OF PASSENGERS WHERE CLASS IS First Class 339 | 340 | SELECT P.NAME, P.PASSPORT_NO 341 | FROM PASSENGER P 342 | WHERE P.TICKET_NO IN 343 | (SELECT T.TICKET_NO 344 | FROM TICKET T 345 | WHERE T.CLASS = 'First Class'); 346 | 347 | 348 | 349 | 9. SELECT PASSENGER NAME HAVING MULTIPLE PHONE NUMBERS: 350 | 351 | SELECT P.NAME 352 | FROM PASSENGER P 353 | WHERE P.PASSPORT_NO IN 354 | (SELECT PPN.PASSPORT_NO 355 | FROM PASSENGER_PHONE_NO PPN 356 | GROUP BY PPN.PASSPORT_NO 357 | HAVING COUNT(*)>1); 358 | 359 | 360 | 361 | 10. SELECT PASSENGER NAME, SEX, TICKET NUMBER HAVING FLIGHT DESTINATION AS Delhi 362 | 363 | SELECT P.NAME, P.SEX, P.TICKET_NO 364 | FROM PASSENGER P 365 | WHERE P.FLIGHT_NO IN 366 | (SELECT F.FLIGHT_NO 367 | FROM FLIGHT F 368 | WHERE F.DESTINATION = 'Delhi'); 369 | 370 | 371 | //COMPLEX QURIES: 372 | 1. SELECT EMPLOYEE ID, PHONE NUMBER, AND AIRPORT NAME WHERE CITY IS Delhi 373 | 374 | select E.E_ID,P.PHONE_NO,A.AIRPORT_NAME 375 | from EMPLOYEE E,EMP_PHONE_NO P,AIRPORT A 376 | where E.E_ID=P.E_ID 377 | and E.AIRPORT_NAME=A.AIRPORT_NAME 378 | and A.CITY in ('delhi'); 379 | 380 | 2. Select Flight Number, Airline ID, Airline Name, Source, Destination whose Duration is greater than 3 hours, and Destination is Delhi or Mumbai. 381 | 382 | select F.FLIGHT_NO, AL.AIRLINE_ID, F.F_SOURCE, F.DESTINATION 383 | from FLIGHT F, AIRLINE AL 384 | where (F.F_DURATION >= 3*60) AND F.DESTINATION in ('Mumbai','Delhi') AND AL.AIRLINE_ID = F.AIRLINE_ID; 385 | 386 | 3. Select children (with age 10 or less) Senior Citizens (with age 60 or greater) - Passport Number, Name, Age, Flight Number, Ticket Number, travelling from Delhi. 387 | Method 1 388 | select P.PASSPORT_NO, P.NAME, P.AGE, P.FLIGHT_NO, T.TICKET_NO 389 | from PASSENGER P, TICKET T 390 | where T.SOURCE in ('Delhi') and (P.AGE >= 60 or P.AGE <= 10); 391 | 392 | Method 2 393 | select P.PASSPORT_NO, P.NAME, P.AGE, P.FLIGHT_NO, T.TICKET_NO 394 | from PASSENGER P, TICKET T 395 | where (P.AGE >= 60 or P.AGE <= 10) and T.SOURCE in 396 | (select T.SOURCE 397 | from TICKET T 398 | where T.SOURCE = 'Delhi'); 399 | 400 | 4. Select Senior Citizens (with age 60 or greater) - Passport Number, Name, Age, Flight Number, Ticket Number, Seat number travelling to Delhi, with the SpiceJet Airline 401 | 402 | select P.PASSPORT_NO, P.NAME, P.AGE, P.FLIGHT_NO, T.TICKET_NO, T.SEAT_NO 403 | from PASSENGER P, TICKET T 404 | where (T.DESTINATION) in ('Delhi') and (P.AGE >= 60) and T.AIRLINE_NAME in 405 | (select AIRLINE_NAME 406 | from TICKET 407 | where AIRLINE_NAME = 'SpiceJet'); 408 | 409 | 410 | 411 | // Views in DBMS 412 | CREATE TABLE tblAirport( 413 | AIRPORT_NAME VARCHAR(20) NOT NULL, 414 | CITY VARCHAR(20), 415 | STATE VARCHAR(20), 416 | PRIMARY KEY (AIRPORT_NAME) 417 | ) 418 | 419 | describe tblAIRPORT 420 | 421 | CREATE TABLE tblAirline( 422 | AIRLINE_ID INT NOT NULL, 423 | AIRLINE_NAME VARCHAR(10), 424 | AP_NAME VARCHAR(10), 425 | PRIMARY KEY (AIRLINE_ID) 426 | ) 427 | 428 | CREATE TABLE FLIGHT( 429 | FLIGHT_NO INT NOT NULL, 430 | SOURCE VARCHAR(20) NOT NULL, 431 | DESTINATION VARCHAR(20) NOT NULL, 432 | D_TIME INT, 433 | A_TIME INT, 434 | DURATION INT NOT NULL, 435 | A_ID INT, 436 | FOREIGN KEY (A_ID) REFERENCES tblAirline(AIRLINE_ID) 437 | ); 438 | 439 | 440 | Insert into tblAirport values ('Mum','Mumbai','Maharashtra') 441 | 442 | Insert into tblAirport values ('Del','Delhi','Haryana') 443 | 444 | Insert into tblAirport values ('Kol','Kolkata','West Bengal') 445 | 446 | Insert into tblAirport values ('Ban','Bangalore','Karnataka') 447 | 448 | 449 | Insert into tblAirline values (1,'Indigo','Mum') 450 | 451 | Insert into tblAirline values (2,'Spicejet','Del') 452 | 453 | Insert into tblAirline values (3,'Air India','Kol') 454 | 455 | Insert into tblAirline values (4,'Air India','Ban') 456 | 457 | 458 | Insert into FLIGHT values (11,'Mum','Del',2,4,2,1) 459 | 460 | Insert into FLIGHT values (22,'Del','Kol',3,4,1,2) 461 | 462 | Insert into FLIGHT values (33,'Kol','Che',11,2,3,3) 463 | 464 | Insert into FLIGHT values (44,'Ban','Mum',2,3,1,4) 465 | 466 | 467 | update tblAirport set AIRPORT_NAME='Mum', CITY='Mumbai',STATE='Maharashtra' where STATE='Karnataka' 468 | 469 | Select AIRLINE_ID, AIRLINE_NAME, AP_NAME 470 | 471 | from tblAirline 472 | 473 | join FLIGHT 474 | 475 | on tblAirline.AIRLINE_ID = FLIGHT.A_ID 476 | 477 | 478 | Create view vWAirportByAirline 479 | 480 | as 481 | 482 | Select AIRLINE_ID, AIRLINE_NAME, AP_NAME 483 | 484 | from tblAirline 485 | 486 | join FLIGHT 487 | 488 | on tblAirline.AIRLINE_ID = FLIGHT.A_ID 489 | 490 | 491 | Create or replace View vWAirportByAirline 492 | 493 | as 494 | 495 | Select AIRPORT_NAME, CITY, STATE 496 | 497 | from tblAirport 498 | 499 | join tblAirline 500 | 501 | on tblAirport.AIRPORT_NAME = tblAirline.AP_NAME 502 | 503 | 504 | SELECT * from vWAirportByAirline 505 | 506 | select * from tblAirport 507 | 508 | select * from tblAirline 509 | 510 | select * from FLIGHT 511 | 512 | 513 | 514 | alter table tblAirport drop primary key; 515 | 516 | 517 | 518 | ALTER table tblAirport 519 | 520 | ADD CONSTRAINT air 521 | 522 | primary key (AIRPORT_NAME) ; 523 | 524 | 525 | 526 | ALTER VIEW vWAirportByAirline 527 | 528 | ADD CONSTRAINT emp_view_unq 529 | 530 | UNIQUE (Airline_ID) DISABLE NOVALIDATE 531 | 532 | 533 | ALTER VIEW vWAirportByAirline 534 | 535 | ADD CONSTRAINT emp_view_unq1 536 | 537 | UNIQUE (name) DISABLE NOVALIDATE 538 | 539 | 540 | ALTER VIEW vWAirportByAirline 541 | 542 | ADD CONSTRAINT emp_view_unq2 543 | 544 | primary key (id) DISABLE NOVALIDATE 545 | 546 | 547 | insert into vWAirportByAirline values (6,'Spicejet','Che') 548 | 549 | insert into vWAirportByAirline (CITY, STATE) values ('Chennai','TamilNadu') 550 | 551 | insert into vWAirportByAirline (STATE) values ('Madras') 552 | 553 | 554 | 555 | select * from vWAirportByAirline 556 | 557 | select * from tblAirport 558 | 559 | alter view vWAirportByAirline 560 | 561 | 562 | Create View vWithAirline_Airport 563 | 564 | as 565 | 566 | Select AIRPORT_NAME, CITY, STATE 567 | 568 | from tblAirport 569 | 570 | join tblAirline 571 | 572 | on tblAirport.AIRPORT_NAME = tblAirline.AP_NAME 573 | 574 | where tblAirline.AIRLINE_NAME = 'Spicejet' 575 | 576 | select * from vWithAirline_Airport 577 | 578 | 579 | Create View vWAirportNonConfidentialData 580 | 581 | as 582 | 583 | Select AIRPORT_NAME, CITY, STATE 584 | 585 | from tblAirport 586 | 587 | join tblAirline 588 | 589 | on tblAirport.AIRPORT_NAME = tblAirline.AP_NAME 590 | 591 | select * from vWAirportNonConfidentialData 592 | 593 | 594 | Create View vWAirportCountByAirline 595 | 596 | as 597 | 598 | Select AIRLINE_NAME, COUNT(A_ID) as TotalCount 599 | 600 | from tblAirline 601 | 602 | join FLIGHT 603 | 604 | on tblAirline.AIRLINE_ID = FLIGHT.A_ID 605 | 606 | select * from vWAirportCountByAirline 607 | 608 | 609 | 610 | SELECT column_name, updatable 611 | 612 | FROM user_updatable_columns 613 | 614 | WHERE table_name = 'vWAirportCountByAirline' 615 | 616 | 617 | //TRIGGERS OUTPUT 618 | 619 | 620 | CREATE TABLE AIRPORT( 621 | AIRPORT_NAME VARCHAR(20) NOT NULL, 622 | CITY VARCHAR(20), 623 | STATE VARCHAR(20), 624 | PRIMARY KEY (AIRPORT_NAME) 625 | ); 626 | 627 | INSERT INTO AIRPORT VALUES('mumbai', 'mumbai', 'maharashtra'); 628 | INSERT INTO AIRPORT VALUES('delhi', 'delhi', 'delhi'); 629 | INSERT INTO AIRPORT VALUES('pune', 'pune', 'maharashtra'); 630 | 631 | SELECT * FROM AIRPORT; 632 | 633 | CREATE OR REPLACE TRIGGER AFTER_INSERT_TR 634 | AFTER INSERT ON AIRPORT 635 | FOR EACH ROW 636 | BEGIN 637 | dbms_output.put_line('insert successfully'); 638 | END; 639 | 640 | INSERT INTO AIRPORT VALUES('A', 'A', 'A'); 641 | 642 | DROP TRIGGER AFTER_INSERT_TR; 643 | 644 | CREATE OR REPLACE TRIGGER BEFORE_INSERT_TR 645 | BEFORE INSERT ON AIRPORT 646 | FOR EACH ROW 647 | BEGIN 648 | :new.AIRPORT_NAME := TRIM(:new.AIRPORT_NAME); 649 | :new.CITY := TRIM(:new.CITY); 650 | :new.STATE := TRIM(:new.STATE); 651 | END; 652 | 653 | INSERT INTO AIRPORT VALUES('B ','B ','B '); 654 | 655 | SELECT * FROM AIRPORT; 656 | 657 | DROP TRIGGER BEFORE_INSERT_TR; 658 | 659 | -------------------------------------------------------------------------------- /Microprocessor (MP)/1902112_Tushar_MP.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tusharnankani/sem4-assignments/3ae356e346583a736e5863a73c34de2a706ea45f/Microprocessor (MP)/1902112_Tushar_MP.pdf -------------------------------------------------------------------------------- /Microprocessor (MP)/MP Practicals/1902112_C23_01.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tusharnankani/sem4-assignments/3ae356e346583a736e5863a73c34de2a706ea45f/Microprocessor (MP)/MP Practicals/1902112_C23_01.docx -------------------------------------------------------------------------------- /Microprocessor (MP)/MP Practicals/1902112_C23_02.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tusharnankani/sem4-assignments/3ae356e346583a736e5863a73c34de2a706ea45f/Microprocessor (MP)/MP Practicals/1902112_C23_02.docx -------------------------------------------------------------------------------- /Microprocessor (MP)/MP Practicals/1902112_C23_03.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tusharnankani/sem4-assignments/3ae356e346583a736e5863a73c34de2a706ea45f/Microprocessor (MP)/MP Practicals/1902112_C23_03.docx -------------------------------------------------------------------------------- /Microprocessor (MP)/MP Practicals/1902112_C23_04.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tusharnankani/sem4-assignments/3ae356e346583a736e5863a73c34de2a706ea45f/Microprocessor (MP)/MP Practicals/1902112_C23_04.docx -------------------------------------------------------------------------------- /Microprocessor (MP)/MP Practicals/1902112_C23_05.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tusharnankani/sem4-assignments/3ae356e346583a736e5863a73c34de2a706ea45f/Microprocessor (MP)/MP Practicals/1902112_C23_05.docx -------------------------------------------------------------------------------- /Microprocessor (MP)/MP Practicals/1902112_C23_06.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tusharnankani/sem4-assignments/3ae356e346583a736e5863a73c34de2a706ea45f/Microprocessor (MP)/MP Practicals/1902112_C23_06.docx -------------------------------------------------------------------------------- /Microprocessor (MP)/MP Practicals/1902112_C23_07.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tusharnankani/sem4-assignments/3ae356e346583a736e5863a73c34de2a706ea45f/Microprocessor (MP)/MP Practicals/1902112_C23_07.docx -------------------------------------------------------------------------------- /Microprocessor (MP)/MP Practicals/1902112_C23_08.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tusharnankani/sem4-assignments/3ae356e346583a736e5863a73c34de2a706ea45f/Microprocessor (MP)/MP Practicals/1902112_C23_08.docx -------------------------------------------------------------------------------- /Microprocessor (MP)/MP Practicals/1902112_C23_09.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tusharnankani/sem4-assignments/3ae356e346583a736e5863a73c34de2a706ea45f/Microprocessor (MP)/MP Practicals/1902112_C23_09.docx -------------------------------------------------------------------------------- /Microprocessor (MP)/MP Practicals/1902112_C23_10.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tusharnankani/sem4-assignments/3ae356e346583a736e5863a73c34de2a706ea45f/Microprocessor (MP)/MP Practicals/1902112_C23_10.docx -------------------------------------------------------------------------------- /Operating System (OS)/BankersAlgorithm/BankersAlgorithms.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | class Bankers { 5 | int allocation[][] = {{0, 1, 0}, 6 | {2, 0, 0}, 7 | {3, 0, 2}, 8 | {2, 1, 1}, 9 | {0, 0, 2}}; 10 | int max[][] = {{7, 5, 3}, 11 | {3, 2, 2}, 12 | {9, 0, 2}, 13 | {2, 2, 2}, 14 | {40, 30, 30}}; 15 | int available[] = {3, 3, 2}, totalInstances[] = {10, 5, 7}; 16 | int numberOfResources = 3, numberOfProcesses = 5; 17 | // request is the need matrix: need = max - allocated; 18 | int request[][] = new int[numberOfProcesses][numberOfResources]; 19 | boolean done[] = new boolean[numberOfProcesses]; 20 | int cnt = 0; 21 | Scanner s = new Scanner(System.in); 22 | 23 | void processInput() { 24 | System.out.println("\n\t\t Welcome to Banker's Algorithm \n"); 25 | 26 | System.out.print("Do you want to input the values? [0/1]: "); 27 | if(s.nextInt() == 1) { 28 | 29 | System.out.print("\nEnter the number of processes: "); 30 | numberOfProcesses = s.nextInt(); 31 | System.out.print("\nEnter the number of resources: "); 32 | numberOfResources = s.nextInt(); 33 | 34 | int totalInstances[] = new int[numberOfResources]; 35 | System.out.println("\nEnter total number of instances per resource:"); 36 | for(int i = 0; i < numberOfResources; ++i) { 37 | System.out.print("Enter total number of instances of resource " + (i + 1) + ": "); 38 | totalInstances[i] = s.nextInt(); 39 | } 40 | System.out.println(""); 41 | int allocation[][] = new int[numberOfProcesses][numberOfResources]; 42 | for(int i = 0; i < numberOfProcesses; i++) { 43 | System.out.print("Enter allocated instances for Process " + (i + 1) + ": "); 44 | for(int j = 0; j < numberOfResources; j++) { 45 | allocation[i][j] = s.nextInt(); 46 | } 47 | } 48 | System.out.println(""); 49 | int max[][] = new int[numberOfProcesses][numberOfResources]; 50 | for(int i = 0; i < numberOfProcesses; i++) { 51 | System.out.print("Enter maximum instances for Process " + (i + 1) + ": "); 52 | for(int j = 0; j < numberOfResources; j++) { 53 | max[i][j] = s.nextInt(); 54 | } 55 | } 56 | // request is the need matrix: need = max - allocated; 57 | int request[][] = new int[numberOfProcesses][numberOfResources]; 58 | int available[] = new int[numberOfResources]; 59 | System.out.println("\nEnter available instances per resource:"); 60 | for(int i = 0; i < numberOfResources; ++i) { 61 | System.out.print("\nEnter number of instances AVAILABLE of resource " + (i + 1) + ": "); 62 | available[i] = s.nextInt(); 63 | } 64 | } 65 | iteratingProcesses(); 66 | } 67 | 68 | void printMatrix(int[][] arr) { 69 | for(int i = 0; i < arr.length; i++) { 70 | for(int j = 0; i < arr[0].length; j++) { 71 | System.out.print( arr[i][j] + " "); 72 | } 73 | System.out.println(""); 74 | } 75 | } 76 | 77 | void computeRequests() { 78 | System.out.println("\nThe Max Matrix is: "); 79 | for(int i = 0; i < allocation.length; ++i) { 80 | for(int j = 0; j < allocation[i].length; ++j) { 81 | System.out.print( max[i][j] + " "); 82 | } 83 | System.out.println(""); 84 | } 85 | 86 | System.out.println("\nThe Allocation Matrix is: "); 87 | for(int i = 0; i < allocation.length; ++i) { 88 | for(int j = 0; j < allocation[i].length; ++j) { 89 | System.out.print( allocation[i][j] + " "); 90 | } 91 | System.out.println(""); 92 | } 93 | 94 | System.out.println("\nThe calculated need matrix is: "); 95 | for(int i = 0; i < allocation.length; ++i) { 96 | for(int j = 0; j < allocation[i].length; ++j) { 97 | request[i][j] = max[i][j] - allocation[i][j]; 98 | System.out.print( request[i][j] + " "); 99 | } 100 | System.out.println(""); 101 | } 102 | } 103 | 104 | void iteratingProcesses() { 105 | computeRequests(); 106 | int prev = -1; 107 | while(prev != cnt && cnt != numberOfProcesses) { 108 | prev = cnt; 109 | for(int i = 0; i < request.length; ++i) { 110 | if(!done[i]) { 111 | boolean ok = true; 112 | for(int j = 0; j < request[0].length; ++j) { 113 | if(request[i][j] > available[j]) { 114 | ok = false; 115 | break; 116 | } 117 | } 118 | 119 | if(ok) { 120 | System.out.println("\n\nProcess "+ (i + 1) +" can be allocated the resources..."); 121 | System.out.println("Process Terminated. Releasing resources..."); 122 | System.out.print("Process " + (i + 1) + ": "); 123 | for(int j = 0; j < available.length; ++j) { 124 | System.out.print(available[j] + " "); 125 | } 126 | System.out.print(" + "); 127 | for(int j = 0; j < allocation[0].length; ++j) { 128 | System.out.print(allocation[i][j] + " "); 129 | } 130 | 131 | System.out.print(" = "); 132 | for(int j = 0; j < request[0].length; ++j) { 133 | available[j] += allocation[i][j]; 134 | System.out.print(available[j] + " "); 135 | } 136 | System.out.println(""); 137 | 138 | done[i] = true; 139 | cnt += 1; 140 | } 141 | } 142 | } 143 | if(prev == cnt) { 144 | System.out.println("\nNone of the remaining processes can be allocated the required resources. \nTerminating iteration..."); 145 | } 146 | } 147 | 148 | if(cnt == numberOfProcesses) { 149 | System.out.println("All processes terminated. \nSafe"); 150 | } else { 151 | System.out.println("\nUnSafe"); 152 | } 153 | } 154 | 155 | } 156 | 157 | class BankersAlgorithm { 158 | public static void main(String args[]) throws IOException 159 | { 160 | Bankers b = new Bankers(); 161 | b.processInput(); 162 | } 163 | } -------------------------------------------------------------------------------- /Operating System (OS)/DiskSchedulingPolicies/DiskSchedulingPolicy.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | class DSP_Algorithms { 5 | // hardcoded values if the user does not want to enter the values; 6 | int[] requestQueue = new int[] { 90, 120, 30, 40, 115, 130, 110, 80, 190, 25 }; 7 | int globalCurrentHead = 86; 8 | int queueLength = requestQueue.length; 9 | int[] orderOfProcessing = new int[queueLength]; 10 | int totalHeadMovement = 0; 11 | Scanner s = new Scanner(System.in); 12 | 13 | 14 | void processInput() { 15 | System.out.println("\n\t\t Welcome to Disk Scheduling Policies \n"); 16 | 17 | System.out.print("Do you want to input the values? [0/1]: "); 18 | if(s.nextInt() == 1) { 19 | System.out.print("\nEnter the length of the request queue: "); 20 | queueLength = s.nextInt(); 21 | 22 | int[] requestQueue = new int[queueLength]; 23 | System.out.println("\nEnter the request queue: "); 24 | for(int i = 0; i < queueLength; ++i) { 25 | System.out.println("\nEnter Element " + (i + 1) + ": "); 26 | requestQueue[i] = s.nextInt(); 27 | } 28 | 29 | System.out.println("\nEnter the current head location: "); 30 | globalCurrentHead = s.nextInt(); 31 | } 32 | 33 | while(true) { 34 | System.out.println("\n\nEnter the policy you want to execute? "); 35 | System.out.println("[1] FCFS (First Come First Serve)"); 36 | System.out.println("[2] SSTF (Shortest Seek Time First)"); 37 | System.out.println("[3] SCAN "); 38 | System.out.println("[4] C-SCAN "); 39 | System.out.println("[5] LOOK "); 40 | System.out.println("[6] C-LOOK "); 41 | System.out.println("[7] Exit "); 42 | System.out.print("Enter your choice? [1-7]: "); 43 | switch(s.nextInt()) { 44 | case 1: { 45 | FCFS(); 46 | break; 47 | } 48 | case 2: { 49 | SSTF(); 50 | break; 51 | } 52 | case 3: { 53 | SCAN(); 54 | break; 55 | } 56 | case 4: { 57 | CSCAN(); 58 | break; 59 | } 60 | case 5: { 61 | LOOK(); 62 | break; 63 | } 64 | case 6: { 65 | CLOOK(); 66 | break; 67 | } 68 | case 7: { 69 | return; 70 | } 71 | default: 72 | System.out.println("Wrong Choice, Please enter a number between 1 and 5. "); 73 | } 74 | } 75 | } 76 | 77 | void printAverageSeekTime(int totalHeadMovement, int totalLength) { 78 | System.out.println("\n\n\tAverage Seek Time: " + (totalHeadMovement) + " / " + (totalLength) + " = " + ((double)totalHeadMovement / (double)totalLength)); 79 | } 80 | 81 | void FCFS() { 82 | int[] orderOfProcessing = new int[requestQueue.length]; 83 | int totalHeadMovement = 0; 84 | int currentHead = globalCurrentHead; 85 | 86 | System.out.println(); 87 | System.out.println("\t\t+--------------------------------------+"); 88 | System.out.println("\t\t|Output for FCFS Disk Scheduling Policy|"); 89 | System.out.println("\t\t+--------------------------------------+"); 90 | System.out.println("\n\tHead currently at: " + currentHead); 91 | 92 | System.out.println("\n Iteration \t Current Head \t Disk Movement \t Total Disk Movement"); 93 | System.out.println("------------------------------------------------------------------------"); 94 | 95 | for(int i = 0; i < requestQueue.length; ++i) { 96 | int currentDiskMovement = Math.abs(currentHead - requestQueue[i]); 97 | totalHeadMovement += currentDiskMovement; 98 | orderOfProcessing[i] = requestQueue[i]; 99 | currentHead = requestQueue[i]; 100 | 101 | System.out.println( "\t" + (i + 1) +"\t\t" + currentHead + "\t\t" + currentDiskMovement + "\t\t" + totalHeadMovement); 102 | } 103 | System.out.println("------------------------------------------------------------------------"); 104 | 105 | System.out.println("\n\tTotal Head Movement: " + totalHeadMovement); 106 | System.out.print("\n\tOrder of Processing: " + (orderOfProcessing[0])); 107 | for(int i = 1; i < orderOfProcessing.length; ++i) { 108 | System.out.print( " -> " + orderOfProcessing[i]); 109 | } 110 | printAverageSeekTime(totalHeadMovement, requestQueue.length); 111 | System.out.println(); 112 | } 113 | 114 | void SSTF() { 115 | int[] orderOfProcessing = new int[requestQueue.length]; 116 | int totalHeadMovement = 0; 117 | int currentHead = globalCurrentHead; 118 | 119 | System.out.println(); 120 | System.out.println("\t\t+--------------------------------------+"); 121 | System.out.println("\t\t|Output for SSTF Disk Scheduling Policy|"); 122 | System.out.println("\t\t+--------------------------------------+"); 123 | System.out.println("\n\tHead currently at: " + currentHead); 124 | 125 | System.out.println("\n Iteration \t Current Head \t Disk Movement \t Total Disk Movement"); 126 | System.out.println("------------------------------------------------------------------------"); 127 | 128 | boolean[] traversed = new boolean[requestQueue.length]; 129 | for(int i = 0; i < requestQueue.length; ++i) { 130 | 131 | int minimumDifference = 1000000, index = -1; 132 | 133 | for(int j = 0; j < requestQueue.length; ++j) { 134 | 135 | if(currentHead != requestQueue[j] && !traversed[j]) { 136 | int currentDifference = Math.abs(currentHead - requestQueue[j]); 137 | 138 | if(currentDifference < minimumDifference) { 139 | minimumDifference = currentDifference; 140 | index = j; 141 | } 142 | } 143 | } 144 | 145 | totalHeadMovement += minimumDifference; 146 | orderOfProcessing[i] = requestQueue[index]; 147 | currentHead = requestQueue[index]; 148 | traversed[index] = true; 149 | 150 | System.out.println( "\t" + (i + 1) +"\t\t" + currentHead + "\t\t" + minimumDifference + "\t\t" + totalHeadMovement); 151 | } 152 | System.out.println("------------------------------------------------------------------------"); 153 | 154 | System.out.println("\n\tTotal Head Movement: " + totalHeadMovement); 155 | System.out.print("\n\tOrder of Processing: " + (orderOfProcessing[0])); 156 | for(int i = 1; i < orderOfProcessing.length; ++i) { 157 | System.out.print( " -> " + orderOfProcessing[i]); 158 | } 159 | printAverageSeekTime(totalHeadMovement, requestQueue.length); 160 | System.out.println(); 161 | } 162 | 163 | void SCAN() { 164 | // "requestQueue.length + 1" since, one extra end will be added to the queue; 165 | int[] orderOfProcessing = new int[requestQueue.length + 1]; 166 | int totalHeadMovement = 0; 167 | int currentHead = globalCurrentHead; 168 | 169 | ArrayList firstHalf = new ArrayList(); 170 | ArrayList secondHalf = new ArrayList(); 171 | 172 | for(int i = 0; i < requestQueue.length; ++i) { 173 | if(currentHead > requestQueue[i]) 174 | firstHalf.add(requestQueue[i]); 175 | else 176 | secondHalf.add(requestQueue[i]); 177 | } 178 | Collections.sort(firstHalf); 179 | Collections.sort(secondHalf); 180 | System.out.print(firstHalf); 181 | System.out.println(secondHalf); 182 | 183 | System.out.print("\nTraverse to the inner track or the outer track? \n [0] Inner Track\n [1] Outer Track \n Your Choice? "); 184 | int outer = s.nextInt(); 185 | 186 | System.out.println(); 187 | System.out.println("\t\t+--------------------------------------+"); 188 | System.out.println("\t\t|Output for SCAN Disk Scheduling Policy|"); 189 | System.out.println("\t\t+--------------------------------------+"); 190 | System.out.println("\n\tHead currently at: " + currentHead); 191 | 192 | System.out.println("\n Iteration \t Current Head \t Disk Movement \t Total Disk Movement"); 193 | System.out.println("------------------------------------------------------------------------"); 194 | 195 | int j = 0; 196 | // inner track first 197 | if(outer == 0) { 198 | for(int i = firstHalf.size() - 1; i >= 0; --i) { 199 | 200 | int currentDiskMovement = Math.abs(currentHead - firstHalf.get(i)); 201 | totalHeadMovement += currentDiskMovement; 202 | orderOfProcessing[j] = firstHalf.get(i); 203 | currentHead = firstHalf.get(i); 204 | 205 | System.out.println( "\t" + (++j) +"\t\t" + currentHead + "\t\t" + currentDiskMovement + "\t\t" + totalHeadMovement); 206 | } 207 | 208 | // going to 0; 209 | totalHeadMovement += (currentHead - 0); 210 | orderOfProcessing[j] = 0; 211 | System.out.println( "\t" + (++j) +"\t\t" + 0 + "\t\t" + currentHead + "\t\t" + totalHeadMovement); 212 | currentHead = 0; 213 | 214 | for(int i = 0; i < secondHalf.size(); i++) { 215 | int currentDiskMovement = Math.abs(currentHead - secondHalf.get(i)); 216 | totalHeadMovement += currentDiskMovement; 217 | orderOfProcessing[j] = secondHalf.get(i); 218 | currentHead = secondHalf.get(i); 219 | 220 | System.out.println( "\t" + (++j) +"\t\t" + currentHead + "\t\t" + currentDiskMovement + "\t\t" + totalHeadMovement); 221 | } 222 | } 223 | else { 224 | for(int i = 0; i < secondHalf.size(); i++) { 225 | int currentDiskMovement = Math.abs(currentHead - secondHalf.get(i)); 226 | totalHeadMovement += currentDiskMovement; 227 | orderOfProcessing[j] = secondHalf.get(i); 228 | currentHead = secondHalf.get(i); 229 | 230 | System.out.println( "\t" + (++j) +"\t\t" + currentHead + "\t\t" + currentDiskMovement + "\t\t" + totalHeadMovement); 231 | } 232 | 233 | // going to 199; 234 | totalHeadMovement += Math.abs(currentHead - 199); 235 | orderOfProcessing[j] = 199; 236 | System.out.println( "\t" + (++j) +"\t\t" + 199 + "\t\t" + Math.abs(currentHead - 199) + "\t\t" + totalHeadMovement); 237 | currentHead = 199; 238 | 239 | for(int i = firstHalf.size() - 1; i >= 0; --i) { 240 | int currentDiskMovement = Math.abs(currentHead - firstHalf.get(i)); 241 | totalHeadMovement += currentDiskMovement; 242 | orderOfProcessing[j] = firstHalf.get(i); 243 | currentHead = firstHalf.get(i); 244 | 245 | System.out.println( "\t" + (++j) +"\t\t" + currentHead + "\t\t" + currentDiskMovement + "\t\t" + totalHeadMovement); 246 | } 247 | } 248 | System.out.println("------------------------------------------------------------------------"); 249 | 250 | System.out.println("\n\tTotal Head Movement: " + totalHeadMovement); 251 | System.out.print("\n\tOrder of Processing: " + (orderOfProcessing[0])); 252 | for(int i = 1; i < orderOfProcessing.length; ++i) { 253 | System.out.print( " -> " + orderOfProcessing[i]); 254 | } 255 | printAverageSeekTime(totalHeadMovement, requestQueue.length); 256 | System.out.println(); 257 | } 258 | 259 | void CSCAN() { 260 | // "requestQueue.length + 2" since, both the extra ends will be added to the queue; 261 | int[] orderOfProcessing = new int[requestQueue.length + 2]; 262 | int totalHeadMovement = 0; 263 | int currentHead = globalCurrentHead; 264 | 265 | ArrayList firstHalf = new ArrayList(); 266 | ArrayList secondHalf = new ArrayList(); 267 | 268 | for(int i = 0; i < requestQueue.length; ++i) { 269 | if(currentHead > requestQueue[i]) 270 | firstHalf.add(requestQueue[i]); 271 | else 272 | secondHalf.add(requestQueue[i]); 273 | } 274 | Collections.sort(firstHalf); 275 | Collections.sort(secondHalf); 276 | System.out.print(firstHalf); 277 | System.out.println(secondHalf); 278 | 279 | System.out.print("\nTraverse to the inner track or the outer track? \n [0] Inner Track\n [1] Outer Track \n Your Choice? "); 280 | int outer = s.nextInt(); 281 | 282 | System.out.println(); 283 | System.out.println("\t\t+----------------------------------------+"); 284 | System.out.println("\t\t|Output for C-SCAN Disk Scheduling Policy|"); 285 | System.out.println("\t\t+----------------------------------------+"); 286 | System.out.println("\n\tHead currently at: " + currentHead); 287 | 288 | System.out.println("\n Iteration \t Current Head \t Disk Movement \t Total Disk Movement"); 289 | System.out.println("------------------------------------------------------------------------"); 290 | 291 | int j = 0; 292 | // Inner Track First 293 | if(outer == 0) { 294 | for(int i = firstHalf.size() - 1; i >= 0; --i) { 295 | 296 | int currentDiskMovement = Math.abs(currentHead - firstHalf.get(i)); 297 | totalHeadMovement += currentDiskMovement; 298 | orderOfProcessing[j] = firstHalf.get(i); 299 | currentHead = firstHalf.get(i); 300 | 301 | System.out.println( "\t" + (++j) +"\t\t" + currentHead + "\t\t" + currentDiskMovement + "\t\t" + totalHeadMovement); 302 | } 303 | 304 | // going to 0; 305 | totalHeadMovement += (currentHead - 0); 306 | orderOfProcessing[j] = 0; 307 | System.out.println( "\t" + (++j) +"\t\t" + 0 + "\t\t" + (currentHead - 0) + "\t\t" + totalHeadMovement); 308 | currentHead = 0; 309 | 310 | // going to 199; 311 | totalHeadMovement += Math.abs(currentHead - 199); 312 | orderOfProcessing[j] = 199; 313 | System.out.println( "\t" + (++j) +"\t\t" + 199 + "\t\t" + 199 + "\t\t" + totalHeadMovement); 314 | currentHead = 199; 315 | 316 | for(int i = secondHalf.size() - 1; i >= 0; --i) { 317 | int currentDiskMovement = Math.abs(currentHead - secondHalf.get(i)); 318 | totalHeadMovement += currentDiskMovement; 319 | orderOfProcessing[j] = secondHalf.get(i); 320 | currentHead = secondHalf.get(i); 321 | 322 | System.out.println( "\t" + (++j) +"\t\t" + currentHead + "\t\t" + currentDiskMovement + "\t\t" + totalHeadMovement); 323 | } 324 | } 325 | 326 | // Outer Track First; 327 | else { 328 | for(int i = 0; i < secondHalf.size(); i++) { 329 | int currentDiskMovement = Math.abs(currentHead - secondHalf.get(i)); 330 | totalHeadMovement += currentDiskMovement; 331 | orderOfProcessing[j] = secondHalf.get(i); 332 | currentHead = secondHalf.get(i); 333 | 334 | System.out.println( "\t" + (++j) +"\t\t" + currentHead + "\t\t" + currentDiskMovement + "\t\t" + totalHeadMovement); 335 | } 336 | 337 | // going to 199; 338 | totalHeadMovement += Math.abs(currentHead - 199); 339 | orderOfProcessing[j] = 199; 340 | System.out.println( "\t" + (++j) +"\t\t" + 199 + "\t\t" + Math.abs(currentHead - 199) + "\t\t" + totalHeadMovement); 341 | currentHead = 199; 342 | 343 | // going to 0; 344 | totalHeadMovement += Math.abs(currentHead - 0); 345 | orderOfProcessing[j] = 0; 346 | System.out.println( "\t" + (++j) +"\t\t" + 0 + "\t\t" + 199 + "\t\t" + totalHeadMovement); 347 | currentHead = 0; 348 | 349 | for(int i = 0; i < firstHalf.size(); i++) { 350 | int currentDiskMovement = Math.abs(currentHead - firstHalf.get(i)); 351 | totalHeadMovement += currentDiskMovement; 352 | orderOfProcessing[j] = firstHalf.get(i); 353 | currentHead = firstHalf.get(i); 354 | 355 | System.out.println( "\t" + (++j) +"\t\t" + currentHead + "\t\t" + currentDiskMovement + "\t\t" + totalHeadMovement); 356 | } 357 | } 358 | System.out.println("------------------------------------------------------------------------"); 359 | 360 | System.out.println("\n\tTotal Head Movement: " + totalHeadMovement); 361 | System.out.print("\n\tOrder of Processing: " + (orderOfProcessing[0])); 362 | for(int i = 1; i < orderOfProcessing.length; ++i) { 363 | System.out.print( " -> " + orderOfProcessing[i]); 364 | } 365 | printAverageSeekTime(totalHeadMovement, requestQueue.length); 366 | System.out.println(); 367 | } 368 | 369 | void LOOK() { 370 | // "requestQueue.length" since, no extra ends will be added to the queue; 371 | int[] orderOfProcessing = new int[requestQueue.length]; 372 | int totalHeadMovement = 0; 373 | int currentHead = globalCurrentHead; 374 | 375 | ArrayList firstHalf = new ArrayList(); 376 | ArrayList secondHalf = new ArrayList(); 377 | 378 | for(int i = 0; i < requestQueue.length; ++i) { 379 | if(currentHead > requestQueue[i]) 380 | firstHalf.add(requestQueue[i]); 381 | else 382 | secondHalf.add(requestQueue[i]); 383 | } 384 | Collections.sort(firstHalf); 385 | Collections.sort(secondHalf); 386 | System.out.print(firstHalf); 387 | System.out.println(secondHalf); 388 | 389 | System.out.print("\nTraverse to the inner track or the outer track? \n [0] Inner Track\n [1] Outer Track \n Your Choice? "); 390 | int outer = s.nextInt(); 391 | 392 | System.out.println(); 393 | System.out.println("\t\t+--------------------------------------+"); 394 | System.out.println("\t\t|Output for LOOK Disk Scheduling Policy|"); 395 | System.out.println("\t\t+--------------------------------------+"); 396 | System.out.println("\n\tHead currently at: " + currentHead); 397 | 398 | System.out.println("\n Iteration \t Current Head \t Disk Movement \t Total Disk Movement"); 399 | System.out.println("------------------------------------------------------------------------"); 400 | 401 | int j = 0; 402 | // inner track first 403 | if(outer == 0) { 404 | for(int i = firstHalf.size() - 1; i >= 0; --i) { 405 | 406 | int currentDiskMovement = Math.abs(currentHead - firstHalf.get(i)); 407 | totalHeadMovement += currentDiskMovement; 408 | orderOfProcessing[j] = firstHalf.get(i); 409 | currentHead = firstHalf.get(i); 410 | 411 | System.out.println( "\t" + (++j) +"\t\t" + currentHead + "\t\t" + currentDiskMovement + "\t\t" + totalHeadMovement); 412 | } 413 | 414 | for(int i = 0; i < secondHalf.size(); i++) { 415 | int currentDiskMovement = Math.abs(currentHead - secondHalf.get(i)); 416 | totalHeadMovement += currentDiskMovement; 417 | orderOfProcessing[j] = secondHalf.get(i); 418 | currentHead = secondHalf.get(i); 419 | 420 | System.out.println( "\t" + (++j) +"\t\t" + currentHead + "\t\t" + currentDiskMovement + "\t\t" + totalHeadMovement); 421 | } 422 | } 423 | else { 424 | for(int i = 0; i < secondHalf.size(); i++) { 425 | int currentDiskMovement = Math.abs(currentHead - secondHalf.get(i)); 426 | totalHeadMovement += currentDiskMovement; 427 | orderOfProcessing[j] = secondHalf.get(i); 428 | currentHead = secondHalf.get(i); 429 | 430 | System.out.println( "\t" + (++j) +"\t\t" + currentHead + "\t\t" + currentDiskMovement + "\t\t" + totalHeadMovement); 431 | } 432 | 433 | for(int i = firstHalf.size() - 1; i >= 0; --i) { 434 | int currentDiskMovement = Math.abs(currentHead - firstHalf.get(i)); 435 | totalHeadMovement += currentDiskMovement; 436 | orderOfProcessing[j] = firstHalf.get(i); 437 | currentHead = firstHalf.get(i); 438 | 439 | System.out.println( "\t" + (++j) +"\t\t" + currentHead + "\t\t" + currentDiskMovement + "\t\t" + totalHeadMovement); 440 | } 441 | } 442 | System.out.println("------------------------------------------------------------------------"); 443 | 444 | System.out.println("\n\tTotal Head Movement: " + totalHeadMovement); 445 | System.out.print("\n\tOrder of Processing: " + (orderOfProcessing[0])); 446 | for(int i = 1; i < orderOfProcessing.length; ++i) { 447 | System.out.print( " -> " + orderOfProcessing[i]); 448 | } 449 | printAverageSeekTime(totalHeadMovement, requestQueue.length); 450 | System.out.println(); 451 | } 452 | 453 | void CLOOK() { 454 | // "requestQueue.length" since, no extra ends will be added to the queue; 455 | int[] orderOfProcessing = new int[requestQueue.length]; 456 | int totalHeadMovement = 0; 457 | int currentHead = globalCurrentHead; 458 | 459 | ArrayList firstHalf = new ArrayList(); 460 | ArrayList secondHalf = new ArrayList(); 461 | 462 | for(int i = 0; i < requestQueue.length; ++i) { 463 | if(currentHead > requestQueue[i]) 464 | firstHalf.add(requestQueue[i]); 465 | else 466 | secondHalf.add(requestQueue[i]); 467 | } 468 | Collections.sort(firstHalf); 469 | Collections.sort(secondHalf); 470 | System.out.print(firstHalf); 471 | System.out.println(secondHalf); 472 | 473 | System.out.print("\nTraverse to the inner track or the outer track? \n [0] Inner Track\n [1] Outer Track \n Your Choice? "); 474 | int outer = s.nextInt(); 475 | 476 | System.out.println(); 477 | System.out.println("\t\t+----------------------------------------+"); 478 | System.out.println("\t\t|Output for C-LOOK Disk Scheduling Policy|"); 479 | System.out.println("\t\t+----------------------------------------+"); 480 | System.out.println("\n\tHead currently at: " + currentHead); 481 | 482 | System.out.println("\n Iteration \t Current Head \t Disk Movement \t Total Disk Movement"); 483 | System.out.println("------------------------------------------------------------------------"); 484 | 485 | int j = 0; 486 | // inner track first 487 | if(outer == 0) { 488 | for(int i = firstHalf.size() - 1; i >= 0; --i) { 489 | 490 | int currentDiskMovement = Math.abs(currentHead - firstHalf.get(i)); 491 | totalHeadMovement += currentDiskMovement; 492 | orderOfProcessing[j] = firstHalf.get(i); 493 | currentHead = firstHalf.get(i); 494 | 495 | System.out.println( "\t" + (++j) +"\t\t" + currentHead + "\t\t" + currentDiskMovement + "\t\t" + totalHeadMovement); 496 | } 497 | 498 | 499 | for(int i = secondHalf.size() - 1; i >= 0; i--) { 500 | int currentDiskMovement = Math.abs(currentHead - secondHalf.get(i)); 501 | totalHeadMovement += currentDiskMovement; 502 | orderOfProcessing[j] = secondHalf.get(i); 503 | currentHead = secondHalf.get(i); 504 | 505 | System.out.println( "\t" + (++j) +"\t\t" + currentHead + "\t\t" + currentDiskMovement + "\t\t" + totalHeadMovement); 506 | } 507 | } 508 | else { 509 | for(int i = 0; i < secondHalf.size(); i++) { 510 | int currentDiskMovement = Math.abs(currentHead - secondHalf.get(i)); 511 | totalHeadMovement += currentDiskMovement; 512 | orderOfProcessing[j] = secondHalf.get(i); 513 | currentHead = secondHalf.get(i); 514 | 515 | System.out.println( "\t" + (++j) +"\t\t" + currentHead + "\t\t" + currentDiskMovement + "\t\t" + totalHeadMovement); 516 | } 517 | 518 | for(int i = 0; i < firstHalf.size(); ++i) { 519 | int currentDiskMovement = Math.abs(currentHead - firstHalf.get(i)); 520 | totalHeadMovement += currentDiskMovement; 521 | orderOfProcessing[j] = firstHalf.get(i); 522 | currentHead = firstHalf.get(i); 523 | 524 | System.out.println( "\t" + (++j) +"\t\t" + currentHead + "\t\t" + currentDiskMovement + "\t\t" + totalHeadMovement); 525 | } 526 | } 527 | System.out.println("------------------------------------------------------------------------"); 528 | 529 | System.out.println("\n\tTotal Head Movement: " + totalHeadMovement); 530 | System.out.print("\n\tOrder of Processing: " + (orderOfProcessing[0])); 531 | for(int i = 1; i < orderOfProcessing.length; ++i) { 532 | System.out.print( " -> " + orderOfProcessing[i]); 533 | } 534 | printAverageSeekTime(totalHeadMovement, requestQueue.length); 535 | System.out.println(); 536 | } 537 | 538 | } 539 | 540 | class DiskSchedulingPolicy { 541 | public static void main(String args[]) throws IOException 542 | { 543 | DSP_Algorithms dsp = new DSP_Algorithms(); 544 | dsp.processInput(); 545 | } 546 | } -------------------------------------------------------------------------------- /Operating System (OS)/MemoryAllocationInOS/MemoryAllocation.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | class MemoryBlock { 5 | int[] memory = new int[] { 100, 300, 40, 50, 150, 240, 200, 400}; 6 | boolean[] free = new boolean[] { false, true, false, true, false, true, false, true }; 7 | int[] processNumber = new int[] { 1, 2, 3, 4 }; 8 | int divs = memory.length; 9 | int processSize; 10 | Scanner s = new Scanner(System.in); 11 | 12 | void processInput() { 13 | System.out.println("\n\tCurrent Scenario of the Memory Allocation \n"); 14 | printTable(-1); 15 | System.out.print("\nEnter the size of the process that needs to be added (in KB): "); 16 | processSize = s.nextInt(); 17 | choice(); 18 | } 19 | 20 | void choice() { 21 | boolean running = true; 22 | while(running) { 23 | System.out.print("\nEnter the Algorithm for Memory Allocation: \n"); 24 | System.out.print("[1] First Fit\n"); 25 | System.out.print("[2] Best Fit\n"); 26 | System.out.print("[3] Worst Fit\n"); 27 | System.out.print("[4] Exit\n"); 28 | 29 | System.out.print("Enter a number (1-4): "); 30 | int fitType = s.nextInt(); 31 | switch(fitType) { 32 | case 1: 33 | System.out.println("\n\t\tAfter First Fit \n"); 34 | firstFit(); 35 | break; 36 | case 2: 37 | System.out.println("\n\t\tAfter Best Fit \n"); 38 | bestFit(); 39 | break; 40 | case 3: 41 | System.out.println("\n\t\tAfter Worst Fit \n"); 42 | worstFit(); 43 | break; 44 | case 4: 45 | running = false; 46 | break; 47 | default: 48 | System.out.println("\nPlease enter a number between 1 and 4.\n"); 49 | } 50 | } 51 | } 52 | 53 | void firstFit() { 54 | int ans = -1; 55 | for(int i = 0; i < divs; i++) { 56 | if(free[i] && processSize <= memory[i]) { 57 | ans = i; 58 | break; 59 | } 60 | } 61 | printTable(ans); 62 | } 63 | 64 | void bestFit() { 65 | int ans = -1, curr = 1000000; 66 | for(int i = 0; i < divs; i++) { 67 | if(free[i] && processSize <= memory[i]) { 68 | if(memory[i] - processSize < curr) { 69 | curr = memory[i] - processSize; 70 | ans = i; 71 | } 72 | } 73 | } 74 | printTable(ans); 75 | } 76 | 77 | void worstFit() { 78 | int ans = -1, curr = 0; 79 | for(int i = 0; i < divs; i++) { 80 | if(free[i] && processSize <= memory[i]) { 81 | if(memory[i] - processSize > curr) { 82 | curr = memory[i] - processSize; 83 | ans = i; 84 | } 85 | } 86 | } 87 | printTable(ans); 88 | } 89 | 90 | void printTable(int pos) { 91 | System.out.print("+----------------------------------------------------------+\n"); 92 | System.out.print("|\tNo.\tMemory \t\t Status \t Process |\n"); 93 | System.out.print("+----------------------------------------------------------+\n"); 94 | int j = 1, ok = 0; 95 | for (int i = 0; i < divs; i++) { 96 | if(i == pos) { 97 | System.out.print("|\t" + (i + 1) + " \t " + processSize + " \t\t " + " NF \t\t " + "Process " + (processNumber.length + 1) + " |"); 98 | if(memory[i] - processSize != 0) { 99 | System.out.print("\n|\t" + (i + 2) + " \t " + (memory[i] - processSize) + " \t\t " + " F \t\t\t |"); 100 | ok = 1; 101 | } 102 | } 103 | else { 104 | System.out.print("|\t" + (i + 1 + ok) + " \t " + memory[i] + " \t\t " + ((free[i]) ? "F \t\t\t |" : "NF \t\t " + "Process " + j++ + " |")); 105 | } 106 | System.out.println(' '); 107 | } 108 | System.out.print("+----------------------------------------------------------+\n"); 109 | } 110 | } 111 | 112 | class MemoryAllocation { 113 | public static void main(String args[]) throws IOException 114 | { 115 | MemoryBlock m = new MemoryBlock(); 116 | m.processInput(); 117 | } 118 | } -------------------------------------------------------------------------------- /Operating System (OS)/PDFs/01. Basic Linux Commands.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tusharnankani/sem4-assignments/3ae356e346583a736e5863a73c34de2a706ea45f/Operating System (OS)/PDFs/01. Basic Linux Commands.pdf -------------------------------------------------------------------------------- /Operating System (OS)/PDFs/02. Shell Programming.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tusharnankani/sem4-assignments/3ae356e346583a736e5863a73c34de2a706ea45f/Operating System (OS)/PDFs/02. Shell Programming.pdf -------------------------------------------------------------------------------- /Operating System (OS)/PageReplacementAlgorithms/PageReplacementFIFO.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | class FIFO { 5 | // hardcoded values if the user does not want to enter the values; 6 | int[] pageNos = new int[] { 7, 0, 2, 0, 5, 9, 4, 7, 8, 2 }; 7 | int pages = pageNos.length; 8 | int noOfFrames = 3; 9 | int[] PR = new int[] { -1, -1, -1 }; 10 | float hits = 0, miss = 0; 11 | Scanner s = new Scanner(System.in); 12 | 13 | void welcomeMessage() { 14 | processInput(); 15 | } 16 | 17 | void processInput() { 18 | // re-initialising the data if user wants to enter the data; 19 | pageNos = new int[100]; 20 | System.out.print("Enter the number of pages: "); 21 | pages = s.nextInt(); 22 | for(int i = 0; i < pages; ++i) { 23 | System.out.print("Enter page " + (i + 1) + ": "); 24 | pageNos[i] = s.nextInt(); 25 | } 26 | System.out.print("\n\nEnter Frame Size: "); 27 | noOfFrames = s.nextInt(); 28 | PR = new int[noOfFrames]; 29 | for(int i = 0; i < noOfFrames; ++i) { 30 | PR[i] = -1; 31 | } 32 | FIFOPR(); 33 | } 34 | 35 | // FIFO Page Replacement 36 | void FIFOPR() { 37 | System.out.println("\n\t\t Frame Blocks \t\t HIT / MISS\n"); 38 | int ptr = 0; 39 | for(int i = 0; i < pages; ++i) { 40 | boolean ok = false; 41 | for(int j = 0; j < noOfFrames; ++j) { 42 | // System.out.println(pageNos[i] + " ~ " + PR[j]); 43 | if(pageNos[i] == PR[j]) { 44 | ok = true; 45 | hits += 1; 46 | break; 47 | } 48 | } 49 | if(!ok) { 50 | PR[ptr] = pageNos[i]; 51 | ptr += 1; 52 | ptr %= noOfFrames; 53 | miss += 1; 54 | } 55 | printCurrent(ok); 56 | } 57 | System.out.println("\n\nTotal Number of Hits: " + hits); 58 | System.out.println("Total Number of Miss: " + miss); 59 | float ratio = (hits / (hits + miss)) * 100; 60 | System.out.println("\nHit Ratio: " + ratio + "%"); 61 | System.out.println("Miss Ratio: " + (100 - ratio) + "%"); 62 | } 63 | 64 | void printCurrent(boolean ok) { 65 | System.out.print("|\t"); 66 | for(int i = 0; i < noOfFrames; ++i) { 67 | System.out.print((PR[i] >= 0) ? PR[i] : "-"); 68 | System.out.print("\t|\t"); 69 | } 70 | System.out.println((ok) ? "Hit" : "Miss"); 71 | } 72 | } 73 | 74 | class PageReplacementFIFO { 75 | public static void main(String args[]) throws IOException 76 | { 77 | FIFO m = new FIFO(); 78 | m.welcomeMessage(); 79 | } 80 | } -------------------------------------------------------------------------------- /Operating System (OS)/PageReplacementAlgorithms/PageReplacementLRU.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | class LRU { 5 | // hardcoded values if the user does not want to enter the values; 6 | int[] pageNos = new int[] { 7, 0, 2, 0, 5, 9, 4, 7, 8, 2 }; 7 | int pages = pageNos.length; 8 | int noOfFrames = 3; 9 | int[] PR = new int[] { -1, -1, -1 }; 10 | float hits = 0, miss = 0; 11 | Scanner s = new Scanner(System.in); 12 | 13 | void welcomeMessage() { 14 | processInput(); 15 | } 16 | 17 | void processInput() { 18 | // re-initialising the data if user wants to enter the data; 19 | pageNos = new int[100]; 20 | System.out.print("Enter the number of pages: "); 21 | pages = s.nextInt(); 22 | for(int i = 0; i < pages; ++i) { 23 | System.out.print("Enter page " + (i + 1) + ": "); 24 | pageNos[i] = s.nextInt(); 25 | } 26 | System.out.print("\n\nEnter Frame Size: "); 27 | noOfFrames = s.nextInt(); 28 | PR = new int[noOfFrames]; 29 | for(int i = 0; i < noOfFrames; ++i) { 30 | PR[i] = -1; 31 | } 32 | LRUPR(); 33 | } 34 | 35 | boolean checkPR() { 36 | for(int i = 0; i < noOfFrames; ++i) { 37 | if(PR[i] == -1) { 38 | return true; 39 | } 40 | } 41 | return false; 42 | } 43 | 44 | // LRU Page Replacement 45 | void LRUPR() { 46 | System.out.println("\n\t\t Frame Blocks \t\t HIT / MISS\n"); 47 | int ptr = 0; 48 | for(int i = 0; i < pages; ++i) { 49 | boolean ok = false; 50 | int curr = pageNos[i]; 51 | // if some page entry in a frame is -1; 52 | if(checkPR()) { 53 | for(int j = 0; j < noOfFrames; j++) { 54 | if(curr == pageNos[j]) { 55 | hits += 1; 56 | ok = true; 57 | break; 58 | } 59 | } 60 | if(!ok) { 61 | miss += 1; 62 | PR[ptr] = pageNos[i]; 63 | ptr += 1; 64 | ptr %= noOfFrames; 65 | } 66 | } 67 | else { 68 | 69 | } 70 | 71 | 72 | // for(int j = 0; j < noOfFrames; ++j) { 73 | // System.out.println(pageNos[i] + " ~ " + PR[j]); 74 | // if(pageNos[i] == PR[j]) { 75 | // ok = true; 76 | // hits += 1; 77 | // break; 78 | // } 79 | // } 80 | // if(!ok) { 81 | // miss += 1; 82 | // } 83 | printCurrent(ok); 84 | } 85 | System.out.println("\n\nTotal Number of Hits: " + hits); 86 | System.out.println("Total Number of Miss: " + miss); 87 | float ratio = (hits / (hits + miss)) * 100; 88 | System.out.println("\nHit Ratio: " + ratio + "%"); 89 | System.out.println("Miss Ratio: " + (100 - ratio) + "%"); 90 | } 91 | 92 | void printCurrent(boolean ok) { 93 | System.out.print("|\t"); 94 | for(int i = 0; i < noOfFrames; ++i) { 95 | System.out.print((PR[i] >= 0) ? PR[i] : "-"); 96 | System.out.print("\t|\t"); 97 | } 98 | System.out.println((ok) ? "Hit" : "Miss"); 99 | } 100 | } 101 | 102 | class PageReplacementLRU { 103 | public static void main(String args[]) throws IOException 104 | { 105 | FIFO m = new FIFO(); 106 | m.welcomeMessage(); 107 | } 108 | } -------------------------------------------------------------------------------- /Operating System (OS)/PagingSimulator/PagingSimulator.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | typedef long long int ll; 6 | typedef unsigned long long int ull; 7 | typedef long double ld; 8 | 9 | #define f(i, a, b) for(int (i) = (a); (i) < (b); ++(i)) 10 | #define all(a) (a).begin(), (a).end() 11 | #define deb(x) cout << #x << ": " << x << endl; 12 | 13 | int main() 14 | { 15 | ll processSize = 0, pageSize = 0, mainSize = 0; 16 | cout << "Enter the Size of a process (in KB): "; 17 | cin >> processSize; 18 | cout << "Enter the Page Size (in bytes): "; 19 | cin >> pageSize; 20 | cout << "Enter the Size of the Physical Memory (in MB): "; 21 | cin >> mainSize; 22 | 23 | ll totalFrames = (mainSize * pow(2, 20)) / pageSize; 24 | ll numberOfPages = (processSize * pow(2, 10)) / pageSize; 25 | 26 | ld bitsOfPageSize = log2(pageSize); 27 | ld bitsOfTotalFrames = log2(totalFrames); 28 | ld bitsOfNumberOfPages = log2(numberOfPages); 29 | 30 | cout << "\n1. Total number of frames in main memory: " << totalFrames << endl; 31 | cout << "2. Total number of entries in page table: " << numberOfPages << endl; 32 | 33 | cout << "3. Number of bits in Physical Address: " << bitsOfPageSize + bitsOfTotalFrames << " bits" << endl; 34 | cout << "4. Number of bits in Logical Address: " << bitsOfPageSize + bitsOfNumberOfPages << " bits" << endl; 35 | 36 | ll sizeOfPageTable = 0; 37 | cout << "\nEnter the number of entries in the Page Table: "; 38 | cin >> sizeOfPageTable; 39 | 40 | map pageTable; 41 | 42 | f(i, 0, sizeOfPageTable) { 43 | cout << endl; 44 | ll pageNumber, frameNumber; 45 | cout << "Enter Page Number: "; 46 | cin >> pageNumber; 47 | cout << "Enter Frame Number: "; 48 | cin >> frameNumber; 49 | 50 | pageTable[pageNumber] = frameNumber; 51 | } 52 | 53 | cout << "Page No. Frame No. Valid Bit" << endl; 54 | 55 | f(i, 0, numberOfPages) { 56 | // Page No. 57 | cout << i << " \t "; 58 | 59 | // Frame No. & Valid Bit 60 | cout << pageTable[i] << " \t " << ((pageTable[i]) ? "1" : "0") << endl; 61 | } 62 | 63 | cout << endl; 64 | bool ok = 1; 65 | while(ok) { 66 | string logicalAddress; 67 | cout << "\nEnter " << bitsOfPageSize + bitsOfNumberOfPages << " bits of Logical Address: "; 68 | cin >> logicalAddress; 69 | reverse(all(logicalAddress)); 70 | ll number = 0, j = 0; 71 | f(i, 0, logicalAddress.length()) { 72 | number += (logicalAddress[i] - '0') * pow(2, j++); 73 | } 74 | deb(number) 75 | cout << ((pageTable[number]) ? "PAGE HIT" : "PAGE MISS") << endl; 76 | cout << "\nContinue? [0 / 1]: "; 77 | cin >> ok; 78 | } 79 | 80 | return 0; 81 | } 82 | -------------------------------------------------------------------------------- /Operating System (OS)/SchedulingAlgorithms/FCFS.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | class FirstComeFirstServe { 5 | // hardcoded values if the user does not want to enter the values; 6 | float[] burstTime = new float[] { 24, 3, 3 }; 7 | int processes = 3; 8 | Scanner s = new Scanner(System.in); 9 | float avgTAT = 0, avgWT = 0, WT = 0, TAT = 0; 10 | 11 | void processInput() { 12 | System.out.print("\nEnter the number of the process that needs to be added (in KB): "); 13 | processes = s.nextInt(); 14 | burstTime = new float[100]; 15 | for(int i = 0; i < processes; ++i) { 16 | System.out.print("Enter the burst time of P" + (i + 1) + " (in s): "); 17 | burstTime[i] = s.nextInt(); 18 | } 19 | } 20 | 21 | void sortBurstTime() { 22 | Arrays.sort(burstTime); 23 | TWTime(); 24 | } 25 | 26 | // a method for calculation of Turnaround and Waiting Time; 27 | void TWTime() { 28 | processInput(); 29 | ganttChart(); 30 | // Printing Time for each process in a tabular format; 31 | System.out.println("\n+------------------------------------------------------+"); 32 | System.out.println("| Process \t Turn Around Time\t Waiting time |"); 33 | for(int i = 0; i < processes; ++i) { 34 | System.out.print("| P" + (i + 1) + "\t\t " + TAT + "s"); 35 | if(i < processes - 1) { 36 | TAT += burstTime[i]; 37 | avgTAT += TAT; 38 | } 39 | WT += burstTime[i]; 40 | avgWT += WT; 41 | System.out.println("\t\t " + WT + "s |"); 42 | } 43 | System.out.println("+------------------------------------------------------+"); 44 | 45 | // Printing Average; 46 | System.out.println("+----------------------------------+"); 47 | System.out.format("| Average Turn Around Time: %.2fs |\n", (avgTAT / processes)); 48 | System.out.format("| Average Waiting Time: %.2fs |\n", (avgWT / processes)); 49 | System.out.println("+----------------------------------+"); 50 | 51 | } 52 | 53 | void ganttChart() { 54 | System.out.println("\n\t\t Gantt Chart "); 55 | System.out.print("\n Process: "); 56 | for(int i = 0; i < processes; ++i) { 57 | System.out.print("\t P" + (i + 1)); 58 | } 59 | System.out.print("\n"); 60 | System.out.print("\n Burst Time: "); 61 | for(int i = 0; i < processes; ++i) { 62 | System.out.print("\t" + burstTime[i] + "s"); 63 | } 64 | System.out.println(); 65 | } 66 | } 67 | 68 | public class FCFS { 69 | public static void main(String args[]) throws IOException 70 | { 71 | FirstComeFirstServe fcfs = new FirstComeFirstServe(); 72 | fcfs.TWTime(); 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /Operating System (OS)/SchedulingAlgorithms/ShortestJobFirst.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | class SJF { 5 | // hardcoded values if the user does not want to enter the values; 6 | float[] burstTime = new float[] { 24, 3, 3 }; 7 | int processes = 3; 8 | Scanner s = new Scanner(System.in); 9 | float avgTAT = 0, avgWT = 0, WT = 0, TAT = 0; 10 | 11 | void processInput() { 12 | System.out.print("\nEnter the number of the process that needs to be added (in KB): "); 13 | processes = s.nextInt(); 14 | burstTime = new float[100]; 15 | for(int i = 0; i < processes; ++i) { 16 | System.out.print("Enter the burst time of P" + (i + 1) + " (in s): "); 17 | burstTime[i] = s.nextFloat(); 18 | } 19 | // Sorting since the algorithm is for shortest Job First; 20 | for (int i = 0; i < processes; i++) 21 | { 22 | for (int j = i + 1; j < processes; j++) 23 | { 24 | float tmp; 25 | if (burstTime[i] > burstTime[j]) 26 | { 27 | tmp = burstTime[i]; 28 | burstTime[i] = burstTime[j]; 29 | burstTime[j] = tmp; 30 | } 31 | } 32 | } 33 | } 34 | 35 | // a method for calculation of Turnaround and Waiting Time; 36 | void TWTime() { 37 | processInput(); 38 | ganttChart(); 39 | // Printing Time for each process in a tabular format; 40 | System.out.println("\n+------------------------------------------------------+"); 41 | System.out.println("| Process \t Turn Around Time\t Waiting time |"); 42 | for(int i = 0; i < processes; ++i) { 43 | System.out.print("| P" + (i + 1) + "\t\t " + TAT + "s"); 44 | if(i < processes - 1) { 45 | TAT += burstTime[i]; 46 | avgTAT += TAT; 47 | } 48 | WT += burstTime[i]; 49 | avgWT += WT; 50 | System.out.println("\t\t " + WT + "s |"); 51 | } 52 | System.out.println("+------------------------------------------------------+"); 53 | 54 | // Printing Average; 55 | System.out.println("+----------------------------------+"); 56 | System.out.format("| Average Turn Around Time: %.2fs |\n", (avgTAT / processes)); 57 | System.out.format("| Average Waiting Time: %.2fs |\n", (avgWT / processes)); 58 | System.out.println("+----------------------------------+"); 59 | 60 | } 61 | 62 | void ganttChart() { 63 | System.out.println("\n\t\t Gantt Chart "); 64 | System.out.print("\n Process: "); 65 | for(int i = 0; i < processes; ++i) { 66 | System.out.print("\t P" + (i + 1)); 67 | } 68 | System.out.print("\n"); 69 | System.out.print("\n Burst Time: "); 70 | for(int i = 0; i < processes; ++i) { 71 | System.out.print("\t" + burstTime[i] + "s"); 72 | } 73 | System.out.println(); 74 | } 75 | } 76 | 77 | 78 | public class ShortestJobFirst { 79 | public static void main(String args[]) throws IOException 80 | { 81 | SJF sjf = new SJF(); 82 | sjf.TWTime(); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /Operating System (OS)/ShellScripts/01_Add2.sh: -------------------------------------------------------------------------------- 1 | # * Write a shell program to Add 2 numbers 2 | 3 | read -p "Enter the first number: " a 4 | read -p "Enter the second number: " b 5 | echo "The sum of $a and $b is $((a+b))" 6 | -------------------------------------------------------------------------------- /Operating System (OS)/ShellScripts/02_EvenOdd.sh: -------------------------------------------------------------------------------- 1 | # * Write a shell program to check if a number entered is even and odd 2 | 3 | read -p "Enter a number: " num 4 | if [ $((num%2)) -eq 1 ] 5 | then 6 | echo "$num is odd." 7 | else 8 | echo "$num is even." 9 | fi 10 | -------------------------------------------------------------------------------- /Operating System (OS)/ShellScripts/03_Sum.sh: -------------------------------------------------------------------------------- 1 | # * Write a shell program to find sum of n numbers 2 | 3 | read -p "Enter a number: " num 4 | sum=0 5 | echo "Enter $num numbers: " 6 | for((i=0; i<$num; i++)) 7 | do 8 | read -p "Enter number $((i+1)): " a 9 | sum=$((sum+a)) 10 | done 11 | echo "The sum of the entered numbers is $sum" 12 | -------------------------------------------------------------------------------- /Operating System (OS)/ShellScripts/04_EligiblityForVoting.sh: -------------------------------------------------------------------------------- 1 | # * Determine if a person is eligible to vote or not 2 | 3 | read -p "Enter the age of the candidate: " age 4 | if (($age >= 18)); 5 | then 6 | echo "The candidate is eligible for voting." 7 | else 8 | echo "The candidate is not eligible for voting." 9 | fi 10 | -------------------------------------------------------------------------------- /Operating System (OS)/ShellScripts/05_DisplayingFiles.sh: -------------------------------------------------------------------------------- 1 | # * Display all filenames beginning with character ‘a’ and displays its contents 2 | 3 | for file in a* 4 | do 5 | echo -e "\nIn $file:" 6 | cat $file 7 | done 8 | -------------------------------------------------------------------------------- /Operating System (OS)/ShellScripts/06_Factorial.sh: -------------------------------------------------------------------------------- 1 | # * Write a shell program to find factorial of a number 2 | 3 | read -p "Enter a number: " num 4 | fac=1 5 | for ((i=1;i<=$num;i++)) 6 | do 7 | fac=$((fac*i)) 8 | done 9 | echo "$num! is $fac" 10 | -------------------------------------------------------------------------------- /Operating System (OS)/ShellScripts/07_LoginCheck.sh: -------------------------------------------------------------------------------- 1 | # * Write a shell program to check validity of a username and password with a function defined in the code 2 | 3 | function check 4 | { 5 | if [[ $username == "ADMIN" && $password == "123456" ]] 6 | then 7 | bool=1 8 | else 9 | bool=0 10 | fi 11 | } 12 | read -p "Enter the username: " username 13 | read -p "Enter the password: " password 14 | check 15 | if (($bool==1)) 16 | then 17 | echo "Username and Password verified." 18 | else 19 | echo "Username and Password not verified." 20 | fi -------------------------------------------------------------------------------- /Python/Experiment_04.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Experiment No. 4 " 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "## Lists in Python\n", 15 | "\n", 16 | "\n", 17 | "List\n", 18 | "- It consists of a group of elements.\n", 19 | "- A single list may contain DataTypes like Integers, Strings, as well as Objects.\n", 20 | "- They are dynamic, mutable & ordered.\n", 21 | "- It is represented by square brackets.\n", 22 | "\n", 23 | "Operation on List used\n", 24 | "1. append(x) - To add value x at end of the list\n", 25 | "2. sort() -To sort items in a list in ascending order\n" 26 | ] 27 | }, 28 | { 29 | "cell_type": "markdown", 30 | "metadata": {}, 31 | "source": [ 32 | "Q1. Write a menu driven program to demonstrate use of list in python\n", 33 | "1. Put even and odd elements in two different list\n", 34 | "2. Merge and sort two list\n", 35 | "3. Update the first element with a value X\n", 36 | "4. Print middle element of list" 37 | ] 38 | }, 39 | { 40 | "cell_type": "code", 41 | "execution_count": 3, 42 | "metadata": {}, 43 | "outputs": [ 44 | { 45 | "name": "stdout", 46 | "output_type": "stream", 47 | "text": [ 48 | "Enter Number Of Elements in List5\n", 49 | "Enter element: 8\n", 50 | "Enter element: 7\n", 51 | "Enter element: 4\n", 52 | "Enter element: 9\n", 53 | "Enter element: 2\n", 54 | "Output:-\n", 55 | "\n", 56 | "1.Put even and odd elemnts in two different list\n", 57 | "2.Merge and sort two list\n", 58 | "3.Update the first element with a value X\n", 59 | "4.Print middle element of list\n", 60 | "5.Exit\n", 61 | "Enter choice: 1\n", 62 | "The even list: [8, 4, 2]\n", 63 | "The odd list: [7, 9]\n", 64 | "\n", 65 | "1.Put even and odd elemnts in two different list\n", 66 | "2.Merge and sort two list\n", 67 | "3.Update the first element with a value X\n", 68 | "4.Print middle element of list\n", 69 | "5.Exit\n", 70 | "Enter choice: 2\n", 71 | "Enter number of elements: 4\n", 72 | "Enter element: 1\n", 73 | "Enter element: 5\n", 74 | "Enter element: 4\n", 75 | "Enter element: 6\n", 76 | "Sorted list is: [1, 2, 4, 4, 5, 6, 7, 8, 9]\n", 77 | "\n", 78 | "1.Put even and odd elemnts in two different list\n", 79 | "2.Merge and sort two list\n", 80 | "3.Update the first element with a value X\n", 81 | "4.Print middle element of list\n", 82 | "5.Exit\n", 83 | "Enter choice: 3\n", 84 | "Enter number of elements: 5\n", 85 | "Enter element: 4\n", 86 | "Enter element: 5\n", 87 | "Enter element: 8\n", 88 | "Enter element: 7\n", 89 | "Enter element: 9\n", 90 | "original list [4, 5, 8, 7, 9]\n", 91 | "Enter the Element which is to be added6\n", 92 | "The updated list [6, 5, 8, 7, 9]\n", 93 | "\n", 94 | "1.Put even and odd elemnts in two different list\n", 95 | "2.Merge and sort two list\n", 96 | "3.Update the first element with a value X\n", 97 | "4.Print middle element of list\n", 98 | "5.Exit\n", 99 | "Enter choice: 4\n", 100 | "Enter number of elements:6\n", 101 | "Enter element:9\n", 102 | "Enter element:8\n", 103 | "Enter element:7\n", 104 | "Enter element:5\n", 105 | "Enter element:4\n", 106 | "Enter element:6\n", 107 | "list is [9, 8, 7, 5, 4, 6]\n", 108 | "mid value is 5\n", 109 | "\n", 110 | "1.Put even and odd elemnts in two different list\n", 111 | "2.Merge and sort two list\n", 112 | "3.Update the first element with a value X\n", 113 | "4.Print middle element of list\n", 114 | "5.Exit\n", 115 | "Enter choice: 5\n" 116 | ] 117 | } 118 | ], 119 | "source": [ 120 | "n=int(input('Enter Number Of Elements in List'))\n", 121 | "lst=[]\n", 122 | "for i in range(0,n,1):\n", 123 | " ele=int(input('Enter element: '))\n", 124 | " lst.append(ele)\n", 125 | " \n", 126 | "print(\"Output:-\")\n", 127 | "choice = 1\n", 128 | "while choice != 0:\n", 129 | " print(\"\\n1.Put even and odd elemnts in two different list\")\n", 130 | " print(\"2.Merge and sort two list\")\n", 131 | " print(\"3.Update the first element with a value X\")\n", 132 | " print(\"4.Print middle element of list\")\n", 133 | " print(\"5.Exit\")\n", 134 | " choice = int(input(\"Enter choice: \"))\n", 135 | " if choice == 1:\n", 136 | " even = []\n", 137 | " odd = []\n", 138 | " for j in lst:\n", 139 | " if j % 2 == 0:\n", 140 | " even.append(j)\n", 141 | " else:\n", 142 | " odd.append(j)\n", 143 | " print(\"The even list: \", even)\n", 144 | " print(\"The odd list: \", odd)\n", 145 | " elif (choice == 2):\n", 146 | " d = []\n", 147 | " new = []\n", 148 | " n1 = int(input(\"Enter number of elements: \"))\n", 149 | " for i in range(1, n1 + 1):\n", 150 | " f = int(input(\"Enter element: \"))\n", 151 | " d.append(f)\n", 152 | " new = lst + d\n", 153 | " new.sort()\n", 154 | " print('Sorted list is: ', new)\n", 155 | " elif choice==3:\n", 156 | " h=[] \n", 157 | " n2=int(input(\"Enter number of elements: \")) \n", 158 | " for i in range(1,n2+1):\n", 159 | " k=int(input(\"Enter element: \"))\n", 160 | " h.append(k) \n", 161 | " print(\"original list \",h) \n", 162 | " elmnt=int(input(\"Enter the Element which is to be added\")) \n", 163 | " h[0]=elmnt \n", 164 | " print(\"The updated list \",h) \n", 165 | " elif choice==4:\n", 166 | " y=[] \n", 167 | " n3=int(input(\"Enter number of elements:\")) \n", 168 | " for i in range(1,n3+1):\n", 169 | " x=int(input(\"Enter element:\"))\n", 170 | " y.append(x)\n", 171 | " print(\"list is \",y) \n", 172 | " print(\"mid value is \",y[int(len(y)/2)]) \n", 173 | " elif choice==5:\n", 174 | " break \n", 175 | " else: \n", 176 | " print(\"Please enter a valid choice\")\n" 177 | ] 178 | }, 179 | { 180 | "cell_type": "markdown", 181 | "metadata": {}, 182 | "source": [ 183 | "\n", 184 | "## Tuples in Python\n", 185 | "\n", 186 | "A tuple in Python is similar to a list.\n", 187 | "\n", 188 | "The difference between the two is that we cannot change the elements of a tuple once it is assigned whereas we can change the elements of a list.\n", 189 | "\n", 190 | "A tuple is created by placing all the items (elements) inside parentheses (), separated by commas. The parentheses are optional, however, it is a good practice to use them.\n", 191 | "\n", 192 | "In this question we used list to take in the input from user and later convert it into tuple\n", 193 | "\n", 194 | "Program\n", 195 | "\n", 196 | "Q2. Write a menu driven program to demonstrate use of tuple in python\n", 197 | "1. Add and show details i.e roll no, name and marks of three subjects of N students in a list of tuple\n", 198 | "2. Display details of a student whose name is X" 199 | ] 200 | }, 201 | { 202 | "cell_type": "code", 203 | "execution_count": 1, 204 | "metadata": {}, 205 | "outputs": [ 206 | { 207 | "name": "stdout", 208 | "output_type": "stream", 209 | "text": [ 210 | "MENU\n", 211 | "\n", 212 | "1. Add new student\n", 213 | "2. Display student info\n", 214 | "3. Exit\n", 215 | "Enter your choice:\n", 216 | "1\n", 217 | "Enter student roll no:112\n", 218 | "Enter student name:Tushar\n", 219 | "Enter student physics marks:12\n", 220 | "Enter student chemistry marks:24\n", 221 | "Enter student maths marks:36\n", 222 | "MENU\n", 223 | "\n", 224 | "1. Add new student\n", 225 | "2. Display student info\n", 226 | "3. Exit\n", 227 | "Enter your choice:\n", 228 | "1\n", 229 | "Enter student roll no:113\n", 230 | "Enter student name:Vivek\n", 231 | "Enter student physics marks:55\n", 232 | "Enter student chemistry marks:68\n", 233 | "Enter student maths marks:75\n", 234 | "MENU\n", 235 | "\n", 236 | "1. Add new student\n", 237 | "2. Display student info\n", 238 | "3. Exit\n", 239 | "Enter your choice:\n", 240 | "1\n", 241 | "Enter student roll no:114\n", 242 | "Enter student name:Parth\n", 243 | "Enter student physics marks:89\n", 244 | "Enter student chemistry marks:78\n", 245 | "Enter student maths marks:54\n", 246 | "MENU\n", 247 | "\n", 248 | "1. Add new student\n", 249 | "2. Display student info\n", 250 | "3. Exit\n", 251 | "Enter your choice:\n", 252 | "2\n", 253 | "Enter name of student whose details are to be displayed:Tushar\n", 254 | "['112', 'Tushar', '12', '24', '36']\n", 255 | "MENU\n", 256 | "\n", 257 | "1. Add new student\n", 258 | "2. Display student info\n", 259 | "3. Exit\n", 260 | "Enter your choice:\n", 261 | "2\n", 262 | "Enter name of student whose details are to be displayed:Vivek\n", 263 | "['113', 'Vivek', '55', '68', '75']\n", 264 | "MENU\n", 265 | "\n", 266 | "1. Add new student\n", 267 | "2. Display student info\n", 268 | "3. Exit\n", 269 | "Enter your choice:\n", 270 | "3\n", 271 | "Thank you for using the system!\n" 272 | ] 273 | } 274 | ], 275 | "source": [ 276 | "students=[]\n", 277 | "ch=0 \n", 278 | "while(ch!=3):\n", 279 | " print(\"MENU\\n\") \n", 280 | " print(\"1. Add new student\\n2. Display student info\\n3. Exit\\nEnter your choice:\") \n", 281 | " ch=int(input()) \n", 282 | " if (ch==1): \n", 283 | " list=[] \n", 284 | " rollno = input(\"Enter student roll no:\") \n", 285 | " list.append(rollno) \n", 286 | " name = input(\"Enter student name:\") \n", 287 | " list.append(name) \n", 288 | " marks1= input(\"Enter student physics marks:\") \n", 289 | " list.append(marks1) \n", 290 | " marks2= input(\"Enter student chemistry marks:\") \n", 291 | " list.append(marks2) \n", 292 | " marks3= input(\"Enter student maths marks:\") \n", 293 | " list.append(marks3) \n", 294 | " students.append(list) \n", 295 | " elif (ch==2): \n", 296 | " flag=0 \n", 297 | " target=input(\"Enter name of student whose details are to be displayed:\") \n", 298 | " for index, tuple in enumerate(students):\n", 299 | " name=tuple[1] \n", 300 | " if(name==target):\n", 301 | " print(students[index]) \n", 302 | " flag=1 \n", 303 | " break \n", 304 | " if (flag==0):\n", 305 | " print(\"Student does not exist in the list\") \n", 306 | " elif (ch==3): \n", 307 | " print(\"Thank you for using the system!\")\n" 308 | ] 309 | }, 310 | { 311 | "cell_type": "markdown", 312 | "metadata": {}, 313 | "source": [ 314 | "## Sets in Python \n", 315 | "\n", 316 | "Sets\n", 317 | "\n", 318 | "- Sets are unordered\n", 319 | "- Set elements are unique.\n", 320 | "- Duplicate elements are not allowed\n", 321 | "- A set itself is mutable i.e. you can add or remove elements from set\n", 322 | "- Elements contained in the sets must be of immutable type. (strings, tuples, Numeric)\n", 323 | "- Sets can have different type of elements that is they can be heterogeneous in nature\n", 324 | "\n", 325 | "#### Set Methods\n", 326 | "1. intersection()\tReturns a set, that is the intersection of two other sets\n", 327 | "2. union()\tReturn a set containing the union of sets\n", 328 | "3. difference()\tReturns a set containing the difference between two or more sets\n", 329 | "4. symmetric_difference()\tReturns a set with the symmetric differences of two sets\n", 330 | "\n", 331 | "Program\n", 332 | "\n", 333 | "Q3. Write a menu driven program to demonstrate use of set in python\n", 334 | "1. Read two sets A and B from user and display set A and B\n", 335 | "2. Perform intersection A ∩ B of two sets A and B\n", 336 | "3. Perform union A UB of two sets A and B\n", 337 | "4. Perform set difference A -B of two sets A and B\n", 338 | "5. Perform symmetric difference A ^ B of two sets A and B" 339 | ] 340 | }, 341 | { 342 | "cell_type": "code", 343 | "execution_count": 2, 344 | "metadata": {}, 345 | "outputs": [ 346 | { 347 | "name": "stdout", 348 | "output_type": "stream", 349 | "text": [ 350 | "Output:-\n", 351 | "Enter the set A:8 7 9 4 1 2\n", 352 | "{'1', '9', '4', ' ', '8', '7', '2'}\n", 353 | "Enter the set B:5 6 6 7 8 7\n", 354 | "{'6', ' ', '8', '7', '5'}\n", 355 | "1.Perform intersection A ∩ B of two sets A and B\n", 356 | "2.Perform union A ∩ B of two sets A and B\n", 357 | "3.Perform set difference A U B of two sets A and B\n", 358 | "4.Perform symmetric difference A ^ B of two sets A and B\n", 359 | "5.Exit\n", 360 | "Enter choice: 1\n", 361 | "{'7', ' ', '8'}\n", 362 | "\n", 363 | "1.Perform intersection A ∩ B of two sets A and B\n", 364 | "2.Perform union A ∩ B of two sets A and B\n", 365 | "3.Perform set difference A U B of two sets A and B\n", 366 | "4.Perform symmetric difference A ^ B of two sets A and B\n", 367 | "5.Exit\n", 368 | "Enter choice: 2\n", 369 | "{'6', '1', '9', '4', ' ', '5', '8', '7', '2'}\n", 370 | "\n", 371 | "1.Perform intersection A ∩ B of two sets A and B\n", 372 | "2.Perform union A ∩ B of two sets A and B\n", 373 | "3.Perform set difference A U B of two sets A and B\n", 374 | "4.Perform symmetric difference A ^ B of two sets A and B\n", 375 | "5.Exit\n", 376 | "Enter choice: 3\n", 377 | "{'4', '1', '9', '2'}\n", 378 | "\n", 379 | "1.Perform intersection A ∩ B of two sets A and B\n", 380 | "2.Perform union A ∩ B of two sets A and B\n", 381 | "3.Perform set difference A U B of two sets A and B\n", 382 | "4.Perform symmetric difference A ^ B of two sets A and B\n", 383 | "5.Exit\n", 384 | "Enter choice: 4\n", 385 | "{'6', '1', '9', '4', '5', '2'}\n", 386 | "\n", 387 | "1.Perform intersection A ∩ B of two sets A and B\n", 388 | "2.Perform union A ∩ B of two sets A and B\n", 389 | "3.Perform set difference A U B of two sets A and B\n", 390 | "4.Perform symmetric difference A ^ B of two sets A and B\n", 391 | "5.Exit\n", 392 | "Enter choice: 5\n" 393 | ] 394 | } 395 | ], 396 | "source": [ 397 | "print(\"Output:-\")\n", 398 | "A={}\n", 399 | "B={}\n", 400 | "A=set(input(\"Enter the set A:\")) \n", 401 | "print(A)\n", 402 | "B=set(input(\"Enter the set B:\")) \n", 403 | "print(B) \n", 404 | "choice=1 \n", 405 | "while choice!=0:\n", 406 | " print(\"1.Perform intersection A ∩ B of two sets A and B\") \n", 407 | " print(\"2.Perform union A ∩ B of two sets A and B\") \n", 408 | " print(\"3.Perform set difference A U B of two sets A and B\") \n", 409 | " print(\"4.Perform symmetric difference A ^ B of two sets A and B\") \n", 410 | " print(\"5.Exit\") \n", 411 | " choice=int(input(\"Enter choice: \")) \n", 412 | " if choice==1: \n", 413 | " print(A & B) \n", 414 | " print() \n", 415 | " elif choice==2: \n", 416 | " print(A | B) \n", 417 | " print() \n", 418 | " elif choice==3: \n", 419 | " print(A - B) \n", 420 | " print() \n", 421 | " elif choice==4: \n", 422 | " print(A ^ B) \n", 423 | " print() \n", 424 | " elif choice==5:\n", 425 | " break \n", 426 | " else:\n", 427 | " print(\"Enter a valid choice. \") \n", 428 | " print()\n" 429 | ] 430 | }, 431 | { 432 | "cell_type": "markdown", 433 | "metadata": {}, 434 | "source": [ 435 | "\n", 436 | "## Dictionary in Python\n", 437 | "\n", 438 | "- A dictionary represents a group of elements arranged in the form of key-value pairs.\n", 439 | "- In the dictionary, the first element is considered as 'key' and immediate next element is taken as its 'value'.\n", 440 | "- The key and values are separated by colon ( : )\n", 441 | "- All the key-value pairs in a dictionary are inserted in curly braces\n", 442 | "\n", 443 | "Methods Used\n", 444 | "\n", 445 | "- sorted( ) function can be used to sort the dictionary.\n", 446 | "- By default, the elements are sorted in ascending order.\n", 447 | "- The format of sorted function is\n", 448 | "- sorted(elements, key = )\n", 449 | "- Elements of the dictionary can be accessed using method d.items() \n", 450 | "- key can be assigned with lambda function which will determine whether data to be sorted using Keys or Values.\n", 451 | "- Following function will consider keys for sorting the elements \n", 452 | " key = lambda t : t[0]\n", 453 | "\n", 454 | "Program\n", 455 | " \n", 456 | "Q4. Write a program to demonstrate use of dictionary in python\n", 457 | "1. Read a dictionary from the user and display.\n", 458 | "2. To sort a dictionary by key\n", 459 | "3. Concatenate two Python dictionaries into a new one" 460 | ] 461 | }, 462 | { 463 | "cell_type": "code", 464 | "execution_count": 2, 465 | "metadata": {}, 466 | "outputs": [ 467 | { 468 | "name": "stdout", 469 | "output_type": "stream", 470 | "text": [ 471 | "Output:-\n", 472 | "Enter the no of elements for a 3\n", 473 | "Enter the key 112\n", 474 | "Enter the value Tushar\n", 475 | "Enter the key 113\n", 476 | "Enter the value Vivek\n", 477 | "Enter the key 114\n", 478 | "Enter the value Aakash\n", 479 | "\n", 480 | "The dictionary a is: {'112': 'Tushar', '113': 'Vivek', '114': 'Aakash'}\n", 481 | "\n", 482 | "Enter the no of elements for b 2\n", 483 | "Enter the key 115\n", 484 | "Enter the value Rohit\n", 485 | "Enter the key 116\n", 486 | "Enter the value Chinmay\n", 487 | "\n", 488 | "The dictionary b is: {'115': 'Rohit', '116': 'Chinmay'}\n", 489 | "\n", 490 | "The sorted dictionary a according to the key is [('112', 'Tushar'), ('113', 'Vivek'), ('114', 'Aakash')]\n", 491 | "\n", 492 | "The sorted dictionary b according to the key is [('115', 'Rohit'), ('116', 'Chinmay')]\n", 493 | "\n", 494 | "The concatenated dictionary is {'112': 'Tushar', '113': 'Vivek', '114': 'Aakash', '115': 'Rohit', '116': 'Chinmay'}\n" 495 | ] 496 | } 497 | ], 498 | "source": [ 499 | "print(\"Output:-\") \n", 500 | "a={} \n", 501 | "b={} \n", 502 | "n=int(input(\"Enter the no of elements for a \")) \n", 503 | "for i in range(n):\n", 504 | " k=input(\"Enter the key \") \n", 505 | " v=input(\"Enter the value \")\n", 506 | " a.update({k:v}) \n", 507 | "print() \n", 508 | "print(\"The dictionary a is: \",a) \n", 509 | "print() \n", 510 | "n1=int(input(\"Enter the no of elements for b \")) \n", 511 | "for i in range(n1):\n", 512 | " t=input(\"Enter the key \") \n", 513 | " w=input(\"Enter the value \")\n", 514 | " b.update({t:w}) \n", 515 | "print() \n", 516 | "print(\"The dictionary b is:\",b) \n", 517 | "print() \n", 518 | "print(\"The sorted dictionary a according to the key is \", sorted(a.items())) \n", 519 | "print() \n", 520 | "print(\"The sorted dictionary b according to the key is \", sorted(b.items())) \n", 521 | "print()\n", 522 | "a.update(b)\n", 523 | "print(\"The concatenated dictionary is \",a)\n" 524 | ] 525 | } 526 | ], 527 | "metadata": { 528 | "kernelspec": { 529 | "display_name": "Python 3", 530 | "language": "python", 531 | "name": "python3" 532 | }, 533 | "language_info": { 534 | "codemirror_mode": { 535 | "name": "ipython", 536 | "version": 3 537 | }, 538 | "file_extension": ".py", 539 | "mimetype": "text/x-python", 540 | "name": "python", 541 | "nbconvert_exporter": "python", 542 | "pygments_lexer": "ipython3", 543 | "version": "3.7.6" 544 | } 545 | }, 546 | "nbformat": 4, 547 | "nbformat_minor": 4 548 | } 549 | -------------------------------------------------------------------------------- /Python/PhoneBook.txt: -------------------------------------------------------------------------------- 1 | Nankani Tushar 8496204146 2 | Rao Jay 5946984169 3 | Rao Kivek 6846514544 4 | Rao Khan 6541714645 5 | Palav Amrita 8469849846 6 | -------------------------------------------------------------------------------- /Python/Q6.py: -------------------------------------------------------------------------------- 1 | def addAll(nums): 2 | total = 0 3 | for num in nums: 4 | total += num 5 | print("\nAddition is:", total) 6 | 7 | def multiplyAll(nums): 8 | total = 1 9 | for num in nums: 10 | total *= num 11 | print("\nProduct is:", total) 12 | 13 | def addAllEven(nums): 14 | total = 0 15 | for i in range(0, len(nums), 2): 16 | total += nums[i] 17 | print("\nAddition at even indices is:", total) 18 | 19 | def insertItems(nums): 20 | num = int(input("Enter a number to be appended: ")) 21 | nums.append(num) 22 | print("\nThe final list is:", nums) -------------------------------------------------------------------------------- /Python/customer_details.txt: -------------------------------------------------------------------------------- 1 | 1, ABC, 12345 2 | 2, DEF, 89461 3 | 3, XYZ, 98416 4 | -------------------------------------------------------------------------------- /Python/experiment_01.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Experiment No. 1" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "### Q 1. Write a python program to print following lines in specific format\n", 15 | "\n", 16 | "```\n", 17 | "Twinkle Twinkle Little Star,\n", 18 | "       \"How I wonder what you are!\"\n", 19 | "              Up above the world so high\n", 20 | "              Like a diamond in the sky.\n", 21 | "'Twinkle Twinkle' Little star\n", 22 | "        How I wonder what you are\n", 23 | "```\n", 24 | "Using only one print() function\n", 25 | "\n", 26 | "SOLUTION:" 27 | ] 28 | }, 29 | { 30 | "cell_type": "code", 31 | "execution_count": 1, 32 | "metadata": {}, 33 | "outputs": [ 34 | { 35 | "name": "stdout", 36 | "output_type": "stream", 37 | "text": [ 38 | "\n", 39 | "Twinkle Twinkle Little Star,\n", 40 | " \"How I wonder what you are!\"\n", 41 | " Up above the world so high\n", 42 | " Like a diamond in the sky.\n", 43 | "'Twinkle Twinkle' Little star\n", 44 | " How I wonder what you are\n", 45 | "\n" 46 | ] 47 | } 48 | ], 49 | "source": [ 50 | "print('''\n", 51 | "Twinkle Twinkle Little Star,\n", 52 | " \"How I wonder what you are!\"\n", 53 | " Up above the world so high\n", 54 | " Like a diamond in the sky.\n", 55 | "'Twinkle Twinkle' Little star\n", 56 | " How I wonder what you are\n", 57 | "''')" 58 | ] 59 | }, 60 | { 61 | "cell_type": "markdown", 62 | "metadata": {}, 63 | "source": [ 64 | "### Q 2. Program to show output formatting take two values and display them using single print() function\n", 65 | "- Str.format()\n", 66 | "- % operator" 67 | ] 68 | }, 69 | { 70 | "cell_type": "code", 71 | "execution_count": 2, 72 | "metadata": {}, 73 | "outputs": [ 74 | { 75 | "name": "stdout", 76 | "output_type": "stream", 77 | "text": [ 78 | "Enter a: 5\n", 79 | "Enter b: 9\n", 80 | "The first value is 5 and second one is 9\n" 81 | ] 82 | } 83 | ], 84 | "source": [ 85 | "a = int(input(\"Enter a: \"))\n", 86 | "b = int(input(\"Enter b: \"))\n", 87 | "\n", 88 | "print(\"The first value is {}\".format(a), \"and second one is %d\" % b)" 89 | ] 90 | }, 91 | { 92 | "cell_type": "markdown", 93 | "metadata": {}, 94 | "source": [ 95 | "### Q 3. Program to find whether input year is leap year or not using 'nested if'" 96 | ] 97 | }, 98 | { 99 | "cell_type": "code", 100 | "execution_count": 3, 101 | "metadata": {}, 102 | "outputs": [ 103 | { 104 | "name": "stdout", 105 | "output_type": "stream", 106 | "text": [ 107 | "Enter an year: 2024\n", 108 | "2024 is a Leap Year\n" 109 | ] 110 | } 111 | ], 112 | "source": [ 113 | "year = int(input(\"Enter an year: \"))\n", 114 | "if(year % 4 == 0):\n", 115 | " if(year % 100 or year % 400 == 0):\n", 116 | " print(\"{} is a Leap Year\".format(year))\n", 117 | " else:\n", 118 | " print(\"{} is not a Leap Year\".format(year))\n", 119 | "else:\n", 120 | " print(\"{} is not a Leap Year\".format(year))" 121 | ] 122 | }, 123 | { 124 | "cell_type": "markdown", 125 | "metadata": {}, 126 | "source": [ 127 | "### Q 4. Program to print all armstrong numbers in the range 1 to 1000" 128 | ] 129 | }, 130 | { 131 | "cell_type": "code", 132 | "execution_count": 4, 133 | "metadata": {}, 134 | "outputs": [ 135 | { 136 | "name": "stdout", 137 | "output_type": "stream", 138 | "text": [ 139 | "1 is an Armstrong Number.\n", 140 | "2 is an Armstrong Number.\n", 141 | "3 is an Armstrong Number.\n", 142 | "4 is an Armstrong Number.\n", 143 | "5 is an Armstrong Number.\n", 144 | "6 is an Armstrong Number.\n", 145 | "7 is an Armstrong Number.\n", 146 | "8 is an Armstrong Number.\n", 147 | "9 is an Armstrong Number.\n", 148 | "153 is an Armstrong Number.\n", 149 | "370 is an Armstrong Number.\n", 150 | "371 is an Armstrong Number.\n", 151 | "407 is an Armstrong Number.\n" 152 | ] 153 | } 154 | ], 155 | "source": [ 156 | "for num in range(1, 1001):\n", 157 | " l = len(str(num))\n", 158 | " total = 0\n", 159 | " for digit in str(num):\n", 160 | " total += int(digit) ** l\n", 161 | " if(total == num):\n", 162 | " print(f\"{num} is an Armstrong Number.\")" 163 | ] 164 | }, 165 | { 166 | "cell_type": "markdown", 167 | "metadata": {}, 168 | "source": [ 169 | "### Q 5. Program to find fibonacci series of n terms" 170 | ] 171 | }, 172 | { 173 | "cell_type": "code", 174 | "execution_count": 5, 175 | "metadata": {}, 176 | "outputs": [ 177 | { 178 | "name": "stdout", 179 | "output_type": "stream", 180 | "text": [ 181 | "Enter the number of terms in the Fibonacci Series: 15\n", 182 | "0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, " 183 | ] 184 | } 185 | ], 186 | "source": [ 187 | "n = int(input(\"Enter the number of terms in the Fibonacci Series: \"))\n", 188 | "\n", 189 | "a, b = 0, 1\n", 190 | "for i in range(n):\n", 191 | " print(a, end=\", \")\n", 192 | " a, b = b, a + b" 193 | ] 194 | }, 195 | { 196 | "cell_type": "markdown", 197 | "metadata": {}, 198 | "source": [ 199 | "### Q 6. Program to print pattern\n", 200 | "```\n", 201 | "A\n", 202 | "B B\n", 203 | "C C C\n", 204 | "D D D D\n", 205 | "E E E E E\n", 206 | "```" 207 | ] 208 | }, 209 | { 210 | "cell_type": "code", 211 | "execution_count": 6, 212 | "metadata": {}, 213 | "outputs": [ 214 | { 215 | "name": "stdout", 216 | "output_type": "stream", 217 | "text": [ 218 | "Enter a number between 1 and 27: 15\n", 219 | "A \n", 220 | "B B \n", 221 | "C C C \n", 222 | "D D D D \n", 223 | "E E E E E \n", 224 | "F F F F F F \n", 225 | "G G G G G G G \n", 226 | "H H H H H H H H \n", 227 | "I I I I I I I I I \n", 228 | "J J J J J J J J J J \n", 229 | "K K K K K K K K K K K \n", 230 | "L L L L L L L L L L L L \n", 231 | "M M M M M M M M M M M M M \n", 232 | "N N N N N N N N N N N N N N \n", 233 | "O O O O O O O O O O O O O O O \n" 234 | ] 235 | } 236 | ], 237 | "source": [ 238 | "n = int(input(\"Enter a number between 1 and 26: \"))\n", 239 | "while(1 > n or n > 26):\n", 240 | " n = int(input(\"Please enter a number between 1 and 26: \"))\n", 241 | " \n", 242 | "char = 'A'\n", 243 | "for num in range(1, n + 1):\n", 244 | " print(f\"{char} \" * num)\n", 245 | " char = chr(ord(char) + 1)" 246 | ] 247 | }, 248 | { 249 | "cell_type": "markdown", 250 | "metadata": {}, 251 | "source": [ 252 | "### Q 6. Program to print pattern\n", 253 | "```\n", 254 | "* * * * *\n", 255 | " * * * *\n", 256 | " * * * \n", 257 | " * *\n", 258 | " *\n", 259 | "```" 260 | ] 261 | }, 262 | { 263 | "cell_type": "code", 264 | "execution_count": 7, 265 | "metadata": {}, 266 | "outputs": [ 267 | { 268 | "name": "stdout", 269 | "output_type": "stream", 270 | "text": [ 271 | "Enter a number: 8\n", 272 | " * * * * * * * * \n", 273 | " * * * * * * * \n", 274 | " * * * * * * \n", 275 | " * * * * * \n", 276 | " * * * * \n", 277 | " * * * \n", 278 | " * * \n", 279 | " * \n" 280 | ] 281 | } 282 | ], 283 | "source": [ 284 | "n = int(input(\"Enter a number: \"))\n", 285 | "\n", 286 | "for num in range(n):\n", 287 | " print(\" \" * (num), \"* \" * (n - num))" 288 | ] 289 | }, 290 | { 291 | "cell_type": "markdown", 292 | "metadata": {}, 293 | "source": [ 294 | "### Q 6. Program to print pattern\n", 295 | "```\n", 296 | " 1\n", 297 | "           1 2 1\n", 298 | "         1 2 3 2 1\n", 299 | "       1 2 3 4 3 2 1\n", 300 | "     1 2 3 4 5 4 3 2 1\n", 301 | "```" 302 | ] 303 | }, 304 | { 305 | "cell_type": "code", 306 | "execution_count": 8, 307 | "metadata": {}, 308 | "outputs": [ 309 | { 310 | "name": "stdout", 311 | "output_type": "stream", 312 | "text": [ 313 | "Enter a number: 10\n", 314 | " 1 \n", 315 | " 1 2 1 \n", 316 | " 1 2 3 2 1 \n", 317 | " 1 2 3 4 3 2 1 \n", 318 | " 1 2 3 4 5 4 3 2 1 \n", 319 | " 1 2 3 4 5 6 5 4 3 2 1 \n", 320 | " 1 2 3 4 5 6 7 6 5 4 3 2 1 \n", 321 | " 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 \n", 322 | " 1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1 \n", 323 | "1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1 \n" 324 | ] 325 | } 326 | ], 327 | "source": [ 328 | "n = int(input(\"Enter a number: \"))\n", 329 | "\n", 330 | "for num in range(1, n + 1):\n", 331 | " print(\" \" * (n - num), end=\"\")\n", 332 | " for i in range(1, num + 1):\n", 333 | " print(i, end=\" \")\n", 334 | " for i in range(num - 1, 0, -1):\n", 335 | " print(i, end=\" \")\n", 336 | " print()" 337 | ] 338 | }, 339 | { 340 | "cell_type": "markdown", 341 | "metadata": {}, 342 | "source": [ 343 | "### Q 6. Program to print pattern\n", 344 | "\n", 345 | "```\n", 346 | " * \n", 347 | " * * \n", 348 | " * * * \n", 349 | " * * * * \n", 350 | " * * * * * \n", 351 | "```" 352 | ] 353 | }, 354 | { 355 | "cell_type": "code", 356 | "execution_count": 1, 357 | "metadata": { 358 | "scrolled": true 359 | }, 360 | "outputs": [ 361 | { 362 | "name": "stdout", 363 | "output_type": "stream", 364 | "text": [ 365 | "Enter a number: 9\n", 366 | " \n", 367 | " * \n", 368 | " * * \n", 369 | " * * * \n", 370 | " * * * * \n", 371 | " * * * * * \n", 372 | " * * * * * * \n", 373 | " * * * * * * * \n", 374 | " * * * * * * * * \n", 375 | " * * * * * * * * * \n" 376 | ] 377 | } 378 | ], 379 | "source": [ 380 | "n = int(input(\"Enter a number: \"))\n", 381 | "\n", 382 | "for num in range(n + 1):\n", 383 | " print(\" \" * (n - num), \"* \" * (num))" 384 | ] 385 | } 386 | ], 387 | "metadata": { 388 | "kernelspec": { 389 | "display_name": "Python 3", 390 | "language": "python", 391 | "name": "python3" 392 | }, 393 | "language_info": { 394 | "codemirror_mode": { 395 | "name": "ipython", 396 | "version": 3 397 | }, 398 | "file_extension": ".py", 399 | "mimetype": "text/x-python", 400 | "name": "python", 401 | "nbconvert_exporter": "python", 402 | "pygments_lexer": "ipython3", 403 | "version": "3.7.6" 404 | } 405 | }, 406 | "nbformat": 4, 407 | "nbformat_minor": 4 408 | } 409 | -------------------------------------------------------------------------------- /Python/experiment_02.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Experiment No. 2" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "## *Python Arrays*\n", 15 | "\n", 16 | "An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array).\n", 17 | "\n", 18 | "For simplicity, we can think of an array a fleet of stairs where on each step is placed a value (let’s say one of your friends). Here, you can identify the location of any of your friends by simply knowing the count of the step they are on. Array can be handled in Python by a module named array. They can be useful when we have to manipulate only a specific data type values. A user can treat lists as arrays. However, user cannot constraint the type of elements stored in a list. If you create arrays using the array module, all elements of the array must be of the same type.\n", 19 | "\n", 20 | "### Creating an Array\n", 21 | "\n", 22 | "Array in Python can be created by importing array module. `array(data_type, value_list)` is used to create an array with data type and value list specified in its arguments.\n", 23 | "\n", 24 | "```python\n", 25 | "# importing \"array\" for array creations \n", 26 | "import array as arr \n", 27 | " \n", 28 | "# creating an array with integer type \n", 29 | "a = arr.array('i', [1, 2, 3]) \n", 30 | " \n", 31 | "# creating an array with float type \n", 32 | "b = arr.array('d', [2.5, 3.2, 3.3])\n", 33 | "```\n", 34 | "\n", 35 | "### Accessing elements from the Array\n", 36 | "\n", 37 | "In order to access the array items refer to the index number. Use the index operator `[]` to access an item in a array. The index must be an integer.\n", 38 | "\n", 39 | "### Adding Elements to an Array\n", 40 | "\n", 41 | "Elements can be added to the Array by using built-in `insert()` function. Insert is used to insert one or more data elements into an array. Based on the requirement, a new element can be added at the beginning, end, or any given index of array. `append()` is also used to add the value mentioned in its arguments at the end of the array.\n", 42 | "\n", 43 | "```python\n", 44 | "# importing \"array\" for array creations \n", 45 | "import array as arr \n", 46 | " \n", 47 | "# array with int type \n", 48 | "a = arr.array('i', [1, 2, 3]) \n", 49 | "# prints 1 2 3\n", 50 | " \n", 51 | "# inserting array using insert() function \n", 52 | "a.insert(1, 4) # inserts 4 at index 1;\n", 53 | "# prints 1 4 2 3\n", 54 | "\n", 55 | "```\n", 56 | "\n", 57 | "### Removing Elements from the Array\n", 58 | "Elements can be removed from the array by using built-in `remove()` function but an Error arises if element doesn’t exist in the set. Remove() method only removes one element at a time, to remove range of elements, iterator is used. pop() function can also be used to remove and return an element from the array, but by default it removes only the last element of the array, to remove element from a specific position of the array, index of the element is passed as an argument to the pop() method.\n", 59 | "\n", 60 | "**Note** – Remove method in List will only remove the first occurrence of the searched element.\n", 61 | "\n", 62 | "```python \n", 63 | "# importing \"array\" for array operations \n", 64 | "import array \n", 65 | " \n", 66 | "# initializing array with array values \n", 67 | "# initializes array with signed integers \n", 68 | "arr = array.array('i', [1, 2, 3, 1, 5]) \n", 69 | " \n", 70 | "print (\"\\r\") \n", 71 | " \n", 72 | "# using pop() to remove element at 2nd position \n", 73 | "print (\"The popped element is : \", end =\"\") \n", 74 | "print (arr.pop(2)) \n", 75 | " \n", 76 | "# using remove() to remove 1st occurrence of 1 \n", 77 | "arr.remove(1) \n", 78 | "```\n", 79 | "\n", 80 | "### Slicing of a Array\n", 81 | "\n", 82 | "In Python array, there are multiple ways to print the whole array with all the elements, but to print a specific range of elements from the array, we use Slice operation. Slice operation is performed on array with the use of colon`(:)`. To print elements from beginning to a range use `[:Index]`, to print elements from end use [:-Index], to print elements from specific Index till the end use `[Index:]`, to print elements within a range, use `[Start Index:End Index]` and to print whole List with the use of slicing operation, use `[:]`. Further, to print whole array in reverse order, use `[::-1]`.\n", 83 | "\n", 84 | "```python\n", 85 | "# importing array module \n", 86 | "import array as arr \n", 87 | " \n", 88 | "# creating a list \n", 89 | "l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] \n", 90 | " \n", 91 | "# Print elements of a range using Slice operation \n", 92 | "Sliced_array = a[3:8] \n", 93 | "print(\"\\nSlicing elements in a range 3-8: \") \n", 94 | "print(Sliced_array) \n", 95 | " \n", 96 | "# Print elements from a pre-defined point to end \n", 97 | "Sliced_array = a[5:] \n", 98 | "print(\"\\nElements sliced from 5th \"\n", 99 | " \"element till the end: \") \n", 100 | "print(Sliced_array) \n", 101 | " \n", 102 | "# Printing elements from beginning till end \n", 103 | "Sliced_array = a[:] \n", 104 | "print(\"\\nPrinting all elements using slice operation: \") \n", 105 | "print(Sliced_array)\n", 106 | "```\n", 107 | "\n", 108 | "### Searching element in a Array\n", 109 | "In order to search an element in the array we use a python in-built `index()` method. This function returns the index of the first occurrence of value mentioned in arguments.\n", 110 | "\n", 111 | "```python\n", 112 | " \n", 113 | "# importing array module \n", 114 | "import array \n", 115 | " \n", 116 | "# initializing array with array values \n", 117 | "# initializes array with signed integers \n", 118 | "arr = array.array('i', [1, 2, 3, 1, 2, 5]) \n", 119 | " \n", 120 | "# using index() to print index of 1st occurrenece of 2 \n", 121 | "print (\"The index of 1st occurrence of 2 is : \", end =\"\") \n", 122 | "print (arr.index(2)) \n", 123 | " \n", 124 | "# using index() to print index of 1st occurrenece of 1 \n", 125 | "print (\"The index of 1st occurrence of 1 is : \", end =\"\") \n", 126 | "print (arr.index(1)) \n", 127 | "```" 128 | ] 129 | }, 130 | { 131 | "cell_type": "markdown", 132 | "metadata": {}, 133 | "source": [ 134 | "### Q1. Python program to\n", 135 | "\n", 136 | "1. Read an array and display\n", 137 | "\n", 138 | "2. Append a new item to the end of the array.\n", 139 | "\n", 140 | "3. To reverse the order of the items in the array (slice operator)\n", 141 | "\n", 142 | "4. Get the length in bytes of one array item\n", 143 | "\n", 144 | "5. To append items from another array\n", 145 | "\n", 146 | "6. Remove a specified item using the index from an array\n", 147 | "\n", 148 | "7. Insert a specified item at the specified position in the array\n", 149 | "\n", 150 | "8. Convert the array into a string\n" 151 | ] 152 | }, 153 | { 154 | "cell_type": "markdown", 155 | "metadata": {}, 156 | "source": [ 157 | "#### 1. Read an array and display - Method 1" 158 | ] 159 | }, 160 | { 161 | "cell_type": "code", 162 | "execution_count": 1, 163 | "metadata": {}, 164 | "outputs": [ 165 | { 166 | "name": "stdout", 167 | "output_type": "stream", 168 | "text": [ 169 | "Enter number of elements: 5\n", 170 | "Enter element 1: 1\n", 171 | "Enter element 2: 2\n", 172 | "Enter element 3: 3\n", 173 | "Enter element 4: 4\n", 174 | "Enter element 5: 5\n", 175 | "The entered list is: 1 2 3 4 5 " 176 | ] 177 | } 178 | ], 179 | "source": [ 180 | "# READ AN ARRAY AND DISPLAY\n", 181 | "\n", 182 | "import array as arr\n", 183 | "a = arr.array('i', [])\n", 184 | " \n", 185 | "n = int(input(\"Enter number of elements: \")) \n", 186 | " \n", 187 | "# iterating till the range \n", 188 | "for i in range(n): \n", 189 | " ele = int(input(f\"Enter element {i + 1}: \")) \n", 190 | " a.append(ele) # adding the element \n", 191 | " \n", 192 | "print(\"The entered list is:\", end=\" \")\n", 193 | "for i in range (n): \n", 194 | " print(a[i], end =\" \")" 195 | ] 196 | }, 197 | { 198 | "cell_type": "markdown", 199 | "metadata": {}, 200 | "source": [ 201 | "#### 1. Read an array and display - Method 2" 202 | ] 203 | }, 204 | { 205 | "cell_type": "code", 206 | "execution_count": 2, 207 | "metadata": {}, 208 | "outputs": [ 209 | { 210 | "name": "stdout", 211 | "output_type": "stream", 212 | "text": [ 213 | "Enter number of elements: 5\n", 214 | "Enter 5 numbers in a single line with spaces in between: 1 2 3 4 5\n", 215 | "1 2 3 4 5 " 216 | ] 217 | } 218 | ], 219 | "source": [ 220 | "# READ AN ARRAY AND DISPLAY\n", 221 | "\n", 222 | "import array as arr\n", 223 | " \n", 224 | "n = int(input(\"Enter number of elements: \")) \n", 225 | "\n", 226 | "nums = map(int, input(f\"Enter {n} numbers in a single line with spaces in between: \").split())\n", 227 | "\n", 228 | "a = arr.array('i', nums)\n", 229 | "\n", 230 | "for i in range (n): \n", 231 | " print(a[i], end =\" \")" 232 | ] 233 | }, 234 | { 235 | "cell_type": "markdown", 236 | "metadata": {}, 237 | "source": [ 238 | "#### 2. Append a new item to the end of the array." 239 | ] 240 | }, 241 | { 242 | "cell_type": "code", 243 | "execution_count": 3, 244 | "metadata": {}, 245 | "outputs": [ 246 | { 247 | "name": "stdout", 248 | "output_type": "stream", 249 | "text": [ 250 | "Enter an item to be appended: 6\n", 251 | "1 2 3 4 5 6 " 252 | ] 253 | } 254 | ], 255 | "source": [ 256 | "item = int(input(\"Enter an item to be appended: \"))\n", 257 | "a.append(item)\n", 258 | "# Final Array\n", 259 | "for it in a: \n", 260 | " print(it, end =\" \")" 261 | ] 262 | }, 263 | { 264 | "cell_type": "markdown", 265 | "metadata": {}, 266 | "source": [ 267 | "#### 3. To reverse the order of the items in the array (slice operator)" 268 | ] 269 | }, 270 | { 271 | "cell_type": "code", 272 | "execution_count": 4, 273 | "metadata": {}, 274 | "outputs": [ 275 | { 276 | "name": "stdout", 277 | "output_type": "stream", 278 | "text": [ 279 | "6 5 4 3 2 1 " 280 | ] 281 | } 282 | ], 283 | "source": [ 284 | "# reversed Array\n", 285 | "for it in a[::-1]: \n", 286 | " print(it, end =\" \")" 287 | ] 288 | }, 289 | { 290 | "cell_type": "markdown", 291 | "metadata": {}, 292 | "source": [ 293 | "#### 4. Get the length in bytes of one array item" 294 | ] 295 | }, 296 | { 297 | "cell_type": "code", 298 | "execution_count": 5, 299 | "metadata": {}, 300 | "outputs": [ 301 | { 302 | "name": "stdout", 303 | "output_type": "stream", 304 | "text": [ 305 | "Length in bytes of one array item: 4\n" 306 | ] 307 | } 308 | ], 309 | "source": [ 310 | "print(\"Length in bytes of one array item: \"+str(a.itemsize))" 311 | ] 312 | }, 313 | { 314 | "cell_type": "markdown", 315 | "metadata": {}, 316 | "source": [ 317 | "#### 5. To append items from another array" 318 | ] 319 | }, 320 | { 321 | "cell_type": "code", 322 | "execution_count": 6, 323 | "metadata": {}, 324 | "outputs": [ 325 | { 326 | "name": "stdout", 327 | "output_type": "stream", 328 | "text": [ 329 | "array('i', [1, 2, 3, 4, 5, 6, 9])\n" 330 | ] 331 | } 332 | ], 333 | "source": [ 334 | "import array as arr\n", 335 | "b = arr.array('i', [7, 8, 9])\n", 336 | "a.append(b[2])\n", 337 | "print(a)" 338 | ] 339 | }, 340 | { 341 | "cell_type": "markdown", 342 | "metadata": {}, 343 | "source": [ 344 | "#### 6. Remove a specified item using the index from an array" 345 | ] 346 | }, 347 | { 348 | "cell_type": "code", 349 | "execution_count": 7, 350 | "metadata": {}, 351 | "outputs": [ 352 | { 353 | "name": "stdout", 354 | "output_type": "stream", 355 | "text": [ 356 | "array('i', [1, 2, 4, 5, 6, 9])\n" 357 | ] 358 | } 359 | ], 360 | "source": [ 361 | "c = a\n", 362 | "del c[2]\n", 363 | "print(c)" 364 | ] 365 | }, 366 | { 367 | "cell_type": "markdown", 368 | "metadata": {}, 369 | "source": [ 370 | "#### 7. Insert a specified item at the specified position in the array" 371 | ] 372 | }, 373 | { 374 | "cell_type": "code", 375 | "execution_count": 8, 376 | "metadata": {}, 377 | "outputs": [ 378 | { 379 | "name": "stdout", 380 | "output_type": "stream", 381 | "text": [ 382 | "Enter an item to be appended: 100\n", 383 | "Enter the position where 100 is to be appended: 2\n", 384 | "array('i', [1, 2, 100, 4, 5, 6, 9])\n" 385 | ] 386 | } 387 | ], 388 | "source": [ 389 | "item = int(input(\"Enter an item to be appended: \"))\n", 390 | "pos = int(input(f\"Enter the position where {item} is to be appended: \"))\n", 391 | "a.insert(pos, item)\n", 392 | "print(a)" 393 | ] 394 | }, 395 | { 396 | "cell_type": "markdown", 397 | "metadata": {}, 398 | "source": [ 399 | "#### 8. Convert the array into a string - Method 1" 400 | ] 401 | }, 402 | { 403 | "cell_type": "code", 404 | "execution_count": 9, 405 | "metadata": {}, 406 | "outputs": [ 407 | { 408 | "name": "stdout", 409 | "output_type": "stream", 410 | "text": [ 411 | "1 2 100 4 5 6 9\n" 412 | ] 413 | } 414 | ], 415 | "source": [ 416 | "print(' '.join(str(i) for i in a))" 417 | ] 418 | }, 419 | { 420 | "cell_type": "markdown", 421 | "metadata": {}, 422 | "source": [ 423 | "#### 8. Convert the array into a string - Method 2" 424 | ] 425 | }, 426 | { 427 | "cell_type": "code", 428 | "execution_count": 10, 429 | "metadata": {}, 430 | "outputs": [ 431 | { 432 | "name": "stdout", 433 | "output_type": "stream", 434 | "text": [ 435 | "1 2 100 4 5 6 9\n" 436 | ] 437 | } 438 | ], 439 | "source": [ 440 | "print(' '.join(map(str, a)))" 441 | ] 442 | }, 443 | { 444 | "cell_type": "markdown", 445 | "metadata": {}, 446 | "source": [ 447 | "## Q2. Python program to remove prime numbers from an array.\n", 448 | "`Sampleinput arr[]={3,4,6,9,13,14,16,17}`\n", 449 | "\n", 450 | "`Outputarr[]={4,6,9,14,16}`" 451 | ] 452 | }, 453 | { 454 | "cell_type": "code", 455 | "execution_count": 11, 456 | "metadata": {}, 457 | "outputs": [ 458 | { 459 | "name": "stdout", 460 | "output_type": "stream", 461 | "text": [ 462 | "Enter number of elements: 8\n", 463 | "Enter 8 numbers in a single line with spaces in between: 3 4 5 6 9 13 14 16 17\n", 464 | "Array after removing primes: array('i', [4, 6, 9, 14, 16])\n" 465 | ] 466 | } 467 | ], 468 | "source": [ 469 | "import array as arr\n", 470 | " \n", 471 | "n = int(input(\"Enter number of elements: \")) \n", 472 | "\n", 473 | "nums = map(int, input(f\"Enter {n} numbers in a single line with spaces in between: \").split())\n", 474 | "\n", 475 | "a = arr.array('i', nums)\n", 476 | "\n", 477 | "print(\"Array after removing primes:\", end=\" \")\n", 478 | "\n", 479 | "b = arr.array('i', [])\n", 480 | "for s in a:\n", 481 | " for i in range(2, s):\n", 482 | " if(s % i==0):\n", 483 | " break;\n", 484 | " if(i==s-1):\n", 485 | " b.append(s)\n", 486 | "for ss in b:\n", 487 | " while ss in a:\n", 488 | " a.remove(ss)\n", 489 | "\n", 490 | "print(a)" 491 | ] 492 | }, 493 | { 494 | "cell_type": "markdown", 495 | "metadata": {}, 496 | "source": [ 497 | "# *Python String*\n", 498 | "\n", 499 | "In Python, Strings are arrays of bytes representing Unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string.\n", 500 | "\n", 501 | "### Creating a String\n", 502 | "Strings in Python can be created using single quotes or double quotes or even triple quotes.\n", 503 | "\n", 504 | "```python\n", 505 | "# Creating a String \n", 506 | "# with single Quotes \n", 507 | "String1 = 'Welcome to the Geeks World'\n", 508 | " \n", 509 | "# Creating a String \n", 510 | "# with double Quotes \n", 511 | "String1 = \"I'm a Geek\"\n", 512 | " \n", 513 | "# Creating a String \n", 514 | "# with triple Quotes \n", 515 | "String1 = '''I'm a Geek and I live in a world of \"Geeks\"'''\n", 516 | " \n", 517 | "# Creating String with triple \n", 518 | "# Quotes allows multiple lines \n", 519 | "String1 = '''Geeks \n", 520 | " For \n", 521 | " Life'''\n", 522 | "```\n", 523 | "\n", 524 | "Accessing characters in Python\n", 525 | "In Python, individual characters of a String can be accessed by using the method of Indexing. Indexing allows negative address references to access characters from the back of the String, \n", 526 | "\n", 527 | "e.g. -1 refers to the last character, -2 refers to the second last character and so on.\n", 528 | "\n", 529 | "\n", 530 | "While accessing an index out of the range will cause an IndexError. Only Integers are allowed to be passed as an index, float or other types will cause a TypeError.\n", 531 | "\n", 532 | "### String Slicing\n", 533 | "To access a range of characters in the String, method of slicing is used. Slicing in a String is done by using a Slicing operator (colon).\n", 534 | "\n", 535 | "```python \n", 536 | "# Creating a String \n", 537 | "String1 = \"TEST STRING\"\n", 538 | "print(\"Initial String: \") \n", 539 | "print(String1) \n", 540 | " \n", 541 | "# Printing 3rd to 12th character \n", 542 | "print(String1[3:12]) \n", 543 | " \n", 544 | "# Printing characters between \n", 545 | "# 3rd and 2nd last character \n", 546 | "print(String1[3:-2]) \n", 547 | "```\n", 548 | "\n", 549 | "### Deleting/Updating from a String\n", 550 | "\n", 551 | "#### Strings are immutable\n", 552 | "\n", 553 | "In Python, Updation or deletion of characters from a String is not allowed. This will cause an error because item assignment or item deletion from a String is not supported. Although deletion of entire String is possible with the use of a built-in del keyword. This is because Strings are immutable, hence elements of a String cannot be changed once it has been assigned. Only new strings can be reassigned to the same name." 554 | ] 555 | }, 556 | { 557 | "cell_type": "markdown", 558 | "metadata": {}, 559 | "source": [ 560 | "## Q3. Python program to change all occurrences of a first character of a string to @ except for first occurrence. \n", 561 | "\n", 562 | "Sample String : 'apple a day'\n", 563 | "\n", 564 | "Expected Result : 'apple @ d@y'" 565 | ] 566 | }, 567 | { 568 | "cell_type": "code", 569 | "execution_count": 12, 570 | "metadata": {}, 571 | "outputs": [ 572 | { 573 | "name": "stdout", 574 | "output_type": "stream", 575 | "text": [ 576 | "an apple a day, keeps the doctor away\n", 577 | "an @pple @ d@y, keeps the doctor @w@y\n" 578 | ] 579 | } 580 | ], 581 | "source": [ 582 | "inp = input()\n", 583 | "ans = \"\"\n", 584 | "cnt = 0\n", 585 | "for ch in inp:\n", 586 | " if(ch == 'a'):\n", 587 | " cnt += 1\n", 588 | " if(cnt > 1):\n", 589 | " ans += '@'\n", 590 | " else:\n", 591 | " ans += ch\n", 592 | " else:\n", 593 | " ans += ch\n", 594 | "print(ans)" 595 | ] 596 | }, 597 | { 598 | "cell_type": "markdown", 599 | "metadata": {}, 600 | "source": [ 601 | "## Q4. Python Program to sort group of strings into alphabetical order" 602 | ] 603 | }, 604 | { 605 | "cell_type": "code", 606 | "execution_count": 13, 607 | "metadata": {}, 608 | "outputs": [ 609 | { 610 | "name": "stdout", 611 | "output_type": "stream", 612 | "text": [ 613 | "Enter a string: Python Program to sort group of strings into alphabetical order\n", 614 | "alphabetical\n", 615 | "group\n", 616 | "into\n", 617 | "of\n", 618 | "order\n", 619 | "program\n", 620 | "python\n", 621 | "sort\n", 622 | "strings\n", 623 | "to\n" 624 | ] 625 | } 626 | ], 627 | "source": [ 628 | "my_str = input(\"Enter a string: \") \n", 629 | "\n", 630 | "# breakdown the string into a list of words \n", 631 | "words = [word.lower() for word in my_str.split()]\n", 632 | "\n", 633 | "# sort the list \n", 634 | "words.sort() \n", 635 | "# display the sorted words \n", 636 | "for word in words: \n", 637 | " print(word)" 638 | ] 639 | }, 640 | { 641 | "cell_type": "markdown", 642 | "metadata": {}, 643 | "source": [ 644 | "## Q4. Python Program to check whether entered string is palindrome or not" 645 | ] 646 | }, 647 | { 648 | "cell_type": "code", 649 | "execution_count": 14, 650 | "metadata": {}, 651 | "outputs": [ 652 | { 653 | "name": "stdout", 654 | "output_type": "stream", 655 | "text": [ 656 | "Enter a string: malayalam\n", 657 | "malayalam is palindrome.\n" 658 | ] 659 | } 660 | ], 661 | "source": [ 662 | "my_str = input(\"Enter a string: \") \n", 663 | "n = len(my_str)\n", 664 | "# breakdown the string into a list of words \n", 665 | "\n", 666 | "if my_str[::-1] == my_str:\n", 667 | " print(my_str + \" is palindrome.\")\n", 668 | "else:\n", 669 | " print(my_str + \" is not palindrome.\")" 670 | ] 671 | } 672 | ], 673 | "metadata": { 674 | "kernelspec": { 675 | "display_name": "Python 3", 676 | "language": "python", 677 | "name": "python3" 678 | }, 679 | "language_info": { 680 | "codemirror_mode": { 681 | "name": "ipython", 682 | "version": 3 683 | }, 684 | "file_extension": ".py", 685 | "mimetype": "text/x-python", 686 | "name": "python", 687 | "nbconvert_exporter": "python", 688 | "pygments_lexer": "ipython3", 689 | "version": "3.7.6" 690 | } 691 | }, 692 | "nbformat": 4, 693 | "nbformat_minor": 4 694 | } 695 | -------------------------------------------------------------------------------- /Python/experiment_03.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Experiment No. 3" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "## *Functions in Python*\n", 15 | "\n", 16 | "Functions is a group of statements that are intended to perform a specific task.\n", 17 | "\n", 18 | "#### Defining a Function\n", 19 | "Keyword def that marks the start of the function header.\n", 20 | "A function name to uniquely identify the function. Function naming follows the same rules of writing identifiers in Python.\n", 21 | "**Parameters** (arguments) through which we pass values to a function. They are optional.\n", 22 | "\n", 23 | "**A colon (:)** to mark the end of the function header.\n", 24 | "\n", 25 | "Optional documentation string (docstring) to describe what the function does.\n", 26 | "One or more valid python statements that make up the function body. Statements must have the same indentation level (usually 4 spaces).\n", 27 | "\n", 28 | "### Syntax\n", 29 | "\n", 30 | "```python\n", 31 | "def function_name(parameters):\n", 32 | "\n", 33 | "\"\"\"docstring\"\"\"\n", 34 | "\n", 35 | "statement(s)\n", 36 | "```\n", 37 | "\n", 38 | "**Advantages**\n", 39 | "\n", 40 | "- Reusability\n", 41 | "- Modularity\n", 42 | "- Code Maintenance\n", 43 | "- Code Debugging\n", 44 | "- Reduces length of code\n", 45 | "\n", 46 | "\n", 47 | "### **Calling a Function**\n", 48 | "\n", 49 | "Once we have defined a function, we can call it from another function, program or even the Python prompt. To call a function we simply type the function name with appropriate parameters.\n", 50 | "\n", 51 | "\n", 52 | "\n", 53 | "- sum(10,15)\n", 54 | "- sum(10.3,21.4)\n", 55 | "\n", 56 | "- The parameters a and b do not know which type of values they are going toreceive till the values are passed at the time of calling the function.\n", 57 | "\n", 58 | "- This is Dynamic Typing, where type of data is determined only at runtime, not at compile time." 59 | ] 60 | }, 61 | { 62 | "cell_type": "markdown", 63 | "metadata": {}, 64 | "source": [ 65 | "# **Question 1:**\n", 66 | "**Write a Python function to check whether a number is perfect or not.(Note : The first perfect number is 6, because 1, 2, and 3 are its proper positive divisors, and 1 + 2 + 3 = 6. Equivalently, the number 6 is equal to half the sum of all its positive divisors: ( 1 + 2 + 3 + 6 ) / 2 = 6. The next perfect number is 28 = 1 +2 + 4 + 7 + 14. This is followed by the perfect numbers 496 and 8128.)**" 67 | ] 68 | }, 69 | { 70 | "cell_type": "code", 71 | "execution_count": 1, 72 | "metadata": {}, 73 | "outputs": [ 74 | { 75 | "name": "stdout", 76 | "output_type": "stream", 77 | "text": [ 78 | "Enter a number to check if it is a perfect number or not: 496\n", 79 | "The number 496 is perfect\n" 80 | ] 81 | } 82 | ], 83 | "source": [ 84 | "def checkperfectnum(num):\n", 85 | " sum = 0;\n", 86 | " for i in range (1,num):\n", 87 | " if num % i==0:\n", 88 | " sum += i\n", 89 | " if sum == num:\n", 90 | " print(\"The number {} is perfect\".format(num))\n", 91 | " \n", 92 | "n = int(input(\"Enter a number to check if it is a perfect number or not: \"))\n", 93 | "checkperfectnum(n)\n" 94 | ] 95 | }, 96 | { 97 | "cell_type": "markdown", 98 | "metadata": {}, 99 | "source": [ 100 | "# **Question 2**\n", 101 | "**Write a Python function to check whether a string is a pangram or not. (Note : Pangrams are words or sentences containing every letter of the alphabet at least once.For example : \"The quick brown fox jumps over the lazy dog\")**" 102 | ] 103 | }, 104 | { 105 | "cell_type": "code", 106 | "execution_count": 3, 107 | "metadata": {}, 108 | "outputs": [ 109 | { 110 | "name": "stdout", 111 | "output_type": "stream", 112 | "text": [ 113 | "enter text: The quick brown fox jumps over the lazy dog\n", 114 | "the text is pangram\n" 115 | ] 116 | } 117 | ], 118 | "source": [ 119 | "import string \n", 120 | "def ispangram(str): \n", 121 | " alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n", 122 | " for char in alphabet: \n", 123 | " if char not in str.lower(): \n", 124 | " return False\n", 125 | " return True\n", 126 | "string=input(\"enter text: \")\n", 127 | "if(ispangram(string) == True): \n", 128 | " print(\"the text is pangram\") \n", 129 | "else: \n", 130 | " print(\"the text is not pangram\") " 131 | ] 132 | }, 133 | { 134 | "cell_type": "markdown", 135 | "metadata": {}, 136 | "source": [ 137 | "## Variable length arguments\n", 138 | "Up until now, functions had a fixed number of arguments. In Python, there are other ways to define a function that can take variable number of arguments.\n", 139 | "\n", 140 | "Sometimes, we do not know in advance the number of arguments that will be passed into a function. Python allows us to handle this kind of situation through function calls with an **arbitrary number of arguments.**\n", 141 | "\n", 142 | "In the function definition, we use an asterisk (*) before the parameter name to denote it as variable length argument.\n", 143 | "\n", 144 | "Syntax:\n", 145 | "\n", 146 | "*def func(farg, *args):*\n", 147 | "\n", 148 | "When, we make a function call with multiple arguments, these arguments get wrapped up into a tuple before being passed into the function." 149 | ] 150 | }, 151 | { 152 | "cell_type": "markdown", 153 | "metadata": {}, 154 | "source": [ 155 | "# **Question 3**\n", 156 | "**Python menu driven program to develop simple calculator using variable length argument**" 157 | ] 158 | }, 159 | { 160 | "cell_type": "code", 161 | "execution_count": 4, 162 | "metadata": {}, 163 | "outputs": [ 164 | { 165 | "name": "stdout", 166 | "output_type": "stream", 167 | "text": [ 168 | "Enter a list of nos: 4 5 9 8\n", 169 | "enter choice: \n", 170 | " 1. addition(+)\n", 171 | " 2. sub(-)\n", 172 | " 3. multi(*)\n", 173 | " 4. div (/)\n", 174 | " 5. exit\n", 175 | " 1\n", 176 | "Result = 26\n", 177 | "enter choice: \n", 178 | " 1. addition(+)\n", 179 | " 2. sub(-)\n", 180 | " 3. multi(*)\n", 181 | " 4. div (/)\n", 182 | " 5. exit\n", 183 | " 2\n", 184 | "Result = -18\n", 185 | "enter choice: \n", 186 | " 1. addition(+)\n", 187 | " 2. sub(-)\n", 188 | " 3. multi(*)\n", 189 | " 4. div (/)\n", 190 | " 5. exit\n", 191 | " 3\n", 192 | "Result = 1440\n", 193 | "enter choice: \n", 194 | " 1. addition(+)\n", 195 | " 2. sub(-)\n", 196 | " 3. multi(*)\n", 197 | " 4. div (/)\n", 198 | " 5. exit\n", 199 | " 4\n", 200 | "Result = 0.06944444444444445\n", 201 | "enter choice: \n", 202 | " 1. addition(+)\n", 203 | " 2. sub(-)\n", 204 | " 3. multi(*)\n", 205 | " 4. div (/)\n", 206 | " 5. exit\n", 207 | " 5\n" 208 | ] 209 | } 210 | ], 211 | "source": [ 212 | "def add(*n2):\n", 213 | " '''Add all the given numbers'''\n", 214 | " res = n2[0]\n", 215 | " for i in range(1,len(n2)):\n", 216 | " res += n2[i]\n", 217 | " print('Result =',res)\n", 218 | "\n", 219 | "def sub(*n2):\n", 220 | " '''Subtract all the given numbers'''\n", 221 | " res = n2[0]\n", 222 | " for i in range(1,len(n2)):\n", 223 | " res -= n2[i]\n", 224 | " print('Result =',res)\n", 225 | "\n", 226 | "def pro(*n2):\n", 227 | " '''Product all the given numbers'''\n", 228 | " res = n2[0]\n", 229 | " for i in range(1,len(n2)):\n", 230 | " res *= n2[i]\n", 231 | " print('Result =',res)\n", 232 | "\n", 233 | "def div(n1, *n2):\n", 234 | " '''Divide all the given numbers'''\n", 235 | " res = n2[0]\n", 236 | " for i in range(1,len(n2)):\n", 237 | " res /= n2[i]\n", 238 | " print('Result = ',res)\n", 239 | "\n", 240 | "def calculator():\n", 241 | " x = list(map(int, input(\"Enter a list of nos: \").split()))\n", 242 | " \n", 243 | " while True:\n", 244 | " ch=input('''enter choice: \n", 245 | " 1. addition(+)\n", 246 | " 2. sub(-)\n", 247 | " 3. multi(*)\n", 248 | " 4. div (/)\n", 249 | " 5. exit\n", 250 | " ''')\n", 251 | " if ch=='1':\n", 252 | " add(*x)\n", 253 | " elif ch=='2':\n", 254 | " sub(*x)\n", 255 | " elif ch=='3':\n", 256 | " pro(*x)\n", 257 | " elif ch=='4':\n", 258 | " div(*x)\n", 259 | " else:\n", 260 | " break\n", 261 | " \n", 262 | "calculator()" 263 | ] 264 | }, 265 | { 266 | "cell_type": "markdown", 267 | "metadata": {}, 268 | "source": [ 269 | "## **What is recursion?**\n", 270 | "\n", 271 | "Recursion is the process of defining something in terms of itself.\n", 272 | "A physical world example would be to place two parallel mirrors facing each other. Any object in between them would be reflected recursively.\n", 273 | "\n", 274 | "In Python, we know that a function can call other functions. It is even possible for the function to call itself. These types of construct are termed as recursive functions. Factorial of a number is the product of all the integers from 1 to that number. For example, the factorial of 6 (denoted as 6!) is 12345*6 = 720.\n", 275 | "\n", 276 | "**Advantages of Recursion**\n", 277 | "\n", 278 | "- Recursive functions make the code look clean and elegant.\n", 279 | "- A complex task can be broken down into simpler sub-problems using recursion.\n", 280 | "- Sequence generation is easier with recursion than using some nested iteration.\n", 281 | "\n", 282 | "**Disadvantages of Recursion**\n", 283 | "\n", 284 | "- Sometimes the logic behind recursion is hard to follow through.\n", 285 | "- Recursive calls are expensive (inefficient) as they take up a lot of memory and time.\n", 286 | "- Recursive functions are hard to debug." 287 | ] 288 | }, 289 | { 290 | "cell_type": "markdown", 291 | "metadata": {}, 292 | "source": [ 293 | "# **Question 4**\n", 294 | "**Program to calculate factorial of a number using recursion**" 295 | ] 296 | }, 297 | { 298 | "cell_type": "code", 299 | "execution_count": 5, 300 | "metadata": {}, 301 | "outputs": [ 302 | { 303 | "name": "stdout", 304 | "output_type": "stream", 305 | "text": [ 306 | "enter number: 20\n", 307 | "The factorial of 20 is 2432902008176640000\n" 308 | ] 309 | } 310 | ], 311 | "source": [ 312 | "def recur_factorial(n):\n", 313 | " if n == 1:\n", 314 | " return n\n", 315 | " else:\n", 316 | " return n*recur_factorial(n-1)\n", 317 | "\n", 318 | "num=int(input(\"enter number: \"))\n", 319 | "if num < 0:\n", 320 | " print(\"Sorry, factorial does not exist for negative numbers\")\n", 321 | "elif num == 0:\n", 322 | " print(\"The factorial of 0 is 1\")\n", 323 | "else:\n", 324 | " print(\"The factorial of\", num, \"is\", recur_factorial(num))" 325 | ] 326 | }, 327 | { 328 | "cell_type": "markdown", 329 | "metadata": {}, 330 | "source": [ 331 | "## *Decorators in Python*\n", 332 | "**Function Decorators**\n", 333 | "\n", 334 | "- Python has an interesting feature called decorators to add functionality to an existing code.\n", 335 | "\n", 336 | "- This is also called metaprogramming because a part of the program tries to modify another part of the program at compile time.\n", 337 | "\n", 338 | "- Decorators are like gift wrappers.\n", 339 | "\n", 340 | "- If you want to extend the behavior of a function but don’t want to modify it permanently, you can wrap a decorator on it.\n", 341 | "\n", 342 | "- A decorator is a function that accepts a function as parameter and returns a function.\n", 343 | "\n", 344 | "- A decorator takes the result of a function, modifies the result and returns it.\n", 345 | "\n", 346 | "- Thus, decorators are useful to perform some additional processing required by a function.\n", 347 | "\n", 348 | "**Creating Decorator**\n", 349 | "\n", 350 | "Decorators are nested functions. The outer function takes the function to decorate as an argument and then the inner function calls it.\n", 351 | "\n", 352 | "**Accepting Arguments in Decorator Functions**\n", 353 | "\n", 354 | "Sometimes, there is a need to define a decorator that accepts arguments.\n", 355 | "\n", 356 | "This can be achieved by passing the arguments to the inner function.\n", 357 | "\n", 358 | "The arguments will then be passed to the function that is being decorated at call time.\n", 359 | "\n", 360 | "\n", 361 | "Example\n", 362 | "\n", 363 | "```python\n", 364 | "#Example - Decorator that increments the value of a number by 2\n", 365 | "def decor(func): #name of the decorator funtion\n", 366 | " def inner(): # This function actually modifies or decorates the value.\n", 367 | " value = func() # access the value return by func\n", 368 | " return value+2 # increase value by 2\n", 369 | " return inner # return the inner function that has processed or decorated the value.\n", 370 | "```\n", 371 | "\n", 372 | "```python\n", 373 | "def num():\n", 374 | " return 10\n", 375 | "res = decor(num)\n", 376 | "print(res())\n", 377 | "```\n", 378 | "\n", 379 | "\n", 380 | "```python\n", 381 | "@decor # apply decorator to the following function\n", 382 | "def num1():\n", 383 | " return 100\n", 384 | "\n", 385 | "print(num1())\n", 386 | "```" 387 | ] 388 | }, 389 | { 390 | "cell_type": "markdown", 391 | "metadata": {}, 392 | "source": [ 393 | "# **Question 5**\n", 394 | "**Python program to calculate square and cube of a number and use two decorators, one to increase result by 4 and another to multiply result by 2.**" 395 | ] 396 | }, 397 | { 398 | "cell_type": "code", 399 | "execution_count": 6, 400 | "metadata": {}, 401 | "outputs": [ 402 | { 403 | "name": "stdout", 404 | "output_type": "stream", 405 | "text": [ 406 | "enter number: 12\n", 407 | "square using decorator and adding four: 148\n", 408 | "square using decorator and multiply by two: 288\n", 409 | "cube using decorator and adding four: 1732\n", 410 | "cube using decorator and multiply by two: 3456\n" 411 | ] 412 | } 413 | ], 414 | "source": [ 415 | "def decor_increase(func): \n", 416 | " def inner1(arg1): \n", 417 | " value = func(arg1) \n", 418 | " return value+4 \n", 419 | " return inner1\n", 420 | "\n", 421 | "def decor_multiply(func): \n", 422 | " def inner2(arg2): \n", 423 | " value = func(arg2) \n", 424 | " return value*2\n", 425 | " return inner2\n", 426 | "\n", 427 | "\n", 428 | "def sqaure(x):\n", 429 | " return x*x\n", 430 | "def cube(x):\n", 431 | " return x*x*x\n", 432 | "n=int(input(\"enter number: \"))\n", 433 | "print(\"square using decorator and adding four:\" ,decor_increase(sqaure)(n))\n", 434 | "print(\"square using decorator and multiply by two:\" ,decor_multiply(sqaure)(n))\n", 435 | "print(\"cube using decorator and adding four:\" ,decor_increase(cube)(n))\n", 436 | "print(\"cube using decorator and multiply by two:\" ,decor_multiply(cube)(n))" 437 | ] 438 | }, 439 | { 440 | "cell_type": "markdown", 441 | "metadata": {}, 442 | "source": [ 443 | "## Modules in python\n", 444 | "\n", 445 | "**What is a Module?**\n", 446 | "\n", 447 | "Consider a module to be the same as a code library.\n", 448 | "\n", 449 | "A file containing a set of functions you want to include in your application.\n", 450 | "\n", 451 | "**Create a Module**\n", 452 | "\n", 453 | "To create a module just save the code you want in a file with the file extension .py:\n", 454 | "\n", 455 | "**Use a Module**\n", 456 | "\n", 457 | "Now we can use the module we just created, by using the import statement:\n", 458 | "\n", 459 | "**Built-in Modules** \n", 460 | "\n", 461 | "There are several built-in modules in Python, which you can import whenever you like.\n", 462 | "\n", 463 | "**Using the dir() Function**\n", 464 | "\n", 465 | "There is a built-in function to list all the function names (or variable names) in a module. The dir() function:\n", 466 | "\n", 467 | "**Import From Module**\n", 468 | "\n", 469 | "You can choose to import only parts from a module, by using the from keyword." 470 | ] 471 | }, 472 | { 473 | "cell_type": "markdown", 474 | "metadata": {}, 475 | "source": [ 476 | "#### `Q6.py`\n", 477 | "\n", 478 | "```python\n", 479 | "def addAll(nums):\n", 480 | " total = 0\n", 481 | " for num in nums:\n", 482 | " total += num\n", 483 | " print(\"\\nAddition is:\", total)\n", 484 | " \n", 485 | "def multiplyAll(nums):\n", 486 | " total = 1\n", 487 | " for num in nums:\n", 488 | " total *= num\n", 489 | " print(\"\\nProduct is:\", total)\n", 490 | " \n", 491 | "def addAllEven(nums):\n", 492 | " total = 0\n", 493 | " for i in range(0, len(nums), 2):\n", 494 | " total += nums[i]\n", 495 | " print(\"\\nAddition at even indices is:\", total)\n", 496 | " \n", 497 | "def insertItems(nums):\n", 498 | " num = int(input(\"Enter a number to be appended: \"))\n", 499 | " nums.append(num)\n", 500 | " print(\"\\nThe final list is:\", nums)\n", 501 | "```" 502 | ] 503 | }, 504 | { 505 | "cell_type": "code", 506 | "execution_count": 7, 507 | "metadata": {}, 508 | "outputs": [ 509 | { 510 | "name": "stdout", 511 | "output_type": "stream", 512 | "text": [ 513 | "Enter a list of nos: 1 2 3 4 5\n", 514 | "[1, 2, 3, 4, 5]\n", 515 | "\n", 516 | "1. Addition of all elements\n", 517 | "2. Product of all elements\n", 518 | "3. Addition of elements at even indices\n", 519 | "4. Append elements in the list\n", 520 | "5. Exit\n", 521 | "Enter the choice: 1\n", 522 | "\n", 523 | "Addition is: 15\n", 524 | "\n", 525 | "1. Addition of all elements\n", 526 | "2. Product of all elements\n", 527 | "3. Addition of elements at even indices\n", 528 | "4. Append elements in the list\n", 529 | "5. Exit\n", 530 | "Enter the choice: 2\n", 531 | "\n", 532 | "Product is: 120\n", 533 | "\n", 534 | "1. Addition of all elements\n", 535 | "2. Product of all elements\n", 536 | "3. Addition of elements at even indices\n", 537 | "4. Append elements in the list\n", 538 | "5. Exit\n", 539 | "Enter the choice: 3\n", 540 | "\n", 541 | "Addition at even indices is: 9\n", 542 | "\n", 543 | "1. Addition of all elements\n", 544 | "2. Product of all elements\n", 545 | "3. Addition of elements at even indices\n", 546 | "4. Append elements in the list\n", 547 | "5. Exit\n", 548 | "Enter the choice: 4\n", 549 | "Enter a number to be appended: 6\n", 550 | "\n", 551 | "The final list is: [1, 2, 3, 4, 5, 6]\n", 552 | "\n", 553 | "1. Addition of all elements\n", 554 | "2. Product of all elements\n", 555 | "3. Addition of elements at even indices\n", 556 | "4. Append elements in the list\n", 557 | "5. Exit\n", 558 | "Enter the choice: 5\n", 559 | "Exit!\n" 560 | ] 561 | } 562 | ], 563 | "source": [ 564 | "from Q6 import *\n", 565 | "\n", 566 | "nums = list(map(int, input(\"Enter a list of nos: \").split()))\n", 567 | "\n", 568 | "print(nums)\n", 569 | "while(1):\n", 570 | " print(\"\\n1. Addition of all elements\")\n", 571 | " print(\"2. Product of all elements\")\n", 572 | " print(\"3. Addition of elements at even indices\")\n", 573 | " print(\"4. Append elements in the list\")\n", 574 | " print(\"5. Exit\")\n", 575 | " choice = int(input(\"Enter the choice: \"))\n", 576 | " if choice == 1:\n", 577 | " addAll(nums)\n", 578 | " elif choice == 2:\n", 579 | " multiplyAll(nums)\n", 580 | " elif choice == 3:\n", 581 | " addAllEven(nums)\n", 582 | " elif choice == 4:\n", 583 | " insertItems(nums)\n", 584 | " else:\n", 585 | " print(\"Exit!\")\n", 586 | " break;" 587 | ] 588 | } 589 | ], 590 | "metadata": { 591 | "kernelspec": { 592 | "display_name": "Python 3", 593 | "language": "python", 594 | "name": "python3" 595 | }, 596 | "language_info": { 597 | "codemirror_mode": { 598 | "name": "ipython", 599 | "version": 3 600 | }, 601 | "file_extension": ".py", 602 | "mimetype": "text/x-python", 603 | "name": "python", 604 | "nbconvert_exporter": "python", 605 | "pygments_lexer": "ipython3", 606 | "version": "3.7.6" 607 | } 608 | }, 609 | "nbformat": 4, 610 | "nbformat_minor": 4 611 | } 612 | -------------------------------------------------------------------------------- /Python/experiment_08.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | from tkinter import messagebox, filedialog 3 | 4 | # Functions 5 | 6 | def save_file(): 7 | '''saves the file in a .txt format''' 8 | f = filedialog.asksaveasfile(mode='w', defaultextension=".txt") 9 | if f is None: # asksaveasfile return `None` if dialog closed with "cancel". 10 | return 11 | text2save = str(text.get(1.0, END)) 12 | f.write(text2save) 13 | f.close() 14 | 15 | # Shows info box if file saved; 16 | return messagebox.showinfo("Saved", "File Saved Successfully") 17 | 18 | def clear_file(): 19 | '''clears the input field ''' 20 | name_var.set("") 21 | text.delete(1.0, END) 22 | 23 | def print_in_cmd(): 24 | '''prints the file in terminal''' 25 | print("Title:", name_var.get()) 26 | 27 | print(str(text.get(1.0, END))) 28 | 29 | # Shows info box if file printed in the terminal; 30 | return messagebox.showinfo("Printed", "File Printed Successfully") 31 | 32 | def donothing(): 33 | pass 34 | 35 | 36 | # create root window 37 | root = Tk() 38 | # root window title and dimension 39 | root.title("Welcome to File Editor") 40 | # Set geometry (widthxheight) 41 | root.geometry('1200x550') 42 | 43 | name_var=StringVar() 44 | # creating a label for TITLE using widget Label 45 | Label(root, text = 'TITLE', font=('calibre',14, 'bold')).place(x=30, y=70) 46 | Entry(root, textvariable = name_var, font=('calibre',13,'normal')).place(x=30, y=110) 47 | 48 | # Text Input 49 | text=Text(root, x=30, y=40, padx = 10, pady = 10, wrap=WORD) 50 | text.pack() 51 | 52 | # adding a label to the root window 53 | lbl = Label(root, text = "File Editor") 54 | 55 | # Text to display where to enter text 56 | Label(root, text="Enter Text: ", font=('calibre', 15, 'bold')).place(x=180, y=220, anchor="center") 57 | 58 | 59 | # button widget with blue color text inside 60 | btn = Button(root, text = "Update", fg = "blue", command=save_file) 61 | btn.place(x = 350, y = 450) 62 | 63 | # button widget with blue color text inside 64 | btn = Button(root, text = "Print", fg = "blue", command=print_in_cmd) 65 | btn.place(x = 475, y = 450) 66 | 67 | # button widget with blue color text inside 68 | btn = Button(root, text = "Clear", fg = "blue", command=clear_file) 69 | btn.place(x = 600, y = 450) 70 | 71 | # button widget with blue color text inside 72 | btn = Button(root, text = "Delete", fg = "red", command=clear_file) 73 | btn.place(x = 725, y = 450) 74 | 75 | # menu bar at the top 76 | menubar=Menu(root) 77 | 78 | filemenu=Menu(menubar,tearoff=0) 79 | filemenu.add_command(label="New", command=clear_file) 80 | filemenu.add_command(label="Open", command=donothing) 81 | filemenu.add_command(label="Save", command=save_file) 82 | filemenu.add_command(label="Save as...", command=save_file) 83 | filemenu.add_separator() 84 | filemenu.add_command(label="Exit", command=root.quit) 85 | # Adding cascade 86 | menubar.add_cascade(label="File", menu=filemenu) 87 | 88 | 89 | editmenu=Menu(menubar,tearoff=0) 90 | editmenu.add_command(label="Undo", command=donothing) 91 | editmenu.add_command(label="Copy", command=donothing) 92 | editmenu.add_command(label="Paste", command=donothing) 93 | # Adding cascade 94 | menubar.add_cascade(label="Edit", menu=editmenu) 95 | 96 | 97 | helpmenu=Menu(menubar,tearoff=0) 98 | helpmenu.add_command(label="Help",command=donothing) 99 | # Adding cascade 100 | menubar.add_cascade(label="Help",menu=helpmenu) 101 | 102 | # configuring the root menu 103 | root.config(menu=menubar) 104 | 105 | # Execute Tkinter 106 | root.mainloop() -------------------------------------------------------------------------------- /Python/experiment_09.py: -------------------------------------------------------------------------------- 1 | # To create connection with MySQL Server 2 | from getpass import getpass 3 | from mysql.connector import connect, Error 4 | 5 | global_id = 1 6 | 7 | try: 8 | with connect( 9 | host="localhost", 10 | user=input("Enter username: "), 11 | password=getpass("Enter password: "), 12 | ) as connection: 13 | print(connection) 14 | except Error as e: 15 | print(e) 16 | 17 | 18 | 19 | import mysql.connector as m 20 | 21 | 22 | # creating connection 23 | conn = m.connect(user='python',password = 'python',host='localhost', database = "filedatabase") 24 | # create cursor object 25 | cursor = conn.cursor() 26 | 27 | 28 | 29 | def create_database(): 30 | # create new database 31 | create_db_query = "CREATE DATABASE filedatabase" 32 | 33 | # execute query 34 | cursor.execute(create_db_query) 35 | 36 | conn.commit() 37 | 38 | 39 | def create_database_table(): 40 | create_table_query = """ CREATE TABLE details ( 41 | id INT PRIMARY KEY, 42 | text VARCHAR(100))""" 43 | 44 | cursor.execute(create_table_query) 45 | 46 | conn.commit() 47 | 48 | def print_tables_in_database(): 49 | 50 | show_tables_query = "SHOW TABLES" 51 | cursor.execute(show_tables_query) 52 | 53 | print("\n\nSHOW TABLES") 54 | print("-" * 50) 55 | 56 | for row in cursor.fetchall(): 57 | print(row) 58 | 59 | conn.commit() 60 | 61 | def insert_text_details(text2save, title2save): 62 | 63 | global global_id 64 | global_id += 1 65 | print(text2save, title2save) 66 | create_insert_query= " INSERT INTO details VALUES (%s, %s, %s) " 67 | 68 | records = [(global_id, text2save, title2save)] 69 | cursor.executemany(create_insert_query, records) 70 | # cursor.execute(create_insert_query) 71 | 72 | print("Values INSERTED in TABLE details") 73 | 74 | conn.commit() 75 | 76 | def alter_table(): 77 | 78 | create_alter_query = "ALTER TABLE details ADD COLUMN title VARCHAR (30)" # Adding a column in the table 79 | cursor.execute(create_alter_query) 80 | print("ALTER TABLE details: Added column Title") 81 | 82 | conn.commit() 83 | 84 | def delete_records_with_id(): 85 | create_update_query="""DELETE FROM details WHERE id >= 1 """ 86 | cursor.execute(create_update_query) 87 | conn.commit() 88 | 89 | return messagebox.showinfo("DELETED", "Records Deleted Successfully") 90 | 91 | def describe_table_on_terminal(): 92 | 93 | create_desc_query=""" DESCRIBE details""" 94 | cursor.execute(create_desc_query) 95 | 96 | print("\n\nDESCRIBE TABLE details") 97 | print("-" * 50) 98 | 99 | for row in cursor.fetchall(): 100 | print(row) 101 | 102 | conn.commit() 103 | 104 | def print_records_on_terminal(): 105 | 106 | describe_table_on_terminal() 107 | create_select_query=""" SELECT * FROM details """ 108 | cursor.execute(create_select_query) 109 | 110 | print("\n\nPrinting TABLE details") 111 | print("-" * 100) 112 | for row in cursor.fetchall(): 113 | print(row) 114 | 115 | conn.commit() 116 | 117 | 118 | 119 | # create_database() 120 | # create_database_table() 121 | # print_tables_in_database() 122 | # describe_table_on_terminal() 123 | # alter_table() 124 | # delete_records_with_id(1) 125 | # print_records_on_terminal() 126 | conn.commit() 127 | 128 | 129 | from tkinter import * 130 | from tkinter import messagebox, filedialog 131 | 132 | 133 | # Functions 134 | 135 | def save_file(): 136 | '''saves the file in a .txt format''' 137 | text2save = str(text.get(1.0, END)) 138 | title = name_var.get() 139 | print(text2save, title) 140 | insert_text_details(text2save, title) 141 | 142 | # Shows info box if file saved; 143 | return messagebox.showinfo("Saved", "File Saved to Database Successfully") 144 | 145 | def clear_file(): 146 | '''clears the input field ''' 147 | text.delete(1.0, END) 148 | 149 | def print_in_cmd(): 150 | '''prints the file in terminal''' 151 | 152 | print_records_on_terminal() 153 | 154 | # Shows info box if file printed in the terminal; 155 | return messagebox.showinfo("Printed", "Records Printed Successfully") 156 | 157 | def donothing(): 158 | pass 159 | 160 | 161 | 162 | # create root window 163 | root = Tk() 164 | # root window title and dimension 165 | root.title("Welcome to File Editor") 166 | # Set geometry (widthxheight) 167 | root.geometry('1200x550') 168 | 169 | name_var=StringVar() 170 | # creating a label for TITLE using widget Label 171 | Label(root, text = 'TITLE', font=('calibre',14, 'bold')).place(x=30, y=70) 172 | Entry(root, textvariable = name_var, font=('calibre',13,'normal')).place(x=30, y=110) 173 | 174 | # Text Input 175 | text=Text(root, x=30, y=40, padx = 10, pady = 10, wrap=WORD) 176 | text.pack() 177 | 178 | # adding a label to the root window 179 | lbl = Label(root, text = "File Editor") 180 | 181 | # Text to display where to enter text 182 | Label(root, text="Enter Text: ", font=('calibre', 15, 'bold')).place(x=180, y=220, anchor="center") 183 | 184 | 185 | # button widget with blue color text inside 186 | btn = Button(root, text = "Save", fg = "blue", command=save_file) 187 | btn.place(x = 350, y = 450) 188 | 189 | # button widget with blue color text inside 190 | btn = Button(root, text = "Print", fg = "blue", command=print_in_cmd) 191 | btn.place(x = 475, y = 450) 192 | 193 | # button widget with blue color text inside 194 | btn = Button(root, text = "Alter", fg = "blue", command=alter_table) 195 | btn.place(x = 600, y = 450) 196 | 197 | # button widget with blue color text inside 198 | btn = Button(root, text = "Delete Records", fg = "red", command=delete_records_with_id) 199 | btn.place(x = 725, y = 450) 200 | 201 | # menu bar at the top 202 | menubar=Menu(root) 203 | 204 | filemenu=Menu(menubar,tearoff=0) 205 | filemenu.add_command(label="New", command=clear_file) 206 | filemenu.add_command(label="Open", command=donothing) 207 | filemenu.add_command(label="Save", command=save_file) 208 | filemenu.add_command(label="Save as...", command=save_file) 209 | filemenu.add_separator() 210 | filemenu.add_command(label="Exit", command=root.quit) 211 | # Adding cascade 212 | menubar.add_cascade(label="File", menu=filemenu) 213 | 214 | 215 | editmenu=Menu(menubar,tearoff=0) 216 | editmenu.add_command(label="Undo", command=donothing) 217 | editmenu.add_command(label="Copy", command=donothing) 218 | editmenu.add_command(label="Paste", command=donothing) 219 | # Adding cascade 220 | menubar.add_cascade(label="Edit", menu=editmenu) 221 | 222 | 223 | helpmenu=Menu(menubar,tearoff=0) 224 | helpmenu.add_command(label="Help",command=donothing) 225 | # Adding cascade 226 | menubar.add_cascade(label="Help",menu=helpmenu) 227 | 228 | # configuring the root menu 229 | root.config(menu=menubar) 230 | 231 | # Execute Tkinter 232 | root.mainloop() -------------------------------------------------------------------------------- /Python/experiment_10/FirstProject/FirstProject/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tusharnankani/sem4-assignments/3ae356e346583a736e5863a73c34de2a706ea45f/Python/experiment_10/FirstProject/FirstProject/__init__.py -------------------------------------------------------------------------------- /Python/experiment_10/FirstProject/FirstProject/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for FirstProject project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'FirstProject.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /Python/experiment_10/FirstProject/FirstProject/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for FirstProject project. 3 | 4 | Generated by 'django-admin startproject' using Django 3.0.6. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.0/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/3.0/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = '$80k_iyzh(nw_h3j_90u%g0j!k4xcgnh@g6ar32hr&+w=2lx5u' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'myapp', 41 | ] 42 | 43 | MIDDLEWARE = [ 44 | 'django.middleware.security.SecurityMiddleware', 45 | 'django.contrib.sessions.middleware.SessionMiddleware', 46 | 'django.middleware.common.CommonMiddleware', 47 | 'django.middleware.csrf.CsrfViewMiddleware', 48 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 49 | 'django.contrib.messages.middleware.MessageMiddleware', 50 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 51 | ] 52 | 53 | ROOT_URLCONF = 'FirstProject.urls' 54 | 55 | TEMPLATES = [ 56 | { 57 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 58 | 'DIRS': [], 59 | 'APP_DIRS': True, 60 | 'OPTIONS': { 61 | 'context_processors': [ 62 | 'django.template.context_processors.debug', 63 | 'django.template.context_processors.request', 64 | 'django.contrib.auth.context_processors.auth', 65 | 'django.contrib.messages.context_processors.messages', 66 | ], 67 | }, 68 | }, 69 | ] 70 | 71 | WSGI_APPLICATION = 'FirstProject.wsgi.application' 72 | 73 | 74 | # Database 75 | # https://docs.djangoproject.com/en/3.0/ref/settings/#databases 76 | 77 | DATABASES = { 78 | 'default': { 79 | 'ENGINE': 'django.db.backends.sqlite3', 80 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 81 | } 82 | } 83 | 84 | 85 | # Password validation 86 | # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators 87 | 88 | AUTH_PASSWORD_VALIDATORS = [ 89 | { 90 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 91 | }, 92 | { 93 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 94 | }, 95 | { 96 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 97 | }, 98 | { 99 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 100 | }, 101 | ] 102 | 103 | 104 | # Internationalization 105 | # https://docs.djangoproject.com/en/3.0/topics/i18n/ 106 | 107 | LANGUAGE_CODE = 'en-us' 108 | 109 | TIME_ZONE = 'UTC' 110 | 111 | USE_I18N = True 112 | 113 | USE_L10N = True 114 | 115 | USE_TZ = True 116 | 117 | 118 | # Static files (CSS, JavaScript, Images) 119 | # https://docs.djangoproject.com/en/3.0/howto/static-files/ 120 | 121 | STATIC_URL = '/static/' 122 | -------------------------------------------------------------------------------- /Python/experiment_10/FirstProject/FirstProject/urls.py: -------------------------------------------------------------------------------- 1 | """FirstProject URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/3.0/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path, include 18 | 19 | urlpatterns = [ 20 | path('admin/', admin.site.urls), 21 | path('', include('myapp.urls')), 22 | ] 23 | -------------------------------------------------------------------------------- /Python/experiment_10/FirstProject/FirstProject/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for FirstProject project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'FirstProject.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /Python/experiment_10/FirstProject/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tusharnankani/sem4-assignments/3ae356e346583a736e5863a73c34de2a706ea45f/Python/experiment_10/FirstProject/db.sqlite3 -------------------------------------------------------------------------------- /Python/experiment_10/FirstProject/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'FirstProject.settings') 9 | try: 10 | from django.core.management import execute_from_command_line 11 | except ImportError as exc: 12 | raise ImportError( 13 | "Couldn't import Django. Are you sure it's installed and " 14 | "available on your PYTHONPATH environment variable? Did you " 15 | "forget to activate a virtual environment?" 16 | ) from exc 17 | execute_from_command_line(sys.argv) 18 | 19 | 20 | if __name__ == '__main__': 21 | main() 22 | -------------------------------------------------------------------------------- /Python/experiment_10/FirstProject/myapp/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tusharnankani/sem4-assignments/3ae356e346583a736e5863a73c34de2a706ea45f/Python/experiment_10/FirstProject/myapp/__init__.py -------------------------------------------------------------------------------- /Python/experiment_10/FirstProject/myapp/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | from .models import * 4 | 5 | # Register your models here. 6 | 7 | admin.site.register(Student) 8 | -------------------------------------------------------------------------------- /Python/experiment_10/FirstProject/myapp/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class MyappConfig(AppConfig): 5 | name = 'myapp' 6 | -------------------------------------------------------------------------------- /Python/experiment_10/FirstProject/myapp/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.0.6 on 2021-05-12 12:27 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | initial = True 9 | 10 | dependencies = [ 11 | ] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name='Student', 16 | fields=[ 17 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 18 | ('name', models.CharField(max_length=200, null=True)), 19 | ('roll_no', models.IntegerField(null=True)), 20 | ('semester', models.IntegerField(null=True)), 21 | ('division', models.CharField(max_length=20, null=True)), 22 | ('department', models.CharField(max_length=200, null=True)), 23 | ], 24 | ), 25 | ] 26 | -------------------------------------------------------------------------------- /Python/experiment_10/FirstProject/myapp/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tusharnankani/sem4-assignments/3ae356e346583a736e5863a73c34de2a706ea45f/Python/experiment_10/FirstProject/myapp/migrations/__init__.py -------------------------------------------------------------------------------- /Python/experiment_10/FirstProject/myapp/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | class Student(models.Model): 5 | name = models.CharField(max_length=200, null=True) 6 | roll_no = models.IntegerField(null=True) 7 | semester = models.IntegerField(null=True) 8 | division = models.CharField(max_length=20, null=True) 9 | department = models.CharField(max_length=200, null=True) 10 | 11 | def __str__(self): 12 | return self.name 13 | -------------------------------------------------------------------------------- /Python/experiment_10/FirstProject/myapp/templates/myapp/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Database Details 9 | 10 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | {% for stud in students %} 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | {% endfor %} 80 |
NameRoll NumberSemesterDivisionDepartment
{{stud.name}}{{stud.roll_no}}{{stud.semester}}{{stud.division}}{{stud.department}}
81 | 82 | 83 | -------------------------------------------------------------------------------- /Python/experiment_10/FirstProject/myapp/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /Python/experiment_10/FirstProject/myapp/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | 3 | from . import views 4 | 5 | urlpatterns = [ 6 | path('', views.home, name='home'), 7 | ] 8 | -------------------------------------------------------------------------------- /Python/experiment_10/FirstProject/myapp/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | 3 | # Create your views here. 4 | 5 | from .models import * 6 | 7 | def home(request): 8 | students = Student.objects.all() 9 | context = {'students': students} 10 | return render(request, 'myapp/index.html', context) -------------------------------------------------------------------------------- /Python/experiment_11.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Experiment 11" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "## Question 1\n", 15 | "#### Write a program, which can run two-thread simultaneously. One thread will print odd numbers and another thread will print even number. " 16 | ] 17 | }, 18 | { 19 | "cell_type": "markdown", 20 | "metadata": {}, 21 | "source": [ 22 | "#### Theory\n", 23 | "A thread represents a separate path of execution of a group of statements
\n", 24 | "\n", 25 | "In every python program, there is always a thread running internally which is appointed by the PVM to execute the program statements
\n", 26 | "\n", 27 | "In Python program, we need to import **'threading'** module which is needed while dealing with threads.
\n", 28 | "\n", 29 | "#### **Creating Threads in Python**\n", 30 | "\n", 31 | "Python provides **'Thread'** class of **threading** module that is useful to create threads
\n", 32 | "\n", 33 | "To create user defined thread, we need to create an object of Thread class.
\n", 34 | "\n", 35 | "There are different ways of creating threads in Python as:
\n", 36 | "\n", 37 | "* Creating a thread without using a class\n", 38 | "* Creating a thread by creating a sub class to Thread Class\n", 39 | "* Creating a thread without creating sub class to Thread Class\n", 40 | "\n", 41 | "#### **Creating Thread without using Sub class**
\n", 42 | "\n", 43 | "The purpose of a thread is to execute a group of statement like a function.
\n", 44 | "\n", 45 | "We can create a thread by creating an object of Thread class and pass the function name as target for the thread as:\n", 46 | "
\n", 47 | "```\n", 48 | "t = Thread(target = functionname, [args = (arg1, arg2, ...)]\n", 49 | "```\n", 50 | "Here,
\n", 51 | "> 't' represents objects of Thread class.\n", 52 | "\n", 53 | "> 'target' represents the function on which thread will act\n", 54 | "\n", 55 | "> 'args' represents a tuple of arguments which are passed to the function\n", 56 | "\n", 57 | "Thread can be started by calling start( ) method as
\n", 58 | "```\n", 59 | "t.start()\n", 60 | "```\n", 61 | "Then thread will jump to the target function and execute the code \n", 62 | "
\n" 63 | ] 64 | }, 65 | { 66 | "cell_type": "code", 67 | "execution_count": 6, 68 | "metadata": {}, 69 | "outputs": [ 70 | { 71 | "name": "stdout", 72 | "output_type": "stream", 73 | "text": [ 74 | "Odd Numbers: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 \n", 75 | "Even Numbers: 0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 \n" 76 | ] 77 | } 78 | ], 79 | "source": [ 80 | "from threading import *\n", 81 | "\n", 82 | "def even():\n", 83 | " print('Even Numbers: ', end='')\n", 84 | " for i in range(0, 30, 2):\n", 85 | " print(i, end = ' ')\n", 86 | " print()\n", 87 | " \n", 88 | "def odd():\n", 89 | " print('Odd Numbers: ', end = '')\n", 90 | " for i in range(1, 30, 2):\n", 91 | " print(i, end =' ')\n", 92 | " print()\n", 93 | " \n", 94 | "t1 = Thread(target=odd)\n", 95 | "t2 = Thread(target=even)\n", 96 | "\n", 97 | "t1.start()\n", 98 | "t2.start()\n", 99 | "\n", 100 | "t1.join()\n", 101 | "t2.join()" 102 | ] 103 | }, 104 | { 105 | "cell_type": "markdown", 106 | "metadata": {}, 107 | "source": [ 108 | "## Question 2\n", 109 | "\n", 110 | "### Write a program to show deadlock of threads and resolve it\n", 111 | "\n", 112 | "#### Theory\n", 113 | "#### **Thread Synchronization**\n", 114 | "\n", 115 | "When a thread is already acting on object preventing any other thread from acting on the same object is called **Thread Synchronization**\n", 116 | "\n", 117 | "**Synchronized Object/ Mutex (Mutually Exclusive Lock):** The object on which threads are synchronized
\n", 118 | "\n", 119 | "Thread synchronization is recommended when multiple threads are acting on same object simultaneously
\n", 120 | "\n", 121 | "It is implemented using following techniques:
\n", 122 | "\n", 123 | "1. Using Locks\n", 124 | "2. Using Semaphores\n", 125 | "\n", 126 | "#### **Locks**\n", 127 | "\n", 128 | "It can be used to lock the object on which thread is acting.
\n", 129 | "\n", 130 | "When thread enters the object, it locks the object.
\n", 131 | "\n", 132 | "When execution gets completed, it will unlock the object and it will comes out of it
\n", 133 | "\n", 134 | "We can create lock by creating an object of lock class as\n", 135 | "```\n", 136 | "l = Lock()\n", 137 | "```\n", 138 | "\n", 139 | "To lock the current object, we should use acquire() method as\n", 140 | "```\n", 141 | "l.acquire()\n", 142 | "```\n", 143 | "To unlock or release the object, we can use release () method as\n", 144 | "```\n", 145 | "l.release()\n", 146 | "``` \n", 147 | "\n" 148 | ] 149 | }, 150 | { 151 | "cell_type": "code", 152 | "execution_count": 7, 153 | "metadata": {}, 154 | "outputs": [ 155 | { 156 | "name": "stdout", 157 | "output_type": "stream", 158 | "text": [ 159 | "Deadlock: \n", 160 | "Hello from lock 1\n", 161 | "Goodbye from lock 2\n", 162 | "\n", 163 | "Avoiding Deadlock: \n", 164 | "Hello from lock 3\n", 165 | "Hello from lock 4\n", 166 | "Exiting Hello command\n", 167 | "Goodbye from lock 4\n", 168 | "Goodbye from lock 3\n", 169 | "Exiting GoodBye command\n" 170 | ] 171 | } 172 | ], 173 | "source": [ 174 | "from threading import *\n", 175 | "from time import *\n", 176 | "l1 = Lock()\n", 177 | "l2 = Lock()\n", 178 | "l3 = Lock()\n", 179 | "l4 = Lock()\n", 180 | "\n", 181 | "def hello():\n", 182 | " l1.acquire()\n", 183 | " print('Hello from lock 1')\n", 184 | " sleep(1.5)\n", 185 | " l2.acquire()\n", 186 | " print('Hello from lock 2')\n", 187 | " l2.release()\n", 188 | " l1.release()\n", 189 | " print('Exiting hello')\n", 190 | "\n", 191 | "\n", 192 | "def goodbye():\n", 193 | " l2.acquire()\n", 194 | " print('Goodbye from lock 2')\n", 195 | " sleep(1.5)\n", 196 | " l1.acquire()\n", 197 | " print('Goodbye from lock 1')\n", 198 | " l1.release()\n", 199 | " l2.release()\n", 200 | " print('Exiting goodbye')\n", 201 | "\n", 202 | "def hello1():\n", 203 | " l3.acquire()\n", 204 | " print('Hello from lock 3')\n", 205 | " l4.acquire()\n", 206 | " print('Hello from lock 4')\n", 207 | " l4.release()\n", 208 | " l3.release()\n", 209 | " print('Exiting Hello command')\n", 210 | "\n", 211 | "\n", 212 | "def goodbye1():\n", 213 | " l4.acquire()\n", 214 | " print('Goodbye from lock 4')\n", 215 | " l3.acquire()\n", 216 | " print('Goodbye from lock 3')\n", 217 | " l3.release()\n", 218 | " l4.release()\n", 219 | " print('Exiting GoodBye command')\n", 220 | "\n", 221 | "print(\"Deadlock: \")\n", 222 | "t1 = Thread(target=hello)\n", 223 | "t2 = Thread(target=goodbye)\n", 224 | "\n", 225 | "t1.start()\n", 226 | "t2.start()\n", 227 | "print(\"\\nAvoiding Deadlock: \")\n", 228 | "t3 = Thread(target=hello1)\n", 229 | "t4 = Thread(target=goodbye1)\n", 230 | "\n", 231 | "t3.start()\n", 232 | "t4.start()" 233 | ] 234 | }, 235 | { 236 | "cell_type": "markdown", 237 | "metadata": {}, 238 | "source": [ 239 | "## Question 3\n", 240 | "#### Write a program to demonstrate communication between threads." 241 | ] 242 | }, 243 | { 244 | "cell_type": "code", 245 | "execution_count": 8, 246 | "metadata": {}, 247 | "outputs": [ 248 | { 249 | "name": "stdout", 250 | "output_type": "stream", 251 | "text": [ 252 | "Enter Food Items You Want to Order: Pizza PavBhaji Lasagna FriedRice\n", 253 | "Pizza is Being Prepared..\n", 254 | "PavBhaji is Being Prepared..\n", 255 | "Lasagna is Being Prepared..\n", 256 | "FriedRice is Being Prepared..\n", 257 | "Pizza PavBhaji Lasagna FriedRice are prepared\n" 258 | ] 259 | } 260 | ], 261 | "source": [ 262 | "from threading import *\n", 263 | "class Food:\n", 264 | " def __init__(self, items):\n", 265 | " self.items = items\n", 266 | " self.lock = Condition()\n", 267 | "\n", 268 | " def prepare(self):\n", 269 | " self.lock.acquire()\n", 270 | " foodstr = ''\n", 271 | " for item in self.items:\n", 272 | " sleep(1)\n", 273 | " print(f'{item} is Being Prepared..')\n", 274 | " foodstr += item + ' '\n", 275 | " self.lock.notify() \n", 276 | " print(f'{foodstr} are prepared')\n", 277 | " self.lock.release()\n", 278 | "\n", 279 | "\n", 280 | "class Customer:\n", 281 | " def __init__(self, food):\n", 282 | " self.food = food \n", 283 | "\n", 284 | " def waiting(self):\n", 285 | " self.food.lock.acquire()\n", 286 | " self.food.lock.wait(timeout=0)\n", 287 | " self.food.lock.release()\n", 288 | " \n", 289 | "items = list(input(\"Enter Food Items You Want to Order: \").strip().split()) \n", 290 | "\n", 291 | "f1 = Food(items)\n", 292 | "\n", 293 | "c1 = Customer(f1)\n", 294 | "\n", 295 | "\n", 296 | "t1 = Thread(target=f1.prepare)\n", 297 | "t2 = Thread(target=c1.waiting)\n", 298 | "\n", 299 | "t1.start()\n", 300 | "t2.start()\n", 301 | "\n", 302 | "t1.join()\n", 303 | "t2.join()" 304 | ] 305 | }, 306 | { 307 | "cell_type": "code", 308 | "execution_count": null, 309 | "metadata": {}, 310 | "outputs": [], 311 | "source": [] 312 | } 313 | ], 314 | "metadata": { 315 | "kernelspec": { 316 | "display_name": "Python 3", 317 | "language": "python", 318 | "name": "python3" 319 | }, 320 | "language_info": { 321 | "codemirror_mode": { 322 | "name": "ipython", 323 | "version": 3 324 | }, 325 | "file_extension": ".py", 326 | "mimetype": "text/x-python", 327 | "name": "python", 328 | "nbconvert_exporter": "python", 329 | "pygments_lexer": "ipython3", 330 | "version": "3.7.6" 331 | } 332 | }, 333 | "nbformat": 4, 334 | "nbformat_minor": 4 335 | } 336 | -------------------------------------------------------------------------------- /Python/my_package/Account/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tusharnankani/sem4-assignments/3ae356e346583a736e5863a73c34de2a706ea45f/Python/my_package/Account/__init__.py -------------------------------------------------------------------------------- /Python/my_package/Account/salary.py: -------------------------------------------------------------------------------- 1 | class Salary: 2 | def __init__(self, basic_pay, HRA, PF): 3 | self.basic_pay = basic_pay 4 | self.HRA = HRA 5 | self.PF = PF 6 | -------------------------------------------------------------------------------- /Python/my_package/Employee/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tusharnankani/sem4-assignments/3ae356e346583a736e5863a73c34de2a706ea45f/Python/my_package/Employee/__init__.py -------------------------------------------------------------------------------- /Python/my_package/Employee/profile.py: -------------------------------------------------------------------------------- 1 | class Profile: 2 | def __init__(self, name, age, dob): 3 | self.name = name 4 | self.age = age 5 | self.dob = dob 6 | -------------------------------------------------------------------------------- /Python/my_package/Employee/qualification.py: -------------------------------------------------------------------------------- 1 | class Qualification: 2 | def __init__(self, degree, qualification): 3 | self.degree = degree 4 | self.qualification = qualification 5 | -------------------------------------------------------------------------------- /Python/my_package/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tusharnankani/sem4-assignments/3ae356e346583a736e5863a73c34de2a706ea45f/Python/my_package/__init__.py -------------------------------------------------------------------------------- /Python/testfile.txt: -------------------------------------------------------------------------------- 1 | This is a test file. 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Semester 4 Assignments 2 | 3 | - Invest your time writing in code and understanding concepts, and not writing theory. 4 | - Except Microprocessor, just copy it as it is. \*facepalm\* 5 | 6 | To access the files, just clone it on your local PC, or fork it if you want to make changes and keep it for yourself. 7 | ```bash 8 | git clone https://github.com/tusharnankani/sem4-assignments 9 | Ctrl C 10 | Ctrl V 11 | ``` 12 | 13 | ### Table of Contents 14 | 15 | - [AOA](#ananlysis-of-algorithms-aoa) 16 | - [DBMS](#database-management-system-dbms) 17 | - [MP](#microprocessor) 18 | - [OS](#operating-system) 19 | - [Python](#python) 20 | 21 | ### [Ananlysis of Algorithms (AOA)](https://github.com/tusharnankani/sem4-assignments/tree/main/Analysis%20of%20Algorithms%20(AOA)) 22 | 23 | 1. To implement Insertion sort and selection sort Algorithm 24 | 2. To implement Quick sort , Merge sort Algorithm 25 | 3. To implement Max min Algorithm 26 | 4. To implement Dijkstra Algorithm 27 | 5. To implement Fractional Knapsack Algorithm 28 | 6. To implement 0/1 knapsack Algorithm 29 | 7. To implement Longest Common Subsequence Algorithm 30 | 8. To implement N QUEENS Algorithm 31 | 9. To implement Sum of subsets Algorithm 32 | 10. To implement Knuth Morris Pratt Algorithm 33 | 34 | ### [Database Management System (DBMS)](https://github.com/tusharnankani/sem4-assignments/tree/main/Database%20Management%20System%20(DBMS)) 35 | 36 | Here is my complete DBMS case study: [Airport-DBMS](https://github.com/tusharnankani/Airport-DBMS) 37 | - And it has all the queries, experiment by experiment, in a queries.txt file. 38 | 39 | ### [Microprocessor](https://github.com/tusharnankani/sem4-assignments/tree/main/Microprocessor%20(MP)) 40 | 41 | - This subject is outdated and awful, please don't invest your time in it. 42 | - I have just given all the .docx files and the final PDFs. 43 | - To access them, just clone this repository in your local machine and you will get all the files. 44 | 45 | ### [Operating System](https://github.com/tusharnankani/sem4-assignments/tree/main/Operating%20System%20(OS)) 46 | 47 | - This is super important, I have also created a different repository all together for this: [OperatingSystemAlgorithms](https://github.com/tusharnankani/OperatingSystemAlgorithms) 48 | - This subject is super interesting, try not to copy the code. This is just for your help. 49 | 50 | #### *Content* 51 | 52 | 0. Shell Scripts 53 | 1. Memory Allocation Simulator 54 | 2. Paging Algorithms 55 | 3. Scheduling Algorithms 56 | 4. Page Replacement Algorithms 57 | 5. Disk Scheduling Algorithms 58 | 6. Banker's Algorithm 59 | 60 | - built with Java, for a better understanding of Operating System. 61 | 62 | ### [Python](https://github.com/tusharnankani/sem4-assignments/tree/main/Python) 63 | 64 | - And finally, Python. 65 | - It has everything, from theory to experiment, all in Jupyter Notebooks. 66 | - Write the code, take some help from here, and use them completely for writing Theory. 67 | - Again, the notebooks might take some time, so clone it and access them on your local PC, like you use Jupyter Notebooks. 68 | 69 | #### Thank you 70 | ### Tushar Nankani 71 | - [LinkedIn](https://www.linkedin.com/in/tusharnankani/) | [Twitter](https://twitter.com/tusharnankanii) 72 | 73 | 74 | --------------------------------------------------------------------------------