├── .idea ├── misc.xml ├── modules.xml └── vcs.xml ├── Capgemini ├── CAPGEMINI CODING QUESTIONS .pdf ├── capg1.py ├── capg2.py ├── capg3.py ├── capg4.py └── capg5.py ├── DataStructures-And-Algorithim ├── LinearSearch.py ├── List.md ├── functionLIst.md ├── mapfunc.py └── test.txt ├── GenC-prep ├── DigitStrings.java ├── Question1.java ├── Question10.java ├── Question11.java ├── Question12.java ├── Question13.java ├── Question2.java ├── Question3.java ├── Question4.java ├── Question5.java ├── Question6.java ├── Question7.java ├── Question8.java ├── Question9.java ├── StrongerKnights.java ├── javaArray.java └── questions.txt ├── README.md ├── classwork ├── datascience.py ├── new_file.py ├── practice1.py ├── practice11.py ├── practice12.py ├── practice2.py ├── practice3.py ├── practice4.py ├── practice5.py ├── practice6.py ├── practice7.py ├── practice8.py ├── practice9.py ├── question10.py └── questions.txt ├── miscelenious ├── DoubleLinkedList$Node.class ├── DoubleLinkedList.class ├── DoubleLinkedList.java ├── LinkedList.java ├── Practice.jav ├── Screenshot.jpg ├── Shopping .py ├── Structure.py ├── agent_try.py ├── arraychallange.py ├── arrchallange.py ├── ascii_art.txt ├── ascii_art_converter.py ├── ascii_video.py ├── calculator.py ├── challange32.py ├── data2.py ├── deployment.py ├── doughnut.py ├── dsaa.py ├── encrypt.py ├── encrytionDecryption.py ├── fibonacci.py ├── graphchallange.py ├── index.html ├── leaaldownload.py ├── lyrics.txt ├── maximumSubArray.py ├── mbappe.txt ├── mergesort.py ├── new_file.py ├── outputs │ ├── fibonacci_spiral_20250404_183922.gif │ ├── fibonacci_spiral_20250404_184148.gif │ └── fibonacci_spiral_20250404_184355.gif ├── passwords.json ├── practice_1.py ├── python_game.py ├── random_luck.py ├── recursion printing.py ├── roman.py ├── script.js ├── searching.py ├── sha512.py ├── string27.py ├── stringchallange1.py ├── stringchallange2.py ├── styles.css ├── sumoftwolinkedlist.py ├── temperature_converter.py ├── test.py ├── testimage.jpg └── turtle_animation.py ├── notes and materials ├── DSA_notes.txt ├── Practice Set.pdf ├── Python-Cheat-Sheet.pdf ├── algorithm-design-techniques_compress.pdf ├── seaborm.md └── ubuntucommands.txt └── out └── production └── pythonFiles ├── Practice.jav ├── Question1.class ├── Question10.class ├── Screenshot.jpg ├── Shopping .py ├── Structure.py ├── agent_try.py ├── arraychallange.py ├── arrchallange.py ├── ascii_art.txt ├── ascii_art_converter.py ├── ascii_video.py ├── calculator.py ├── challange32.py ├── data2.py ├── deployment.py ├── doughnut.py ├── dsaa.py ├── encrypt.py ├── encrytionDecryption.py ├── fibonacci.py ├── graphchallange.py ├── index.html ├── leaaldownload.py ├── lyrics.txt ├── maximumSubArray.py ├── mbappe.txt ├── mergesort.py ├── new_file.py ├── passwords.json ├── practice_1.py ├── python_game.py ├── questions.txt ├── random_luck.py ├── recursion printing.py ├── roman.py ├── script.js ├── searching.py ├── sha512.py ├── string27.py ├── stringchallange1.py ├── stringchallange2.py ├── styles.css ├── sumoftwolinkedlist.py ├── temperature_converter.py ├── test.py ├── testimage.jpg └── turtle_animation.py /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Capgemini/CAPGEMINI CODING QUESTIONS .pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anubhob435/pythonFiles/e8fe21829ff9f4e194e4f6bd8ba913539385d73f/Capgemini/CAPGEMINI CODING QUESTIONS .pdf -------------------------------------------------------------------------------- /Capgemini/capg1.py: -------------------------------------------------------------------------------- 1 | def max_people(N): 2 | # Initialize k to 1 3 | k = 1 4 | 5 | # Keep increasing k until sum exceeds N 6 | while (k * (k + 1)) // 2 <= N: 7 | k += 1 8 | 9 | # Since we went one step too far, return k-1 10 | return k - 1 11 | 12 | # Test cases 13 | def test_cases(): 14 | test_inputs = [10, 5, 3, 15] 15 | for N in test_inputs: 16 | result = max_people(N) 17 | print(f"Input N = {N}") 18 | print(f"Output: {result}") 19 | print() 20 | 21 | # Run test cases 22 | if __name__ == "__main__": 23 | test_cases() -------------------------------------------------------------------------------- /Capgemini/capg2.py: -------------------------------------------------------------------------------- 1 | def find_nearest_digits(N): 2 | digits = list(range(1, 10)) # 1 to 9 3 | digit1 = min(digits, key=lambda x: abs(x - N)) 4 | digits.remove(digit1) 5 | digit2 = min(digits, key=lambda x: abs(x - N)) 6 | return digit1, digit2 7 | 8 | def generate_fibonacci(n): 9 | if n <= 0: 10 | return [] 11 | if n == 1: 12 | return [0] 13 | 14 | fib = [0, 1] 15 | while len(fib) < n: 16 | fib.append(fib[-1] + fib[-2]) 17 | return fib 18 | 19 | def solve_fibonacci_sum(N): 20 | # Step 1: Find nearest digits 21 | digit1, digit2 = find_nearest_digits(N) 22 | 23 | # Step 2: Calculate product 24 | product = digit1 * digit2 25 | 26 | # Step 3: Generate Fibonacci sequence 27 | fib_sequence = generate_fibonacci(product) 28 | 29 | # Step 4: Calculate sum 30 | return sum(fib_sequence) 31 | 32 | def test_cases(): 33 | test_inputs = [3, 5, 7] 34 | for N in test_inputs: 35 | result = solve_fibonacci_sum(N) 36 | print(f"Input N = {N}") 37 | digit1, digit2 = find_nearest_digits(N) 38 | print(f"Nearest digits: {digit1}, {digit2}") 39 | print(f"Product: {digit1 * digit2}") 40 | print(f"Fibonacci sum: {result}") 41 | print() 42 | 43 | if __name__ == "__main__": 44 | test_cases() -------------------------------------------------------------------------------- /Capgemini/capg3.py: -------------------------------------------------------------------------------- 1 | def get_distance_from_target(number, target): 2 | return abs(number - target) 3 | 4 | def find_k_closest(arr, t, k): 5 | # Create list of (number, distance) pairs 6 | distances = [] 7 | for num in arr: 8 | distance = get_distance_from_target(num, t) 9 | distances.append((num, distance)) 10 | 11 | # Sort by distance 12 | distances.sort(key=lambda pair: pair[1]) 13 | 14 | # Take first k numbers 15 | result = [] 16 | for i in range(k): 17 | result.append(distances[i][0]) 18 | 19 | return result 20 | 21 | def calculate_product(numbers): 22 | result = 1 23 | for num in numbers: 24 | result *= num 25 | return result 26 | 27 | def generate_fibonacci_up_to(n): 28 | if n <= 0: 29 | return [] 30 | 31 | fib = [0, 1] 32 | while fib[-1] <= n: 33 | fib.append(fib[-1] + fib[-2]) 34 | return fib[:-1] # Remove last number that exceeded n 35 | 36 | def solve_min_diff_fibonacci(arr, t, k): 37 | # Step 1: Find k closest elements 38 | closest_elements = find_k_closest(arr, t, k) 39 | 40 | # Step 2: Calculate their product 41 | product = calculate_product(closest_elements) 42 | 43 | # Step 3: Generate Fibonacci sequence up to product 44 | fib_sequence = generate_fibonacci_up_to(product) 45 | 46 | # Step 4: Calculate sum 47 | return sum(fib_sequence) 48 | 49 | def test_cases(): 50 | test_cases = [ 51 | ([1, 2, 3, 4, 5], 3, 2), 52 | ([10, 20, 30, 40, 50], 25, 3), 53 | ([5, 10, 15, 20], 12, 2) 54 | ] 55 | 56 | for arr, t, k in test_cases: 57 | result = solve_min_diff_fibonacci(arr, t, k) 58 | closest = find_k_closest(arr, t, k) 59 | product = calculate_product(closest) 60 | print(f"Array: {arr}") 61 | print(f"Target: {t}") 62 | print(f"K: {k}") 63 | print(f"K closest elements: {closest}") 64 | print(f"Their product: {product}") 65 | print(f"Fibonacci sum: {result}") 66 | print() 67 | 68 | if __name__ == "__main__": 69 | test_cases() -------------------------------------------------------------------------------- /Capgemini/capg4.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | #comitting to make sure that github streak is maintained 4 | #comitting to make sure that github streak is maintained 5 | #COMMITING TO KEEP GITHUB STREAK ON TRACK 6 | 7 | def generate_random_quote(): 8 | quotes = [ 9 | "Life is like a box of chocolates.", 10 | "The only way to do great work is to love what you do.", 11 | "Be yourself; everyone else is already taken.", 12 | "Strive not to be a success, but rather to be of value." 13 | ] 14 | return random.choice(quotes) 15 | 16 | def main(): 17 | print("Random quote:") 18 | print(generate_random_quote()) 19 | random_number = random.randint(1, 100) 20 | print("A random number between 1 and 100:", random_number) 21 | 22 | if __name__ == "__main__": 23 | main() -------------------------------------------------------------------------------- /Capgemini/capg5.py: -------------------------------------------------------------------------------- 1 | def find_nearest_number(arr, target): 2 | """Find number in array closest to target""" 3 | if not arr: 4 | return None 5 | return min(arr, key=lambda x: abs(x - target)) 6 | 7 | def generate_fibonacci(n): 8 | """Generate Fibonacci sequence up to n terms""" 9 | if n <= 0: 10 | return [] 11 | if n == 1: 12 | return [0] 13 | 14 | fib = [0, 1] 15 | while len(fib) < n: 16 | fib.append(fib[-1] + fib[-2]) 17 | return fib 18 | 19 | def solve_nearest_fibonacci(arr, target, key): 20 | # Input validation 21 | if not arr or key < 0: 22 | return 0 23 | 24 | # Find nearest number 25 | nearest = find_nearest_number(arr, target) 26 | 27 | # Generate Fibonacci sequence 28 | fib_sequence = generate_fibonacci(key) 29 | 30 | # Calculate sum 31 | return sum(fib_sequence) 32 | 33 | def test_cases(): 34 | tests = [ 35 | ([1, 5, 10, 15], 12, 5), 36 | ([2, 4, 6, 8], 5, 3), 37 | ([20, 30, 40], 25, 4), 38 | ([], 5, 3), # Edge case: empty array 39 | ([1], 1, 0) # Edge case: single element, zero key 40 | ] 41 | 42 | for arr, target, key in tests: 43 | print(f"\nTest Case:") 44 | print(f"Array: {arr}") 45 | print(f"Target: {target}") 46 | print(f"Key: {key}") 47 | 48 | result = solve_nearest_fibonacci(arr, target, key) 49 | if arr: 50 | nearest = find_nearest_number(arr, target) 51 | print(f"Nearest number to {target}: {nearest}") 52 | print(f"Fibonacci sum: {result}") 53 | 54 | if __name__ == "__main__": 55 | test_cases() -------------------------------------------------------------------------------- /DataStructures-And-Algorithim/LinearSearch.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anubhob435/pythonFiles/e8fe21829ff9f4e194e4f6bd8ba913539385d73f/DataStructures-And-Algorithim/LinearSearch.py -------------------------------------------------------------------------------- /DataStructures-And-Algorithim/List.md: -------------------------------------------------------------------------------- 1 | # Data Structures and Algorithms List 2 | 3 | ## Beginner Level (Foundational Algorithms) 4 | 5 | 1. Linear Search 6 | 2. Binary Search 7 | 3. Bubble Sort 8 | 4. Selection Sort 9 | 5. Insertion Sort 10 | 6. Merge Sort 11 | 7. Quick Sort 12 | 8. Two Pointers Technique 13 | 9. Sliding Window Technique 14 | 10. Kadane's Algorithm (Maximum Subarray Sum) 15 | 11. Prefix Sum and Difference Arrays 16 | 12. Flood Fill Algorithm (DFS/BFS for grid problems) 17 | 18 | ## Intermediate Level (Core Algorithms) 19 | 20 | 13. Hashing (Maps, Sets, Frequency Count) 21 | 14. Heap/Priority Queue Algorithms 22 | 15. Counting Sort and Bucket Sort 23 | 16. Binary Search on Answer (E.g., Minimum Capacity to Ship Packages) 24 | 17. Union-Find/Disjoint Set Union (DSU) 25 | 18. KMP Algorithm (Pattern Matching) 26 | 19. Rabin-Karp Algorithm (String Matching) 27 | 20. DFS and BFS (Graph Traversals) 28 | 21. Topological Sort (Kahn's Algorithm, DFS-based) 29 | 22. Dijkstra's Algorithm (Shortest Path) 30 | 23. Bellman-Ford Algorithm (Shortest Path with Negative Weights) 31 | 24. Floyd-Warshall Algorithm (All-Pairs Shortest Path) 32 | 33 | ## Advanced Level (High-Impact Algorithms) 34 | 35 | 25. Backtracking (e.g., N-Queens, Sudoku Solver, Permutations) 36 | 26. Dynamic Programming on Subsets (Subset Sum, Knapsack) 37 | 27. Dynamic Programming on Strings (Longest Common Subsequence, Edit Distance) 38 | 28. Dynamic Programming on Grids (Unique Paths, Min Path Sum) 39 | 29. Segment Trees (Range Queries, Lazy Propagation) 40 | 30. Fenwick Tree/Binary Indexed Tree 41 | 31. Trie (Prefix Tree) (For String Problems) 42 | 32. Suffix Arrays and LCP Array 43 | 33. Manacher's Algorithm (Longest Palindromic Substring) 44 | 34. Shortest Path in a DAG (Dynamic Programming + Topological Sort) 45 | 35. Bit Manipulation Algorithms (e.g., Subset Generation, XOR tricks) 46 | -------------------------------------------------------------------------------- /DataStructures-And-Algorithim/functionLIst.md: -------------------------------------------------------------------------------- 1 | # Python Function Reference 2 | 3 | ## Basic Functions 4 | 5 | ### `print()` 6 | - `sep=""` - separator between items 7 | - `end=""` - what to print at the end 8 | 9 | ### `help()` 10 | Get help documentation for objects 11 | 12 | ### `range(a, b, c)` 13 | - `a` = start value 14 | - `b` = end value (not included) 15 | - `c` = step value 16 | 17 | ### `list()` 18 | Create a new list 19 | 20 | ## Higher-Order Functions 21 | 22 | ### `map()` 23 | Applies a function to each item in a list 24 | 25 | **Using lambda:** 26 | ```python 27 | map(lambda x: x + "s", strings) 28 | ``` 29 | 30 | **Using custom function:** 31 | ```python 32 | def add_s(string): 33 | return string + "s" 34 | 35 | map(add_s, strings) 36 | ``` 37 | 38 | ### `filter()` 39 | Filters items in a list based on a condition 40 | 41 | **Example:** 42 | ```python 43 | x = filter(longer_than_4, strings) 44 | # or with lambda 45 | x = filter(lambda x: condition, strings) 46 | ``` 47 | 48 | ### `sum(numbers, start=0)` 49 | Sum all numbers in a list with optional start value 50 | 51 | ### `sorted()` 52 | Returns a sorted list 53 | 54 | **Parameters:** 55 | - `reverse=True` - sort in descending order 56 | - `key` - custom function to specify sorting criteria 57 | 58 | **Example:** Sort list of dictionaries by specific key 59 | ```python 60 | sorted(list_of_dicts, key=lambda x: x['key_name']) 61 | ``` 62 | 63 | ## Iteration Functions 64 | 65 | ### `enumerate()` 66 | Enhanced for loop with index 67 | 68 | ```python 69 | for index, task in enumerate(tasks): 70 | print(f"{index + 1}. {task}") 71 | ``` 72 | 73 | ### `zip()` 74 | Combines multiple iterables (stops at shortest length) 75 | 76 | ## File Operations 77 | 78 | ### `open()` 79 | Open a file with specified permissions 80 | - `"r"` - read 81 | - `"w"` - write 82 | - `"a"` - append 83 | - `"wr"` - read/write 84 | 85 | ### File Handling Best Practice 86 | ```python 87 | with open("filename.txt", "w") as file: 88 | file.write("content") 89 | # file automatically closes 90 | ``` 91 | 92 | **Manual closing:** 93 | ```python 94 | file.close() 95 | ``` 96 | 97 | 98 | pprint() -------------------------------------------------------------------------------- /DataStructures-And-Algorithim/mapfunc.py: -------------------------------------------------------------------------------- 1 | help(list) -------------------------------------------------------------------------------- /DataStructures-And-Algorithim/test.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anubhob435/pythonFiles/e8fe21829ff9f4e194e4f6bd8ba913539385d73f/DataStructures-And-Algorithim/test.txt -------------------------------------------------------------------------------- /GenC-prep/DigitStrings.java: -------------------------------------------------------------------------------- 1 | public class DigitStrings { 2 | public static int CountSurroundingNumbers(String str){ 3 | 4 | int surrond_count = 0; 5 | int temp = 0; 6 | int len = str.length(); 7 | 8 | for (int i = 0; i < len; i++){ 9 | if (Character.isDigit(str.charAt(i))) 10 | System.err.println("hi"); 11 | } 12 | 13 | return 0; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /GenC-prep/Question1.java: -------------------------------------------------------------------------------- 1 | import java.text.DecimalFormat; 2 | import java.util.Scanner; 3 | 4 | public class Question1 { 5 | public static void main(String[] args) { 6 | Scanner sc = new Scanner(System.in); 7 | DecimalFormat df2 =new DecimalFormat("0.00"); 8 | 9 | System.out.print("Enter Total fuel to fill the tank: "); 10 | double total_fuel = sc.nextDouble(); 11 | 12 | System.out.print("Enter Total distance covered: "); 13 | double total_distance = sc.nextDouble(); 14 | 15 | if(total_fuel <=0 || total_distance<=0 ){ 16 | System.out.println("Invalid Input"); 17 | } 18 | else{ 19 | double total_distance_miles = total_distance/0.6214; 20 | double total_fuel_gallons = total_fuel/0.2642; 21 | 22 | 23 | double per100_km_fuel = (total_fuel/total_distance)*100; 24 | System.out.println(df2.format(per100_km_fuel)); 25 | 26 | double miles_per_gallons = total_distance_miles/total_fuel_gallons; 27 | 28 | System.out.println(df2.format(miles_per_gallons)); 29 | } 30 | 31 | 32 | sc.close(); 33 | } 34 | } -------------------------------------------------------------------------------- /GenC-prep/Question10.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Question10 { 4 | public static void main(String[] args) { 5 | Scanner scanner = new Scanner(System.in); 6 | System.out.println("Enter a 4-digit number:"); 7 | int number = scanner.nextInt(); 8 | scanner.close(); 9 | 10 | if (isValidCarNumber(number)) { 11 | System.out.println(number + " is a valid car number"); 12 | } else { 13 | System.out.println(number + " is not a valid car number"); 14 | } 15 | scanner.close(); 16 | } 17 | 18 | public static boolean isValidCarNumber(int number) { 19 | // Check if it's a positive 4-digit number 20 | if (number < 1000 || number > 9999) { 21 | return false; 22 | } 23 | 24 | // Calculate sum of digits 25 | int sum = 0; 26 | int temp = number; 27 | 28 | while (temp > 0) { 29 | sum += temp % 10; 30 | temp /= 10; 31 | } 32 | 33 | // Check if sum is divisible by 3 or 5 or 7 34 | return sum % 3 == 0 || sum % 5 == 0 || sum % 7 == 0; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /GenC-prep/Question11.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class Question11 { 3 | public static void main(String[] args) { 4 | Scanner sc = new Scanner(System.in); 5 | System.out.print("Enter the number of courses available "); 6 | int num = sc.nextInt(); 7 | 8 | if (num < 1 || num >20){ 9 | System.out.println("Invalid number of courses: "); 10 | System.exit(0); 11 | } 12 | 13 | String[] Courses = new String[num]; 14 | 15 | System.out.println("Enter Course Names: "); 16 | sc.nextLine(); 17 | for (int i = 0; i < num; i++){ 18 | Courses[i] = sc.nextLine(); 19 | } 20 | 21 | System.out.println("Enter the course to be searched: "); 22 | String st = sc.nextLine().toLowerCase(); 23 | 24 | boolean course_avalable = false; 25 | for( int j = 0; j 100) 21 | System.exit(0); 22 | 23 | if(y> max_this_sem) 24 | max_this_sem = y; 25 | } 26 | max_marks_arr[i] = max_this_sem; 27 | } 28 | 29 | for (int k =0; k < x; k++){ 30 | System.out.println("Highest Marks in " + (k+1) + " smester is " + (max_marks_arr[k])); 31 | } 32 | 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /GenC-prep/Question2.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class Question2 { 3 | public static void main(String[] args) { 4 | Scanner sc = new Scanner(System.in); 5 | 6 | System.out.println("Enter no. of pizzas bought: "); 7 | int pizza = sc.nextInt(); 8 | 9 | System.out.println("Enter no. of puffs bought: "); 10 | int puffs = sc.nextInt(); 11 | 12 | System.out.println("Enter no. of cool drinks bought: "); 13 | int cooldrinks = sc.nextInt(); 14 | 15 | int price_pizza = 100; 16 | int price_puffs = 20; 17 | int prize_cooldrinks = 10; 18 | 19 | int total_bill = (pizza * price_pizza) + (puffs * price_puffs) + (cooldrinks * prize_cooldrinks); 20 | System.out.println("no. of pizaas: " + pizza); 21 | System.out.println("no. of Puffs: " + puffs); 22 | System.out.println("no. of cooldrinks: " + cooldrinks); 23 | System.out.println("Total price: " + total_bill); 24 | System.out.println("Enjoy the show!! "); 25 | 26 | sc.close(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /GenC-prep/Question3.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class Question3 { 3 | public static void main(String[] args) { 4 | Scanner sc = new Scanner(System.in); 5 | 6 | System.out.println("Enter the numbers: "); 7 | 8 | for(int i = 1; i<= 4; i++){ 9 | int x = sc.nextInt(); 10 | char y = (char) x; 11 | System.err.println(x + "- " + y); 12 | 13 | } 14 | 15 | sc.close(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /GenC-prep/Question4.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Scanner; 3 | 4 | public class Question4 { 5 | public static void main(String[] args) { 6 | Scanner sc = new Scanner(System.in); 7 | 8 | System.out.println("Enter the no of students placed in CSE"); 9 | int cse = sc.nextInt(); 10 | if (cse < 0) 11 | System.out.println("invalid Input"); 12 | 13 | System.out.println("Enter the no of students placed in ECE"); 14 | int ece = sc.nextInt(); 15 | if (ece < 0) 16 | System.out.println("invalid Input"); 17 | 18 | System.out.println("Enter the no of students placed in MECH"); 19 | int mech = sc. nextInt(); 20 | if (mech < 0) 21 | System.out.println("invalid Input"); 22 | 23 | if(cse == ece & ece == mech) 24 | System.out.println("None got highest placements"); 25 | 26 | else{ 27 | System.out.println("HIGHEST PLACEMENT: "); 28 | if (cse>= ece && cse>= mech) 29 | System.out.println("CSE"); 30 | if (ece>= cse && ece >= mech) 31 | System.err.println("ECE"); 32 | if (mech >= cse && mech> ece) 33 | System.out.println("MECH"); 34 | } 35 | 36 | 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /GenC-prep/Question5.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Question5 { 3 | public static void main(String[] args){ 4 | Scanner sc = new Scanner(System.in); 5 | 6 | int cost_of_k = 75; 7 | int cost_of_q = 150; 8 | int cost_of_refreshments = 50; 9 | int discount_percentage = 0; 10 | 11 | double total_bill = 0; 12 | 13 | System.out.println("enter the number of tickets: "); 14 | int tickets = sc.nextInt(); 15 | if (tickets <5 && tickets > 40){ 16 | System.out.println("invalid tickets"); 17 | System.exit(0); 18 | } 19 | if(tickets >= 20){ 20 | discount_percentage = 10; 21 | } 22 | sc.nextLine(); 23 | System.out.println("Do You want refreshments? "); 24 | char op1 = sc.nextLine().charAt(0); 25 | if (op1 == 'y') 26 | total_bill += tickets * cost_of_refreshments; 27 | 28 | System.out.println("Do You have Coupon?: "); 29 | char op2 = sc.nextLine().charAt(0); 30 | if (op2 == 'y') 31 | discount_percentage += 2; 32 | 33 | 34 | System.out.println("Enter circle: "); 35 | char circle = sc.nextLine().charAt(0); 36 | 37 | if (circle == 'q') 38 | total_bill += tickets * cost_of_q; 39 | else 40 | total_bill += tickets * cost_of_k; 41 | 42 | 43 | double finaal_bill = total_bill - (discount_percentage * total_bill /100); 44 | System.out.println("Ticket cost: " + finaal_bill); 45 | 46 | 47 | 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /GenC-prep/Question6.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class Question6 { 3 | public static void main(String[] args) { 4 | Scanner sc = new Scanner(System.in); 5 | 6 | System.out.println("Enter month number:"); 7 | int month = sc.nextInt(); 8 | 9 | if (month >12 || month < 1){ 10 | System.out.println("invalid month"); 11 | System.exit(0); 12 | } 13 | System.out.print("Season: "); 14 | if (month >= 3 && month <= 5){ 15 | System.out.println("Spring"); 16 | } 17 | if (month >= 6 && month <= 8){ 18 | System.out.println("Summer"); 19 | } 20 | if (month >= 9 && month <= 11){ 21 | System.out.println("Autumn"); 22 | } 23 | if (month ==12 && month <= 2){ 24 | System.out.println("Winter"); 25 | } 26 | 27 | sc.close(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /GenC-prep/Question7.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class Question7 { 3 | 4 | public static boolean isprime(int a){ 5 | boolean isprime = true; 6 | int x; 7 | if (a<2) 8 | isprime = false; 9 | else if (a== 2) 10 | isprime = true; 11 | 12 | else{ 13 | for (int i= 2; i b){ 30 | System.out.println("Invalid Input"); 31 | System.exit(0); 32 | } 33 | sc.close(); 34 | 35 | for(int j = a; j <= b; j++){ 36 | boolean k = isprime(j); 37 | if (k == true) 38 | System.out.print(j + " "); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /GenC-prep/Question8.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class Question8 { 3 | public static void main(String[] args) { 4 | Scanner sc = new Scanner(System.in); 5 | int n = sc.nextInt(); 6 | int x = n; 7 | int rev = 0; 8 | while(n !=0){ 9 | int z = n %10; 10 | rev = rev *10 + z; 11 | n = n/10; 12 | } 13 | 14 | if(x == rev) 15 | System.out.println("palindrome"); 16 | else 17 | System.out.println("Not a palindrome"); 18 | 19 | sc.close(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /GenC-prep/Question9.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class Question9 { 3 | public static void main(String[] args) { 4 | Scanner sc = new Scanner(System.in); 5 | 6 | System.out.println("Enter Salary"); 7 | double Salary = sc.nextDouble(); 8 | if (Salary <= 0){ 9 | System.out.println("Invalid Input"); 10 | System.exit(0); 11 | } 12 | System.out.print("Enter the performance appraisal rating: "); 13 | double appraisal = sc.nextDouble(); 14 | if (appraisal< 1 || appraisal > 5){ 15 | System.out.println("Invalid Input"); 16 | System.exit(0); 17 | } 18 | 19 | double new_salary = 0; 20 | 21 | if(appraisal >= 1 && appraisal <= 3){ 22 | new_salary = Salary + (0.1 * Salary); 23 | } 24 | else if(appraisal >= 3.1 && appraisal <= 4){ 25 | new_salary = Salary + (0.25 * Salary); 26 | } 27 | else 28 | new_salary = Salary + (0.3 * Salary ); 29 | 30 | 31 | System.out.println(new_salary); 32 | 33 | sc.close(); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /GenC-prep/StrongerKnights.java: -------------------------------------------------------------------------------- 1 | public class StrongerKnights { 2 | 3 | public static int CountSpecialKnights(int N, int[] arr){ 4 | 5 | int special_knights_count = 0; 6 | 7 | for(int i = 0; i< N; i++){ 8 | int left = 0; 9 | int right = 0; 10 | 11 | for (int j =0; j< i; j++ ){ 12 | if (arr[j]> arr[i]) 13 | left+=1; 14 | } 15 | for (int k = i+1; k arr[i]) 17 | right += 1; 18 | } 19 | if (left > right) 20 | special_knights_count += 1; 21 | 22 | } 23 | 24 | if (special_knights_count > 0) 25 | return special_knights_count-1; 26 | 27 | return 0; 28 | 29 | } 30 | public static void main(String[] args) { 31 | int[] array = {5,4,3,2,1}; 32 | 33 | int x = CountSpecialKnights(5, array); 34 | System.out.print(x); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /GenC-prep/javaArray.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class javaArray { 3 | public static void main(String[] args) { 4 | Scanner sc = new Scanner(System.in); 5 | int array[] = {1,3,5,7,2,2,1}; 6 | Arrays.sort(array); 7 | for (int i = 0; i<= 6; i++) 8 | System.out.print(array[i] + ", "); 9 | 10 | System.out.println(); 11 | 12 | String arr[] = {"boys", "apple", "girls", "zebra", "hello" }; 13 | for (int j = 0; j<= 4; j++) 14 | System.out.print(arr[j] + ", "); 15 | 16 | System.out.println(); 17 | 18 | Arrays.sort(arr); 19 | for (int j = 0; j<= 4; j++) 20 | System.out.print(arr[j] + ", "); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python Code Collection 2 | 3 | A repository containing various Python implementations, algorithm challenges, coursework, and web applications. 4 | 5 | ## Repository Structure 6 | 7 | - **Classwork**: Collection of Python exercises and solutions from coursework 8 | - Array manipulation 9 | - String processing 10 | - Linked list implementations 11 | - Dynamic programming 12 | - Search algorithms 13 | 14 | - **Capgemini**: Interview preparation and coding challenges for Capgemini 15 | - Algorithmic problems 16 | - Fibonacci sequence applications 17 | - Optimization problems 18 | 19 | - **Miscellaneous**: Various standalone projects and scripts 20 | - Web scraping tools 21 | - Voice recognition web app 22 | - Data visualization 23 | - Algorithm challenges 24 | - String manipulation utilities 25 | - ASCII art and animation 26 | - Encryption utilities 27 | 28 | - **Notes and Materials**: Documentation and learning resources 29 | - Algorithm design techniques 30 | - DSA notes 31 | - Python cheat sheets 32 | - Practice problem sets 33 | 34 | ## Key Projects 35 | 36 | ### Voice Recognition Web App 37 | - Interactive web application with dark/light theme toggle 38 | - Speech-to-text functionality using browser APIs 39 | - Responsive design with visual feedback 40 | - Files: `index.html`, `styles.css`, `script.js` 41 | 42 | ### Algorithm Implementations 43 | - Graph traversal with BFS/DFS (`graphchallange.py`) 44 | - Array manipulation algorithms (`arrchallange.py`) 45 | - Roman numeral conversion (`roman.py`) 46 | - Dynamic programming solutions (`practice5.py`) 47 | - Merge sort implementation (`mergesort.py`) 48 | - Maximum subarray problem (`maximumSubArray.py`) 49 | 50 | ### ASCII Art Tools 51 | - ASCII art converter (`ascii_art_converter.py`) 52 | - ASCII video generator (`ascii_video.py`) 53 | - Pre-generated ASCII art examples 54 | 55 | ### Fibonacci Visualizations 56 | - Graphical spiral representations (`fibonacci.py`) 57 | - Generated GIF animations in outputs folder 58 | - Mathematical implementations 59 | 60 | ### Utilities 61 | - Temperature converter (`temperature_converter.py`) 62 | - Calculator application (`calculator.py`) 63 | - Encryption/decryption tools (`encrypt.py`, `encrytionDecryption.py`, `sha512.py`) 64 | - Random luck generator (`random_luck.py`) 65 | 66 | ### Database Application 67 | - MySQL-based shopping system 68 | - User authentication and account management 69 | - Product inventory and transaction processing 70 | - Random discount generation system 71 | 72 | ## Learning Resources 73 | 74 | - Comprehensive DSA notes available in DSA_notes.txt 75 | - Practice problems with solutions in the classwork directory 76 | - Algorithm design techniques PDF 77 | - Python cheat sheet for quick reference 78 | 79 | ## Technologies Used 80 | 81 | - Python 3.x 82 | - Java 83 | - HTML/CSS/JavaScript 84 | - MySQL database connectivity 85 | - Web APIs (Speech Recognition) 86 | - Data structures and algorithms 87 | 88 | ## Getting Started 89 | 90 | 1. Clone the repository 91 | 2. Install required dependencies: 92 | ```bash 93 | pip install mysql-connector-python pyfiglet 94 | ``` 95 | 3. Run desired scripts using Python: 96 | ```bash 97 | python classwork/practice1.py 98 | ``` 99 | 100 | ## Note 101 | 102 | This repository represents a collection of coding exercises, projects, and learning materials. Individual files may have specific requirements or dependencies. 103 | 104 | Last updated: April 20, 2025 -------------------------------------------------------------------------------- /classwork/datascience.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | 3 | # Create a sample DataFrame 4 | data = { 5 | 'Name': ['John', 'Emma', 'Alex', 'Sarah'], 6 | 'Age': [25, 28, 22, 30], 7 | 'City': ['New York', 'London', 'Paris', 'Tokyo'] 8 | } 9 | 10 | # Create DataFrame 11 | df = pd.DataFrame(data) 12 | 13 | # Display the DataFrame 14 | print("Original DataFrame:") 15 | print(df) 16 | 17 | # Basic operations 18 | print("\nFirst 2 rows:") 19 | print(df.head(2)) 20 | 21 | # Get basic statistics 22 | print("\nBasic statistics of Age:") 23 | print(df['Age'].describe()) 24 | 25 | # Filter data 26 | print("\nPeople older than 25:") 27 | print(df[df['Age'] > 25]) -------------------------------------------------------------------------------- /classwork/new_file.py: -------------------------------------------------------------------------------- 1 | print("Hello! This is a nice code.") 2 | #testing if GitHub commits works from GitHub mobile 3 | -------------------------------------------------------------------------------- /classwork/practice1.py: -------------------------------------------------------------------------------- 1 | def rotate_array(arr=None, d=1): 2 | if not arr: 3 | return [] 4 | 5 | n = len(arr) 6 | if n == 0 or d == 0: 7 | return arr 8 | 9 | d = d % n 10 | 11 | return arr[-d:] + arr[:-d] 12 | 13 | if __name__ == "__main__": 14 | # Test cases 15 | test_array = [1, 2, 3, 4, 5] 16 | print(f"Original array: {test_array}") 17 | print(f"Rotated by 2: {rotate_array(test_array, 2)}") # Output: [4, 5, 1, 2, 3] -------------------------------------------------------------------------------- /classwork/practice11.py: -------------------------------------------------------------------------------- 1 | def dec_to_n_base(n, num): 2 | 3 | if num == 0: 4 | return "0" 5 | 6 | # Digits used for representation (0-9, A-Z) 7 | digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" 8 | 9 | # Validate base is within allowed range 10 | if n < 2 or n > len(digits): 11 | raise ValueError(f"Base must be between 2 and {len(digits)}") 12 | 13 | result = [] 14 | while num > 0: 15 | result.append(digits[num % n]) 16 | num //= n 17 | return "".join(reversed(result)) 18 | 19 | # Test cases 20 | if __name__ == "__main__": 21 | print(f"Decimal 10 in binary (base 2): {dec_to_n_base(2, 10)}") # Should output: 1010 22 | print(f"Decimal 15 in hex (base 16): {dec_to_n_base(16, 15)}") # Should output: F 23 | print(f"Decimal 255 in hex (base 16): {dec_to_n_base(16, 255)}") # Should output: FF 24 | print(f"Decimal 125 in base 7: {dec_to_n_base(7, 125)}") # Should output: 236 25 | print(f"Decimal 0 in any base: {dec_to_n_base(16, 0)}") # Should output: 0 26 | -------------------------------------------------------------------------------- /classwork/practice12.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | #Write a python code to arrange the elements of an array based on the rand( frequency of their appearence.) 4 | 5 | arr = [1, 2, 3, 2, 4, 3, 2] 6 | freq = Counter(arr) 7 | result = sorted(arr, key=lambda x: freq[x], reverse=True) 8 | print(result) -------------------------------------------------------------------------------- /classwork/practice2.py: -------------------------------------------------------------------------------- 1 | def rotate_from_index(arr, d): 2 | 3 | # Handle edge cases 4 | if not arr or d >= len(arr) or d < 0: 5 | return arr 6 | 7 | # Store value at d 8 | temp = arr[d] 9 | 10 | # Shift elements left 11 | for i in range(d, len(arr)-1): 12 | arr[i] = arr[i+1] 13 | 14 | # Place temp at end 15 | arr[-1] = temp 16 | 17 | return arr 18 | 19 | # Test cases 20 | if __name__ == "__main__": 21 | test_array = [1, 2, 3, 4, 5] 22 | print(f"Original array: {test_array}") 23 | print(f"After rotation from index 2: {rotate_from_index(test_array.copy(), 2)}") # [1, 2, 4, 5, 3] 24 | 25 | # Edge cases 26 | print(f"Empty array: {rotate_from_index([], 1)}") # [] 27 | print(f"Invalid index: {rotate_from_index([1, 2, 3], 5)}") # [1, 2, 3] -------------------------------------------------------------------------------- /classwork/practice3.py: -------------------------------------------------------------------------------- 1 | def find_single_person(arr): 2 | 3 | result = 0 4 | for num in arr: 5 | result ^= num 6 | return result 7 | 8 | # Test cases 9 | if __name__ == "__main__": 10 | test_cases = [ 11 | [1, 2, 3, 2, 1], # should return 3 12 | [5, 5, 8, 8, 9], # should return 9 13 | [1, 1, 2], # should return 2 14 | ] 15 | 16 | for test in test_cases: 17 | print(f"Party: {test}") 18 | print(f"Single person: {find_single_person(test)}\n") -------------------------------------------------------------------------------- /classwork/practice4.py: -------------------------------------------------------------------------------- 1 | def move_hashes_to_front(s): 2 | hash_count = s.count('#') 3 | s = s.replace('#', '') 4 | result = '#' * hash_count + s 5 | return result 6 | 7 | # Test case 8 | input_string = "move#hash#to#the#front" 9 | output_string = move_hashes_to_front(input_string) 10 | print(output_string) -------------------------------------------------------------------------------- /classwork/practice5.py: -------------------------------------------------------------------------------- 1 | def max_steal(houses): 2 | if not houses: 3 | return 0 4 | if len(houses) == 1: 5 | return houses[0] 6 | 7 | prev1 = 0 8 | prev2 = 0 9 | 10 | for money in houses: 11 | current = max(prev1, prev2 + money) 12 | prev2 = prev1 13 | prev1 = current 14 | 15 | return prev1 16 | 17 | # Test case 18 | houses = [100, 4000, 300, 4000, 9000, 600] 19 | print(max_steal(houses)) # Output: 13000 -------------------------------------------------------------------------------- /classwork/practice6.py: -------------------------------------------------------------------------------- 1 | def has_pair_with_sum(arr, target): 2 | seen = set() 3 | for num in arr: 4 | complement = target - num 5 | if complement in seen: 6 | return True, (complement, num) 7 | seen.add(num) 8 | return False, None 9 | 10 | # Test case 11 | arr = [0, -1, 2, -3, 1, -4] 12 | target = -2 13 | found, pair = has_pair_with_sum(arr, target) 14 | print(f"Found pair: {found}") # Expected output: True 15 | print(f"Numbers: {pair}") # Expected output: (-3, 1) -------------------------------------------------------------------------------- /classwork/practice7.py: -------------------------------------------------------------------------------- 1 | def compress_string(s): 2 | # Dictionary to store character frequencies 3 | char_freq = {} 4 | 5 | # Parse the input string 6 | i = 0 7 | while i < len(s): 8 | # Get the character 9 | char = s[i] 10 | 11 | # Find the number that follows 12 | i += 1 13 | num = "" 14 | while i < len(s) and s[i].isdigit(): 15 | num += s[i] 16 | i += 1 17 | 18 | # Add to dictionary, combining frequencies if char exists 19 | freq = int(num) 20 | char_freq[char] = char_freq.get(char, 0) + freq 21 | 22 | # Create compressed string with sorted characters 23 | result = "" 24 | for char in sorted(char_freq.keys()): 25 | result += char + str(char_freq[char]) 26 | 27 | return result 28 | 29 | # Test cases 30 | test_strings = [ 31 | "a3b2c1a2", # Should become "a5b2c1" 32 | "b1a2c3b4", # Should become "a2b5c3" 33 | "z2a1z1", # Should become "a1z3" 34 | ] 35 | 36 | for test in test_strings: 37 | print(f"Input: {test}") 38 | print(f"Output: {compress_string(test)}\n") 39 | -------------------------------------------------------------------------------- /classwork/practice8.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, val): 3 | self.val = val 4 | self.next = None 5 | 6 | def reverse_list(head): 7 | prev = None 8 | current = head 9 | while current: 10 | nxt = current.next 11 | current.next = prev 12 | prev = current 13 | current = nxt 14 | return prev -------------------------------------------------------------------------------- /classwork/practice9.py: -------------------------------------------------------------------------------- 1 | def product_smallestpair(target_sum, arr): 2 | if not arr: 3 | return -1 4 | if len(arr) < 2: 5 | return 0 6 | 7 | arr.sort() 8 | if arr[0] + arr[1] <= target_sum: 9 | return arr[0] * arr[1] 10 | return 0 11 | 12 | # Test case 13 | if __name__ == "__main__": 14 | print(product_smallestpair(5, [1, 2, 3, 4])) # Expected output: 2 (1*2) -------------------------------------------------------------------------------- /classwork/question10.py: -------------------------------------------------------------------------------- 1 | def robin_karp(text: str, pattern: str): 2 | if not pattern: 3 | return [0] if text else [] 4 | base = 256 5 | m = len(pattern) 6 | n = len(text) 7 | h = 1 8 | for _ in range(m - 1): 9 | h = (h * base) 10 | p_hash = 0 11 | t_hash = 0 12 | result = [] 13 | for i in range(m): 14 | p_hash = (base * p_hash + ord(pattern[i])) 15 | t_hash = (base * t_hash + ord(text[i])) 16 | for i in range(n - m + 1): 17 | if p_hash == t_hash: 18 | if text[i:i+m] == pattern: 19 | result.append(i) 20 | if i < n - m: 21 | t_hash = (base * (t_hash - ord(text[i]) * h) + ord(text[i + m])) 22 | return result 23 | 24 | print(robin_karp("AABAACAADAABAABA", "AABA")) # Expected output: [0, 9, 12] -------------------------------------------------------------------------------- /classwork/questions.txt: -------------------------------------------------------------------------------- 1 | Question 1 2 | Given an inteeger array of size n, task is to rotate the array, elements to the right by d positions. 3 | 4 | Question 2 5 | givven an array of integers and a index position d, rotate the array one elements from dth position to the end 6 | 7 | 8 | Question 3 9 | in a party of N people each person is denoted by an integer, couples are presented by the same number. find out the only single person at the party of couple 10 | 11 | test case 12 | 13 | 1 2 3 2 1 output 3 14 | 15 | 16 | Question 4 17 | You have to write a function that will accept a string which length is "len", the string has some "#", in it. You 18 | have to move all the hashes to the front of the string and return the whole string back and print it 19 | TEST CASE: 20 | > move#hash#to#the#front 21 | output: ####movehashtothefront 22 | 23 | Question 5 24 | There are n houses built in a line, each of which contains some money. A robber wants 25 | to steal money from the houses but he cant steal from two consecutive/adjacent houses. 26 | the task is to find the maximum amount of money which can be stolen 27 | 28 | test case: 29 | A 100 B 200 C 300 D 400 E 500 F 600 30 | 31 | 32 | Given an array arr[] of n integers and a target value, the task is to find weather there is a pair of elements 33 | in the array whhose sum is equal to the target. 34 | 35 | arr[] = [0, -1, 2, -3, 1] 36 | 37 | write a python code to rotate a matrix by 90 degree 38 | 39 | question 7 40 | Consider a string , S , that is a series of character, each followed by its frequency as an integer 41 | the string is not compresed correctly, so there may be multiple occurances of the same character. A propery 42 | of ea compressed string will consist of one instanc ch character in alphabetical order followed by total count 43 | of that character withing the string 44 | 45 | Question 8 46 | Given a singly linked list, write a function to reverse the linked list. The function should take the head of the linked list as input and return the new head of the reversed linked list. 47 | 48 | Example: 49 | Input: 1 -> 2 -> 3 -> 4 -> 5 -> NULL 50 | Output: 5 -> 4 -> 3 -> 2 -> 1 -> NULL 51 | 52 | 53 | Question 9 54 | 55 | the function def product smallestpair(sun arr) accepts an integer array of set n implement 56 | the function to fin the pair(arr[i] arr[k]) where i = k, such that arr[i] and arr[k] 57 | are the least two elements of the array(arr[i]+ arr[k]) <= sum and return the product element of the 58 | pair. Note return -1 if array is empty or if n<2 return 0 if no such pair found. 59 | 60 | question 10 61 | 62 | implement robin-karp algorithim 63 | 64 | 65 | N base notion is a system for writing numbers which uses only n different symbols. 66 | these symbols are the first n symbols from the given notation list (including the symbol for o) 67 | decimal to n based notation are (0:0, 1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:9, 68 | 10:A, 11:B, and so on upto 35:Z) 69 | 70 | implement the following function char* DectoNBase(int n , int num): 71 | the funtion accept a positive int n and num implement the function to calculate the n base equivalent of 72 | num and return the same as a string 73 | 74 | 75 | the steps are 76 | devide the decimal no. by N treat the division as integer division 77 | write the remainder in n based notation. 78 | divide the quotient again by n. 79 | repeat step 2 and 3 untill the quotient is 0. 80 | 81 | Question 12. 82 | 83 | Write a python code to arrange the elements of an array based on the rand( frequency of their appearence.) -------------------------------------------------------------------------------- /miscelenious/DoubleLinkedList$Node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anubhob435/pythonFiles/e8fe21829ff9f4e194e4f6bd8ba913539385d73f/miscelenious/DoubleLinkedList$Node.class -------------------------------------------------------------------------------- /miscelenious/DoubleLinkedList.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anubhob435/pythonFiles/e8fe21829ff9f4e194e4f6bd8ba913539385d73f/miscelenious/DoubleLinkedList.class -------------------------------------------------------------------------------- /miscelenious/DoubleLinkedList.java: -------------------------------------------------------------------------------- 1 | public class DoubleLinkedList { 2 | 3 | private static class Node { 4 | E element; 5 | Node prev; 6 | Node next; 7 | 8 | public Node(E element, Node prev, Node next) { 9 | this.element = element; 10 | this.prev = prev; 11 | this.next = next; 12 | } 13 | } 14 | 15 | private Node head; 16 | private Node tail; 17 | private int size; 18 | 19 | public DoubleLinkedList() { 20 | head = null; 21 | tail = null; 22 | size = 0; 23 | } 24 | 25 | public int size() { 26 | return size; 27 | } 28 | 29 | public boolean isEmpty() { 30 | return size == 0; 31 | } 32 | 33 | public void addFirst(E element) { 34 | Node newNode = new Node<>(element, null, head); 35 | if (head != null) { 36 | head.prev = newNode; 37 | } else { 38 | tail = newNode; 39 | } 40 | head = newNode; 41 | size++; 42 | } 43 | 44 | public void addLast(E element) { 45 | Node newNode = new Node<>(element, tail, null); 46 | if (tail != null) { 47 | tail.next = newNode; 48 | } else { 49 | head = newNode; 50 | } 51 | tail = newNode; 52 | size++; 53 | } 54 | 55 | public E removeFirst() { 56 | if (isEmpty()) { 57 | return null; 58 | } 59 | 60 | E element = head.element; 61 | head = head.next; 62 | 63 | if (head != null) { 64 | head.prev = null; 65 | } else { 66 | tail = null; 67 | } 68 | 69 | size--; 70 | return element; 71 | } 72 | 73 | public E removeLast() { 74 | if (isEmpty()) { 75 | return null; 76 | } 77 | 78 | E element = tail.element; 79 | tail = tail.prev; 80 | 81 | if (tail != null) { 82 | tail.next = null; 83 | } else { 84 | head = null; 85 | } 86 | 87 | size--; 88 | return element; 89 | } 90 | 91 | public void display() { 92 | Node current = head; 93 | while (current != null) { 94 | System.out.print(current.element + " <-> "); 95 | current = current.next; 96 | } 97 | System.out.println("null"); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /miscelenious/LinkedList.java: -------------------------------------------------------------------------------- 1 | class LinkedList { 2 | // Node class for linked list 3 | class Node { 4 | int data; 5 | Node next; 6 | 7 | public Node(int data) { 8 | this.data = data; 9 | this.next = null; 10 | } 11 | } 12 | 13 | private Node head; 14 | 15 | // Constructor 16 | public LinkedList() { 17 | this.head = null; 18 | } 19 | 20 | // Add a node at the end 21 | public void append(int data) { 22 | if (head == null) { 23 | head = new Node(data); 24 | return; 25 | } 26 | 27 | Node current = head; 28 | while (current.next != null) { 29 | current = current.next; 30 | } 31 | current.next = new Node(data); 32 | } 33 | 34 | // Add a node at the beginning 35 | public void prepend(int data) { 36 | Node newNode = new Node(data); 37 | newNode.next = head; 38 | head = newNode; 39 | } 40 | 41 | // Insert a node after a given node 42 | public void insertAfter(Node prevNode, int data) { 43 | if (prevNode == null) { 44 | System.out.println("The given previous node cannot be null"); 45 | return; 46 | } 47 | 48 | Node newNode = new Node(data); 49 | newNode.next = prevNode.next; 50 | prevNode.next = newNode; 51 | } 52 | 53 | // Delete a node with given key 54 | public void deleteNode(int key) { 55 | Node temp = head, prev = null; 56 | 57 | // If head node itself holds the key to be deleted 58 | if (temp != null && temp.data == key) { 59 | head = temp.next; 60 | return; 61 | } 62 | 63 | // Search for the key to be deleted 64 | while (temp != null && temp.data != key) { 65 | prev = temp; 66 | temp = temp.next; 67 | } 68 | 69 | // If key was not present in linked list 70 | if (temp == null) return; 71 | 72 | // Unlink the node from linked list 73 | prev.next = temp.next; 74 | } 75 | 76 | // Search a node 77 | public boolean search(int key) { 78 | Node current = head; 79 | while (current != null) { 80 | if (current.data == key) { 81 | return true; 82 | } 83 | current = current.next; 84 | } 85 | return false; 86 | } 87 | 88 | // Print the linked list 89 | public void printList() { 90 | Node current = head; 91 | System.out.print("LinkedList: "); 92 | while (current != null) { 93 | System.out.print(current.data + " "); 94 | current = current.next; 95 | } 96 | System.out.println(); 97 | } 98 | 99 | // Get the size of linked list 100 | public int size() { 101 | int count = 0; 102 | Node current = head; 103 | while (current != null) { 104 | count++; 105 | current = current.next; 106 | } 107 | return count; 108 | } 109 | 110 | // Get node at specific index 111 | public Node getAt(int index) { 112 | Node current = head; 113 | int count = 0; 114 | 115 | while (current != null) { 116 | if (count == index) { 117 | return current; 118 | } 119 | count++; 120 | current = current.next; 121 | } 122 | 123 | return null; 124 | } 125 | 126 | // Main method for testing 127 | public static void main(String[] args) { 128 | LinkedList list = new LinkedList(); 129 | 130 | // Append elements 131 | list.append(1); 132 | list.append(2); 133 | list.append(3); 134 | list.printList(); 135 | 136 | // Prepend element 137 | list.prepend(0); 138 | list.printList(); 139 | 140 | // Insert after second node 141 | list.insertAfter(list.getAt(1), 5); 142 | list.printList(); 143 | 144 | // Delete node 145 | list.deleteNode(2); 146 | list.printList(); 147 | 148 | // Search 149 | System.out.println("Search for 5: " + list.search(5)); 150 | System.out.println("Search for 2: " + list.search(2)); 151 | 152 | // Size 153 | System.out.println("Size of linked list: " + list.size()); 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /miscelenious/Practice.jav: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class Practice { 3 | 4 | public static boolean isprime(int n){ 5 | 6 | boolean isprime= true; 7 | 8 | if(n <= 1){ 9 | return false; 10 | } 11 | else if(n == 2){ 12 | return true; 13 | } 14 | else{ 15 | for (int i = 2; i < n; i++) { 16 | 17 | if (n % i == 0) { 18 | isprime = false; 19 | break; 20 | } 21 | 22 | } 23 | } 24 | return isprime; 25 | } 26 | 27 | 28 | public static void main(String [] args){ 29 | 30 | 31 | } 32 | 33 | 34 | } 35 | 36 | 37 | -------------------------------------------------------------------------------- /miscelenious/Screenshot.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anubhob435/pythonFiles/e8fe21829ff9f4e194e4f6bd8ba913539385d73f/miscelenious/Screenshot.jpg -------------------------------------------------------------------------------- /miscelenious/Structure.py: -------------------------------------------------------------------------------- 1 | x = [] 2 | n = int(input("how many elements")) 3 | for i in range (0, n): 4 | y = int(input("enter element: ") 5 | x.append(y) 6 | 7 | print(x) -------------------------------------------------------------------------------- /miscelenious/arraychallange.py: -------------------------------------------------------------------------------- 1 | def ArrayChallenge(num): 2 | def get_digits(n): 3 | return [int(d) for d in str(n)] 4 | 5 | digits = get_digits(num) # Extract initial digits 6 | multiplications = 0 7 | 8 | while True: 9 | # Check for adjacent duplicate numbers 10 | for i in range(len(digits) - 1): 11 | if digits[i] == digits[i + 1]: # Found adjacent duplicates 12 | return multiplications 13 | 14 | # Pick the first digit as the multiplier 15 | multiplier = digits[0] 16 | num *= multiplier # Multiply num 17 | multiplications += 1 18 | 19 | # Extract new digits and replace the existing list 20 | digits = get_digits(num) # Replace digits with new digits 21 | 22 | # Test case 23 | num = 8 24 | print(ArrayChallenge(num)) # Output should be 3 -------------------------------------------------------------------------------- /miscelenious/arrchallange.py: -------------------------------------------------------------------------------- 1 | def ArrayChallenge(num): 2 | def get_digits(n): 3 | return [int(d) for d in str(n)] 4 | 5 | digits = get_digits(num) 6 | multiplications = 0 7 | 8 | while True: 9 | # Check for adjacent duplicates 10 | for i in range(len(digits) - 1): 11 | if digits[i] == digits[i + 1]: 12 | return multiplications 13 | 14 | # If no duplicates, multiply by one of its digits 15 | # Choose the first digit for simplicity 16 | multiplier = digits[0] 17 | new_num = num * multiplier 18 | new_digits = get_digits(new_num) 19 | 20 | # Append new digits to the list 21 | digits.extend(new_digits) 22 | num = new_num 23 | multiplications += 1 24 | 25 | # Test cases 26 | #print(ArrayChallenge(8)) # Output: 3 27 | print(ArrayChallenge(198)) # Output: 2 28 | #print(ArrayChallenge(134)) # Output: 1 29 | #print(ArrayChallenge(46)) # Output: 2 -------------------------------------------------------------------------------- /miscelenious/ascii_art.txt: -------------------------------------------------------------------------------- 1 | @@@@@@@@@@@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | @@@@@@@@@@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 3 | @@@@@@@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 4 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 5 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 6 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 7 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 8 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 9 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 10 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 11 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 12 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%+. .-#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 13 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#::+%%+. *%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 14 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%* -... .+* *%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 15 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%* -. . .+* *%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 16 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#:.+#%+. *%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 17 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%+. .-#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 18 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 19 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 20 | @@@@@@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 21 | @@@@@@@@@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 22 | @@@@@@@@@@@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@@@@@ 23 | @@@@@@@@@@@@@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@@@@@@@@@@@@@@ 24 | @@@@@@@@@@@@@@@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 25 | @@@@@@@@@@@@@@@@@@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 26 | @@@@@@@@@@@@@@@@@@@@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 27 | @@@@@@@@@@@@@@@@@@@@@@@%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 28 | @@@@@@@@@@@@@@@@@@@@@@@@@%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 29 | -------------------------------------------------------------------------------- /miscelenious/ascii_art_converter.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | import sys 3 | 4 | def convert_to_ascii(image_path, width=100, height=None): 5 | """ 6 | Convert an image to ASCII art. 7 | 8 | Args: 9 | image_path (str): Path to the image file 10 | width (int): Width of the output ASCII art (in characters) 11 | height (int): Height of the output ASCII art (in lines) 12 | If None, it's calculated to maintain aspect ratio 13 | 14 | Returns: 15 | str: ASCII art representation of the image 16 | """ 17 | try: 18 | # Open the image 19 | img = Image.open(image_path) 20 | 21 | # Calculate height to maintain aspect ratio if not provided 22 | if height is None: 23 | aspect_ratio = img.height / img.width 24 | height = int(width * aspect_ratio * 0.5) # 0.5 factor because characters are taller than wide 25 | 26 | # Resize the image 27 | img = img.resize((width, height)) 28 | 29 | # Convert to grayscale 30 | img = img.convert('L') 31 | 32 | # ASCII characters from darkest to lightest 33 | ascii_chars = '@%#*+=-:. ' 34 | 35 | # Convert pixels to ASCII characters 36 | pixels = list(img.getdata()) 37 | ascii_art = '' 38 | for i, pixel in enumerate(pixels): 39 | # Map pixel value (0-255) to ASCII character 40 | ascii_index = int(pixel * len(ascii_chars) / 256) 41 | ascii_art += ascii_chars[ascii_index] 42 | if (i + 1) % width == 0: 43 | ascii_art += '\n' 44 | 45 | return ascii_art 46 | 47 | except Exception as e: 48 | return f"Error: {str(e)}" 49 | 50 | def main(): 51 | if len(sys.argv) < 2: 52 | print("Usage: python ascii_art_converter.py [width] [height]") 53 | return 54 | 55 | image_path = sys.argv[1] 56 | width = int(sys.argv[2]) if len(sys.argv) > 2 else 100 57 | height = int(sys.argv[3]) if len(sys.argv) > 3 else None 58 | 59 | ascii_art = convert_to_ascii(image_path, width, height) 60 | print(ascii_art) 61 | 62 | # Optionally save to file 63 | save_option = input("Do you want to save the ASCII art to a file? (y/n): ") 64 | if save_option.lower() == 'y': 65 | output_file = input("Enter output file name (default: ascii_art.txt): ") or "ascii_art.txt" 66 | with open(output_file, 'w') as f: 67 | f.write(ascii_art) 68 | print(f"ASCII art saved to {output_file}") 69 | 70 | if __name__ == "__main__": 71 | main() 72 | -------------------------------------------------------------------------------- /miscelenious/ascii_video.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | import os 4 | import time 5 | from datetime import datetime 6 | from PIL import Image, ImageDraw, ImageFont 7 | import moviepy.editor as mp # Updated import for better compatibility 8 | 9 | # Check for CUDA availability at the start 10 | use_cuda = False 11 | try: 12 | if cv2.cuda.getCudaEnabledDeviceCount() > 0: 13 | use_cuda = True 14 | print("CUDA is available. Attempting to use GPU for OpenCV operations.") 15 | else: 16 | print("CUDA not available or OpenCV not built with CUDA support. Using CPU for OpenCV operations.") 17 | except AttributeError: 18 | print("cv2.cuda module not found. Using CPU for OpenCV operations.") 19 | 20 | def get_ascii_char(pixel_value): 21 | # ASCII characters from darkest to lightest 22 | ascii_chars = "@%#*+=-:. " 23 | # Map pixel value (0-255) to ASCII character 24 | index = int(pixel_value / 255 * (len(ascii_chars) - 1)) 25 | return ascii_chars[index] 26 | 27 | def frame_to_ascii(frame, width=100): 28 | # Calculate height to maintain aspect ratio 29 | aspect_ratio = frame.shape[1] / frame.shape[0] 30 | height = int(width / aspect_ratio / 2) # Dividing by 2 because characters are taller than wide 31 | 32 | resized = None # Initialize resized variable 33 | 34 | if use_cuda: 35 | try: 36 | # Upload frame to GPU 37 | gpu_frame = cv2.cuda_GpuMat() 38 | gpu_frame.upload(frame) 39 | 40 | # Convert color on GPU 41 | gpu_gray = cv2.cuda.cvtColor(gpu_frame, cv2.COLOR_BGR2GRAY) 42 | 43 | # Resize on GPU 44 | gpu_resized = cv2.cuda.resize(gpu_gray, (width, height)) 45 | 46 | # Download result back to CPU 47 | resized = gpu_resized.download() 48 | 49 | except cv2.error as e: 50 | print(f"CUDA error during processing: {e}. Falling back to CPU for this frame.") 51 | # Fallback to CPU if CUDA operations fail for this frame 52 | gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 53 | resized = cv2.resize(gray, (width, height)) 54 | except Exception as e: # Catch other potential CUDA-related errors 55 | print(f"An unexpected error occurred with CUDA: {e}. Falling back to CPU for this frame.") 56 | gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 57 | resized = cv2.resize(gray, (width, height)) 58 | 59 | # If CUDA is not used or fallback occurred 60 | if resized is None: 61 | # CPU implementation 62 | gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 63 | resized = cv2.resize(gray, (width, height)) 64 | 65 | # Convert the pixels to ASCII characters 66 | ascii_frame = "" 67 | for row in resized: 68 | for pixel in row: 69 | ascii_frame += get_ascii_char(pixel) 70 | ascii_frame += "\n" 71 | 72 | return ascii_frame 73 | 74 | def ascii_to_image(ascii_text, font_size=15, bg_color=(0, 0, 0), text_color=(255, 255, 255)): 75 | # Calculate image dimensions based on ASCII text 76 | lines = ascii_text.split('\n') 77 | char_width = font_size / 2 78 | img_width = int(max(len(line) for line in lines) * char_width) 79 | img_height = int(len(lines) * font_size) 80 | 81 | # Create a new image 82 | img = Image.new('RGB', (img_width, img_height), color=bg_color) 83 | draw = ImageDraw.Draw(img) 84 | 85 | # Try to load a monospace font (will fall back to default if not available) 86 | try: 87 | font = ImageFont.truetype("Courier", font_size) 88 | except IOError: 89 | font = ImageFont.load_default() 90 | 91 | # Draw the ASCII art on the image 92 | y = 0 93 | for line in lines: 94 | draw.text((0, y), line, font=font, fill=text_color) 95 | y += font_size 96 | 97 | return np.array(img) 98 | 99 | def create_output_dir(): 100 | # Create output directory if it doesn't exist 101 | output_dir = os.path.join(os.path.dirname(__file__), "outputs") 102 | if not os.path.exists(output_dir): 103 | os.makedirs(output_dir) 104 | return output_dir 105 | 106 | def process_video(video_path, output_width=100, fps=None): 107 | print(f"Processing video: {video_path}") 108 | 109 | # Extract filename without extension 110 | video_filename = os.path.basename(video_path) 111 | video_name = os.path.splitext(video_filename)[0] 112 | 113 | # Create timestamp for unique output filenames 114 | timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") 115 | 116 | # Create output directory 117 | output_dir = create_output_dir() 118 | 119 | # Output path for ASCII video 120 | output_path = os.path.join(output_dir, f"{video_name}_ascii_{timestamp}.mp4") 121 | 122 | # Load the video 123 | video_clip = mp.VideoFileClip(video_path) 124 | 125 | # Use original fps if not specified 126 | if fps is None: 127 | fps = video_clip.fps 128 | 129 | # Extract audio 130 | audio = video_clip.audio 131 | 132 | # Process frames and convert to ASCII images 133 | print("Converting frames to ASCII...") 134 | 135 | # Temporary list to store the ASCII frames 136 | ascii_frames = [] 137 | 138 | # Get total number of frames for progress reporting 139 | total_frames = int(video_clip.duration * video_clip.fps) 140 | processed_frames = 0 141 | 142 | # Process each frame 143 | for frame in video_clip.iter_frames(fps=fps): 144 | # Convert frame to ASCII text (will use GPU if available and working) 145 | ascii_text = frame_to_ascii(frame, width=output_width) 146 | 147 | # Convert ASCII text to image 148 | ascii_image = ascii_to_image(ascii_text) 149 | 150 | # Add frame to list 151 | ascii_frames.append(ascii_image) 152 | 153 | # Update progress 154 | processed_frames += 1 155 | if processed_frames % 10 == 0: 156 | print(f"Processed {processed_frames}/{total_frames} frames ({processed_frames/total_frames*100:.1f}%)") 157 | 158 | print("Creating video from ASCII frames...") 159 | # Create a video from the ASCII frames 160 | ascii_clip = mp.ImageSequenceClip(ascii_frames, fps=fps) 161 | 162 | # Add the original audio to the ASCII video 163 | if audio is not None: 164 | ascii_clip = ascii_clip.set_audio(audio) 165 | 166 | # Write the result to file 167 | print(f"Writing ASCII video to {output_path}") 168 | ascii_clip.write_videofile(output_path, codec='libx264') 169 | 170 | # Clean up 171 | video_clip.close() 172 | if audio is not None: 173 | audio.close() 174 | ascii_clip.close() 175 | 176 | print(f"ASCII video saved to {output_path}") 177 | return output_path 178 | 179 | def main(): 180 | # Default sample video path 181 | default_video = os.path.join(os.path.dirname(os.path.dirname(__file__)), "videos", "sample1.mp4") 182 | 183 | # Get user input 184 | video_path = input(f"Enter path to video file (or press Enter to use sample: {default_video}): ") 185 | if not video_path: 186 | video_path = default_video 187 | 188 | if not os.path.exists(video_path): 189 | print(f"Error: File {video_path} not found.") 190 | return 191 | 192 | # Ask for ASCII width 193 | try: 194 | width = input("Enter ASCII width (default: 100): ") 195 | width = int(width) if width else 100 196 | except ValueError: 197 | print("Invalid input, using default width of 100") 198 | width = 100 199 | 200 | # Ask for FPS 201 | try: 202 | fps_input = input("Enter desired FPS (press Enter to use original): ") 203 | fps = int(fps_input) if fps_input else None 204 | except ValueError: 205 | print("Invalid input, using original FPS") 206 | fps = None 207 | 208 | # Process the video 209 | start_time = time.time() 210 | output_file = process_video(video_path, output_width=width, fps=fps) 211 | end_time = time.time() 212 | 213 | print(f"Processing completed in {end_time - start_time:.2f} seconds.") 214 | print(f"ASCII video saved to: {output_file}") 215 | 216 | if __name__ == "__main__": 217 | main() -------------------------------------------------------------------------------- /miscelenious/challange32.py: -------------------------------------------------------------------------------- 1 | print("Hello World") 2 | -------------------------------------------------------------------------------- /miscelenious/data2.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | import matplotlib.pyplot as plt 4 | 5 | def is_prime(n): 6 | if n < 2: 7 | return False 8 | for i in range(2, int(np.sqrt(n)) + 1): 9 | if n % i == 0: 10 | return False 11 | return True 12 | 13 | # Generate prime numbers up to 100 14 | numbers = range(2, 101) 15 | primes = [num for num in numbers if is_prime(num)] 16 | 17 | # Create the plot 18 | plt.figure(figsize=(10, 6)) 19 | plt.plot(primes, [1] * len(primes), 'ro', markersize=8) 20 | plt.grid(True) 21 | plt.title('Prime Numbers up to 100') 22 | plt.xlabel('Numbers') 23 | plt.yticks([]) # Hide y-axis ticks 24 | plt.show() -------------------------------------------------------------------------------- /miscelenious/deployment.py: -------------------------------------------------------------------------------- 1 | #deploying repo 2 | -------------------------------------------------------------------------------- /miscelenious/doughnut.py: -------------------------------------------------------------------------------- 1 | import os 2 | import math 3 | import time 4 | import numpy as np 5 | 6 | def clear_screen(): 7 | os.system('cls' if os.name == 'nt' else 'clear') 8 | 9 | def render_frame(A, B): 10 | # Precompute sines and cosines of A and B 11 | cosA, sinA = math.cos(A), math.sin(A) 12 | cosB, sinB = math.cos(B), math.sin(B) 13 | 14 | # Screen dimensions 15 | width, height = 80, 24 16 | 17 | # Buffer for the output 18 | output = [[' ' for _ in range(width)] for _ in range(height)] 19 | 20 | # Z-buffer for depth 21 | zbuffer = [[0 for _ in range(width)] for _ in range(height)] 22 | 23 | # Donut parameters 24 | R1 = 1 # Distance from center to center of torus tube 25 | R2 = 2 # Radius of torus tube 26 | K2 = 5 # Distance from viewer to donut 27 | K1 = width * K2 * 3 / (8 * (R1 + R2)) # Scaling factor 28 | 29 | # Rotation around the y-axis (vertical) 30 | for theta in np.linspace(0, 2 * math.pi, 50): 31 | cosTheta, sinTheta = math.cos(theta), math.sin(theta) 32 | 33 | # Rotation around the x-axis (horizontal) 34 | for phi in np.linspace(0, 2 * math.pi, 20): 35 | cosPhi, sinPhi = math.cos(phi), math.sin(phi) 36 | 37 | # 3D coordinates of the point on the torus 38 | x = R2 * cosTheta + R1 39 | y = R2 * sinTheta 40 | 41 | # 3D rotation 42 | x1 = x * cosB - y * sinB 43 | y1 = x * sinB + y * cosB 44 | z1 = R2 * cosPhi + R1 45 | 46 | # Rotate around x-axis 47 | y2 = y1 * cosA - z1 * sinA 48 | z2 = y1 * sinA + z1 * cosA 49 | 50 | # 3D to 2D projection 51 | z = 1 / (K2 + z2) 52 | x3 = int(width / 2 + K1 * x1 * z) 53 | y3 = int(height / 2 - K1 * y2 * z) 54 | 55 | # Calculate luminance 56 | L = cosPhi * cosTheta * sinB - cosA * cosTheta * sinPhi - sinA * sinTheta + cosB * (cosA * sinTheta - cosTheta * sinA * sinPhi) 57 | 58 | # Only render if point is visible and in front of previous points 59 | if 0 <= x3 < width and 0 <= y3 < height and z > zbuffer[y3][x3]: 60 | zbuffer[y3][x3] = z 61 | luminance_index = int(L * 8) 62 | # ASCII chars by increasing luminance 63 | chars = '.,-~:;=!*#$@' 64 | output[y3][x3] = chars[max(0, min(luminance_index, len(chars) - 1))] 65 | 66 | # Render the frame 67 | result = '\n'.join(''.join(row) for row in output) 68 | clear_screen() 69 | print(result) 70 | 71 | def main(): 72 | A = 0 73 | B = 0 74 | try: 75 | while True: 76 | render_frame(A, B) 77 | A += 0.07 78 | B += 0.03 79 | time.sleep(0.03) 80 | except KeyboardInterrupt: 81 | print("Animation stopped") 82 | 83 | if __name__ == "__main__": 84 | main() 85 | -------------------------------------------------------------------------------- /miscelenious/dsaa.py: -------------------------------------------------------------------------------- 1 | import pyfiglet 2 | import time 3 | 4 | def show_word_in_figlet(word): 5 | # Render the word in figlet style 6 | ascii_art = pyfiglet.figlet_format(word, font="roman") 7 | print(ascii_art) 8 | 9 | def read_lyrics_and_show_figlet(file_path): 10 | try: 11 | # Open the lyrics.txt file 12 | with open(file_path, 'r') as file: 13 | # Read the entire content of the file 14 | lyrics = file.read() 15 | 16 | # Split the text into individual words 17 | words = lyrics.split() 18 | 19 | # Loop through each word and display it in figlet 20 | for word in words: 21 | show_word_in_figlet(word) 22 | time.sleep(0.4) # Optional: Pause between words for better visualization 23 | except FileNotFoundError: 24 | print(f"Error: The file '{file_path}' does not exist.") 25 | except Exception as e: 26 | print(f"An error occurred: {e}") 27 | 28 | # Path to the lyrics.txt file 29 | file_path = 'lyrics.txt' 30 | 31 | # Call the function to read lyrics and display in figlet 32 | read_lyrics_and_show_figlet(file_path) 33 | #nothing comit 34 | -------------------------------------------------------------------------------- /miscelenious/encrypt.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import json 3 | import os 4 | 5 | def create_and_store_password(): 6 | """ 7 | Ask user for username and password, encrypt the password using SHA-256, 8 | and store it in passwords.json file. 9 | """ 10 | username = input("Enter username: ") 11 | password = input("Enter password: ") 12 | 13 | # Encrypt password using SHA-256 14 | hashed_password = hashlib.sha256(password.encode()).hexdigest() 15 | 16 | # Initialize empty dict if file doesn't exist or load existing data 17 | if os.path.exists("passwords.json"): 18 | with open("passwords.json", "r") as file: 19 | try: 20 | passwords_dict = json.load(file) 21 | except json.JSONDecodeError: 22 | passwords_dict = {} 23 | else: 24 | passwords_dict = {} 25 | 26 | # Store username and hashed password 27 | passwords_dict[username] = hashed_password 28 | 29 | # Write back to file 30 | with open("passwords.json", "w") as file: 31 | json.dump(passwords_dict, file, indent=4) 32 | 33 | print(f"Password for {username} has been stored successfully!") 34 | 35 | def fetch_and_check_password(): 36 | """ 37 | Ask user for username and password, verify if the password matches 38 | the stored hashed password for that username. 39 | """ 40 | username = input("Enter username: ") 41 | password = input("Enter password: ") 42 | 43 | # Hash the input password 44 | hashed_password = hashlib.sha256(password.encode()).hexdigest() 45 | 46 | # Check if passwords.json exists 47 | if not os.path.exists("passwords.json"): 48 | print("No passwords have been stored yet.") 49 | return 50 | 51 | # Load passwords from file 52 | with open("passwords.json", "r") as file: 53 | try: 54 | passwords_dict = json.load(file) 55 | except json.JSONDecodeError: 56 | print("Password file is corrupted or empty.") 57 | return 58 | 59 | # Check if username exists and password matches 60 | if username in passwords_dict: 61 | if passwords_dict[username] == hashed_password: 62 | print("Verified! Password is correct.") 63 | else: 64 | print("Password is incorrect.") 65 | else: 66 | print(f"Username '{username}' not found.") 67 | 68 | # Example usage: 69 | if __name__ == "__main__": 70 | print("1. Create and store a password") 71 | print("2. Verify a password") 72 | choice = input("Enter your choice (1 or 2): ") 73 | 74 | if choice == "1": 75 | create_and_store_password() 76 | elif choice == "2": 77 | fetch_and_check_password() 78 | else: 79 | print("Invalid choice!") 80 | -------------------------------------------------------------------------------- /miscelenious/encrytionDecryption.py: -------------------------------------------------------------------------------- 1 | def caesar_cipher(): 2 | try: 3 | choice = input("Choose operation - Encrypt (E) / Decrypt (D): ").upper() 4 | if choice not in ['E', 'D']: 5 | raise ValueError("Invalid choice. Please enter 'E' or 'D'.") 6 | 7 | text = input("Enter the text: ") 8 | shift = int(input("Enter the shift value (integer): ")) 9 | 10 | result = "" 11 | for char in text: 12 | if char.isalpha(): 13 | offset = 65 if char.isupper() else 97 14 | if choice == 'E': 15 | shifted_char = chr((ord(char) - offset + shift) % 26 + offset) 16 | else: 17 | shifted_char = chr((ord(char) - offset - shift) % 26 + offset) 18 | 19 | result += shifted_char 20 | print(f"{char} -> {shifted_char}") 21 | else: 22 | result += char 23 | 24 | print(f"Result: {result}") 25 | except ValueError as ve: 26 | print(f"Error: {ve}") 27 | 28 | 29 | # Diffie-Hellman Key Exchange Implementation 30 | 31 | def diffie_hellman(): 32 | try: 33 | p = int(input("Enter a prime number (p): ")) 34 | g = int(input("Enter a primitive root (g): ")) 35 | 36 | alice_private = int(input("Alice's private key: ")) 37 | bob_private = int(input("Bob's private key: ")) 38 | 39 | alice_public = (g ** alice_private) % p 40 | bob_public = (g ** bob_private) % p 41 | 42 | print(f"Alice's Public Key: {alice_public}") 43 | print(f"Bob's Public Key: {bob_public}") 44 | 45 | alice_shared_secret = (bob_public ** alice_private) % p 46 | bob_shared_secret = (alice_public ** bob_private) % p 47 | 48 | print(f"Alice's Shared Secret: {alice_shared_secret}") 49 | print(f"Bob's Shared Secret: {bob_shared_secret}") 50 | 51 | if alice_shared_secret == bob_shared_secret: 52 | print("Shared secret keys match!") 53 | else: 54 | print("Error: Shared secrets do not match!") 55 | except ValueError: 56 | print("Error: Invalid input! Please enter integers only.") 57 | 58 | 59 | if __name__ == "__main__": 60 | print("1. Caesar Cipher") 61 | print("2. Diffie-Hellman Key Exchange") 62 | choice = input("Choose an option (1/2): ") 63 | 64 | if choice == '1': 65 | caesar_cipher() 66 | elif choice == '2': 67 | diffie_hellman() 68 | else: 69 | print("Invalid choice! Please select either 1 or 2.") 70 | -------------------------------------------------------------------------------- /miscelenious/fibonacci.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import numpy as np 3 | from matplotlib.animation import FuncAnimation 4 | import matplotlib.patches as patches 5 | from matplotlib.colors import LinearSegmentedColormap 6 | import matplotlib.gridspec as gridspec 7 | 8 | def generate_fibonacci(n): 9 | """Generate Fibonacci sequence up to n terms.""" 10 | fib_sequence = [0, 1] 11 | for i in range(2, n): 12 | fib_sequence.append(fib_sequence[i-1] + fib_sequence[i-2]) 13 | return fib_sequence 14 | 15 | def fibonacci_spiral_animation(n=16, interval=500, save_gif=False): 16 | """Create an enhanced animated Fibonacci spiral with sequence visualization.""" 17 | # Create custom colormap for better visual appeal 18 | colors = [(0.2, 0.4, 0.6), (0.4, 0.7, 0.9), (0.95, 0.5, 0.1), (0.9, 0.3, 0.3)] 19 | custom_cmap = LinearSegmentedColormap.from_list("fibonacci_colors", colors, N=n) 20 | 21 | # Generate complete Fibonacci sequence for the graph 22 | fibonacci_sequence = generate_fibonacci(n+5) 23 | 24 | # Set up the figure with grid layout - modified to remove the bar chart column 25 | fig = plt.figure(figsize=(16, 10)) 26 | gs = gridspec.GridSpec(2, 1, height_ratios=[4, 1]) 27 | 28 | # Spiral animation subplot - now takes full width 29 | ax_spiral = plt.subplot(gs[0, 0]) 30 | ax_spiral.set_xlim(-150, 150) 31 | ax_spiral.set_ylim(-150, 150) 32 | ax_spiral.set_title('Fibonacci Spiral', fontsize=18, fontweight='bold') 33 | ax_spiral.axis('equal') 34 | ax_spiral.axis('off') 35 | 36 | # Golden ratio information subplot 37 | ax_info = plt.subplot(gs[1, 0]) 38 | ax_info.axis('off') 39 | 40 | # Add title to the figure 41 | fig.suptitle('The Fibonacci Sequence & Golden Spiral', fontsize=22, fontweight='bold') 42 | 43 | # Initialize elements 44 | rectangles = [] 45 | spirals = [] 46 | text_artists = [] 47 | 48 | def init(): 49 | return [] 50 | 51 | def animate(frame): 52 | # Clear previous frame elements 53 | for rect in rectangles: 54 | rect.remove() 55 | rectangles.clear() 56 | 57 | if spirals: 58 | spirals[0].remove() 59 | spirals.clear() 60 | 61 | for text in text_artists: 62 | text.remove() 63 | text_artists.clear() 64 | 65 | # Create Fibonacci sequence up to current frame 66 | fib_values = fibonacci_sequence[:frame+2] 67 | 68 | # Draw rectangles for the golden spiral 69 | x, y = 0, 0 70 | a, b = 0, 1 71 | 72 | # Add spiral center marker 73 | center_marker = ax_spiral.plot(0, 0, 'o', color='black', markersize=5)[0] 74 | rectangles.append(center_marker) 75 | 76 | for i in range(min(frame + 1, n)): 77 | color = custom_cmap(i/n) 78 | 79 | if i % 4 == 0: 80 | rect = patches.Rectangle((x, y), b, a, fill=False, 81 | edgecolor=color, linewidth=2) 82 | x += b 83 | elif i % 4 == 1: 84 | rect = patches.Rectangle((x-a, y), a, b, fill=False, 85 | edgecolor=color, linewidth=2) 86 | y += b 87 | elif i % 4 == 2: 88 | rect = patches.Rectangle((x-a-b, y), b, a, fill=False, 89 | edgecolor=color, linewidth=2) 90 | x -= b 91 | else: 92 | rect = patches.Rectangle((x-a, y-a), a, b, fill=False, 93 | edgecolor=color, linewidth=2) 94 | y -= b 95 | 96 | ax_spiral.add_patch(rect) 97 | rectangles.append(rect) 98 | 99 | # Add rectangle dimension text for better understanding 100 | size_text = ax_spiral.text(x-a/2, y-b/2, f"{b}×{a}", 101 | ha='center', va='center', fontsize=8, 102 | color='black', alpha=0.7) 103 | text_artists.append(size_text) 104 | 105 | a, b = b, a+b 106 | 107 | # Draw the spiral for the current frame 108 | theta = np.linspace(0, (frame/2 + 1) * np.pi, 1000) 109 | golden_ratio = (1 + np.sqrt(5)) / 2 110 | r = golden_ratio ** (theta / np.pi) 111 | spiral, = ax_spiral.plot(r * np.cos(theta), r * np.sin(theta), color='red', linewidth=2.5) 112 | spirals.append(spiral) 113 | 114 | # Display golden ratio approximation 115 | if len(fib_values) >= 3: 116 | ratio_text = f"F({frame+1})/F({frame}) = {fib_values[-1]}/{fib_values[-2]} = {fib_values[-1]/fib_values[-2]:.6f}" 117 | golden_text = f"Golden Ratio (φ) = {(1 + np.sqrt(5))/2:.6f}" 118 | diff = abs((fib_values[-1]/fib_values[-2]) - (1 + np.sqrt(5))/2) 119 | accuracy = f"Difference: {diff:.6f}" 120 | 121 | # Add sequence display to info panel since we removed the bar chart 122 | sequence_text = f"Fibonacci Sequence: {', '.join(map(str, fib_values))}" 123 | 124 | info_text = ax_info.text(0.5, 0.5, 125 | f"{sequence_text}\n\n{ratio_text}\n{golden_text}\n{accuracy}\n\n" 126 | f"As the sequence progresses, the ratio between consecutive\n" 127 | f"Fibonacci numbers approaches the Golden Ratio (φ).", 128 | ha='center', va='center', fontsize=12, 129 | bbox=dict(boxstyle='round', facecolor='lightyellow', alpha=0.9)) 130 | text_artists.append(info_text) 131 | 132 | # Add current frame info to spiral plot 133 | if frame >= 0: 134 | frame_text = ax_spiral.text(0.05, 0.95, 135 | f"Step: {frame+1}\nCurrent Fibonacci: {fib_values[frame+1]}", 136 | transform=ax_spiral.transAxes, fontsize=12, 137 | verticalalignment='top', 138 | bbox=dict(boxstyle='round', facecolor='white', alpha=0.8)) 139 | text_artists.append(frame_text) 140 | 141 | # Combine all artists 142 | all_artists = rectangles + spirals + text_artists 143 | return all_artists 144 | 145 | # Set up animation with progress bar 146 | from tqdm import tqdm 147 | progress_bar = tqdm(total=n, desc="Generating animation") 148 | 149 | def update_progress(frame, *args): 150 | progress_bar.update(1) 151 | return animate(frame) 152 | 153 | # Limit the animation to exactly n frames (stopping at step 16 by default) 154 | anim = FuncAnimation(fig, update_progress, frames=range(n), 155 | init_func=init, blit=True, 156 | interval=interval, repeat=False) # Changed repeat to False to stop at the last frame 157 | 158 | # Add animation control buttons 159 | ax_buttons = plt.axes([0.81, 0.02, 0.1, 0.04]) 160 | button_pause = plt.Button(ax_buttons, 'Pause/Play') 161 | 162 | def toggle_pause(event): 163 | if anim.event_source: 164 | if anim.event_source.running: 165 | anim.event_source.stop() 166 | else: 167 | anim.event_source.start() 168 | 169 | button_pause.on_clicked(toggle_pause) 170 | 171 | plt.tight_layout(rect=[0, 0, 1, 0.95]) # Adjust layout to accommodate the title 172 | 173 | # Save animation if requested with error handling 174 | if save_gif: 175 | try: 176 | from datetime import datetime 177 | import os 178 | 179 | # Create output directory if it doesn't exist 180 | output_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "outputs") 181 | os.makedirs(output_dir, exist_ok=True) 182 | 183 | # Generate timestamp for unique filename 184 | timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") 185 | filename = f'fibonacci_spiral_{timestamp}.gif' 186 | filepath = os.path.join(output_dir, filename) 187 | 188 | # Save with progress indicator 189 | print(f"Saving animation to: {filepath}") 190 | anim.save(filepath, writer='pillow', fps=2, dpi=120) 191 | print(f"Animation saved successfully!") 192 | except Exception as e: 193 | print(f"Error saving animation: {str(e)}") 194 | 195 | # Close progress bar after animation is complete 196 | progress_bar.close() 197 | 198 | return fig, anim 199 | 200 | if __name__ == "__main__": 201 | # Create and display animation - ensuring we stop at exactly step 16 202 | fig, anim = fibonacci_spiral_animation(n=16, interval=800, save_gif=True) 203 | 204 | plt.show() -------------------------------------------------------------------------------- /miscelenious/graphchallange.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict, deque 2 | 3 | def GraphChallenge(strarr): 4 | # Create an adjacency list representation of the graph 5 | graph = defaultdict(list) 6 | for path in strarr: 7 | node1, node2 = path.split('-') 8 | graph[node1].append(node2) 9 | graph[node2].append(node1) 10 | 11 | # Perform BFS to find the longest path 12 | max_path_length = 0 13 | for node in graph: 14 | queue = deque([(node, 0)]) # (node, path_length) 15 | visited = set() 16 | while queue: 17 | current_node, path_length = queue.popleft() 18 | if current_node not in visited: 19 | visited.add(current_node) 20 | max_path_length = max(max_path_length, path_length) 21 | for neighbor in graph[current_node]: 22 | queue.append((neighbor, path_length + 1)) 23 | 24 | return max_path_length 25 | 26 | print(GraphChallenge(["b-e", "b-c","c-d", "a-b", "e-f"])) # Output: 4 27 | print(GraphChallenge(["b-a", "c-e", "b-c", "d-c"])) # Output: 3 28 | -------------------------------------------------------------------------------- /miscelenious/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Voice Recognition 7 | 8 | 9 | 12 | 13 | 14 | 17 |
18 |

Voice Recognition

19 | 23 |
Tap the microphone to start speaking...
24 |
25 | 26 | Ready 27 | 34 |
35 |
36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /miscelenious/leaaldownload.py: -------------------------------------------------------------------------------- 1 | def wait_for_results_and_download_judgments(driver): 2 | try: 3 | print("Waiting for results to load...") 4 | WebDriverWait(driver, 20).until( 5 | EC.presence_of_element_located((By.ID, "showList")) 6 | ) 7 | time.sleep(2) 8 | 9 | # Collect judgment links 10 | show_list_div = driver.find_element(By.ID, "showList") 11 | rows = show_list_div.find_elements(By.TAG_NAME, "tr") 12 | 13 | print("Collecting all the links for only Judgments(not for orders)") 14 | 15 | judgment_links = [] 16 | for row in rows: 17 | links = row.find_elements(By.TAG_NAME, "a") 18 | for link in links: 19 | if link.text.strip().lower() == "judgment": 20 | href = link.get_attribute("href") 21 | if href: 22 | judgment_links.append(href) 23 | 24 | print(f"Found {len(judgment_links)} judgment link(s).") 25 | 26 | for i, pdf_url in enumerate(judgment_links, 1): 27 | print(f"Downloading judgment #{i}") 28 | driver.execute_script("window.open('');") 29 | driver.switch_to.window(driver.window_handles[-1]) 30 | driver.get(pdf_url) 31 | time.sleep(5) # Allow time for download 32 | driver.close() 33 | driver.switch_to.window(driver.window_handles[0]) 34 | time.sleep(1) 35 | 36 | print(f"All available judgments downloaded: {len(judgment_links)}") 37 | except Exception as e: 38 | print(f"Error while fetching judgments: {e}") -------------------------------------------------------------------------------- /miscelenious/lyrics.txt: -------------------------------------------------------------------------------- 1 | Diet mountain dew, baby, New York City 2 | Never was there ever a girl so pretty 3 | Do you think we'll be in love forever? 4 | Do you think we'll be in love? 5 | 6 | Diet mountain dew, baby, New York City 7 | Can we hit it now low down and gritty? 8 | Do you think we'll be in love forever? 9 | Do you think we'll be in love? 10 | -------------------------------------------------------------------------------- /miscelenious/maximumSubArray.py: -------------------------------------------------------------------------------- 1 | def max_subarray_sum(nums): 2 | max_ending = max_so_far = nums[0] 3 | for x in nums[1:]: 4 | max_ending = max(x, max_ending + x) 5 | max_so_far = max(max_so_far, max_ending) 6 | return max_so_far 7 | 8 | if __name__ == "__main__": 9 | arr = [1, -3, 2, 1, -1, 3, -2] 10 | print(max_subarray_sum(arr)) -------------------------------------------------------------------------------- /miscelenious/mbappe.txt: -------------------------------------------------------------------------------- 1 | **************************************************************************************************** 2 | *************************************************########**************************++++++=++++****** 3 | ***********************************************#%%%%%%%%##*************************++++--=-===****** 4 | ***********************************************######%#####****************************-------****** 5 | **********************************************####**####%%#***************************************** 6 | **********************************************###%%%%###%%#***************************************** 7 | **********************************************####%%####%#****************************************** 8 | ***********************************************%%***##%%%******************************************* 9 | **********************************************+**+****##******************************************** 10 | ******************************************+=-:=************--=+************************************* 11 | *************************************+=--:....-#****###**#*:...:---=***********++++++*++++++++++++++ 12 | ***********************************+-.....:...:-*##****##*-....... .:=**++++++++++++++++++++++++++++ 13 | **********************************+:...::::......:=++++=-...:===-.....-+++++++++++++++++++++++++++++ 14 | *+*******************************+:...::....................:=+++=:....:++++++++++++++++++++++++++++ 15 | *********************************=......:::...............:=::++++=::::.-+++++++++++++++++++++++++++ 16 | *********+******+*+*******+++++*+:...:-==+=::::::.........:---=++*+=--:::++++++********+++++++++++++ 17 | ++********++**++++++++++++++++++:..:-++++=---:::::::::..::::--==+***-::::=++++++**++**++++++++***+++ 18 | +******++++++++++++++++++++++++=:::-+++++=----------:::::::-+==-=+**-.::::=+++++++++++++++++++++++++ 19 | ++++++**+**++++++++++++++++++++*#*+++**+=--========--:::---=====-=+===++---+++++++++++++++++++++++++ 20 | +++++++++++++++++++++++++++++++++++****=-=-===--=-===-==--=======++++****+++++++++++++++++++++++++++ 21 | +++++++++++++++++++++++++++++++++**#*+*=-==++===--=*++***---==+++*+++********+++++++++++++++++++++++ 22 | ++++++++++++++++++++++++++++++****#*++++++=======--**+*+*---===+**++++**#******+++++++++++++++++++++ 23 | +++++++++++++++++++*++++++++**#####*+++*++=---:::::++=**+:---===+++++++*#####**++++++++++++++++++*++ 24 | +++++++++++++++*+++*++++++++*#####*+++++==----:::::--:==------=+=+++++++**####*+++++++++++++++++++++ 25 | +++++++++++++++++++++++++++++*#**+++++++-::::---::::::.:::::---=+++++++++++***++++++++++++++++++++++ 26 | +++++++++++++++++++++++++++++++++++++++=---::::::::.:::::::----=+++++++++++++++++++++++*++**++++++++ 27 | +++++++++++++++++++++++++++++++++++++++-::-::------:::::::::::::=+++++++++++++++++++++++++++++++++++ 28 | +++++++++++++++++++++++++++++++++++++++:.::::::::-----::::::::::-+++++++++++++++++++++++++++++++++++ 29 | -------------------------------------------------------------------------------- /miscelenious/mergesort.py: -------------------------------------------------------------------------------- 1 | #Merge Sort 2 | 3 | def merge_sort(arr): 4 | if len(arr) > 1: 5 | mid = len(arr) // 2 6 | left = arr[:mid] 7 | right = arr[mid:] 8 | 9 | merge_sort(left) 10 | merge_sort(right) 11 | 12 | i = j = k = 0 13 | 14 | while i < len(left) and j < len(right): 15 | if left[i] < right[j]: 16 | arr[k] = left[i] 17 | i += 1 18 | else: 19 | arr[k] = right[j] 20 | j += 1 21 | k += 1 22 | 23 | while i < len(left): 24 | arr[k] = left[i] 25 | i += 1 26 | k += 1 27 | 28 | while j < len(right): 29 | arr[k] = right[j] 30 | j += 1 31 | k += 1 -------------------------------------------------------------------------------- /miscelenious/new_file.py: -------------------------------------------------------------------------------- 1 | def greet(name): 2 | """A simple function that prints a greeting message""" 3 | return f"Hello, {name}!" 4 | 5 | def main(): 6 | # Example usage 7 | user_name = input("Enter your name: ") 8 | message = greet(user_name) 9 | print(message) 10 | 11 | if __name__ == "__main__": 12 | main() -------------------------------------------------------------------------------- /miscelenious/outputs/fibonacci_spiral_20250404_183922.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anubhob435/pythonFiles/e8fe21829ff9f4e194e4f6bd8ba913539385d73f/miscelenious/outputs/fibonacci_spiral_20250404_183922.gif -------------------------------------------------------------------------------- /miscelenious/outputs/fibonacci_spiral_20250404_184148.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anubhob435/pythonFiles/e8fe21829ff9f4e194e4f6bd8ba913539385d73f/miscelenious/outputs/fibonacci_spiral_20250404_184148.gif -------------------------------------------------------------------------------- /miscelenious/outputs/fibonacci_spiral_20250404_184355.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anubhob435/pythonFiles/e8fe21829ff9f4e194e4f6bd8ba913539385d73f/miscelenious/outputs/fibonacci_spiral_20250404_184355.gif -------------------------------------------------------------------------------- /miscelenious/passwords.json: -------------------------------------------------------------------------------- 1 | { 2 | "anubhob": "7d727ac57ca6285f5a38be092aaea0a0d7678607071f1e04d8537159d8d66482" 3 | } -------------------------------------------------------------------------------- /miscelenious/practice_1.py: -------------------------------------------------------------------------------- 1 | import seaborn as sns 2 | 3 | def divide_numbers(a, b): 4 | try: 5 | result = a / b 6 | return result 7 | except ZeroDivisionError: 8 | return "Error: Division by zero is not allowed" 9 | 10 | # Test the function 11 | print(divide_numbers(10, 2)) # Normal division 12 | print(divide_numbers(10, 0)) # Attempting division by zero 13 | 14 | import matplotlib.pyplot as plt 15 | 16 | # Load built-in dataset 17 | tips = sns.load_dataset("tips") 18 | 19 | # Create a scatterplot 20 | sns.scatterplot(data=tips, x="total_bill", y="tip") 21 | plt.title("Tips vs Total Bill Amount") 22 | plt.show() 23 | 24 | -------------------------------------------------------------------------------- /miscelenious/python_game.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import random 3 | 4 | # Initialize Pygame 5 | pygame.init() 6 | 7 | # Set up the display 8 | WIDTH = 800 9 | HEIGHT = 600 10 | screen = pygame.display.set_mode((WIDTH, HEIGHT)) 11 | pygame.display.set_caption("Dodge the Blocks") 12 | 13 | # Colors 14 | WHITE = (255, 255, 255) 15 | RED = (255, 0, 0) 16 | BLUE = (0, 0, 255) 17 | 18 | # Player settings 19 | player_size = 50 20 | player_x = WIDTH // 2 - player_size // 2 21 | player_y = HEIGHT - player_size - 10 22 | player_speed = 5 23 | 24 | # Enemy settings 25 | enemy_size = 50 26 | enemy_speed = 5 27 | enemies = [] 28 | 29 | # Game loop 30 | running = True 31 | clock = pygame.time.Clock() 32 | score = 0 33 | 34 | while running: 35 | # Event handling 36 | for event in pygame.event.get(): 37 | if event.type == pygame.QUIT: 38 | running = False 39 | 40 | # Player movement 41 | keys = pygame.key.get_pressed() 42 | if keys[pygame.K_LEFT] and player_x > 0: 43 | player_x -= player_speed 44 | if keys[pygame.K_RIGHT] and player_x < WIDTH - player_size: 45 | player_x += player_speed 46 | 47 | # Create new enemies 48 | if len(enemies) < 5 and random.random() < 0.02: 49 | enemies.append([random.randint(0, WIDTH - enemy_size), -enemy_size]) 50 | 51 | # Update enemy positions 52 | for enemy in enemies[:]: 53 | enemy[1] += enemy_speed 54 | if enemy[1] > HEIGHT: 55 | enemies.remove(enemy) 56 | score += 1 57 | 58 | # Collision detection 59 | player_rect = pygame.Rect(player_x, player_y, player_size, player_size) 60 | for enemy in enemies: 61 | enemy_rect = pygame.Rect(enemy[0], enemy[1], enemy_size, enemy_size) 62 | if player_rect.colliderect(enemy_rect): 63 | running = False 64 | 65 | # Drawing 66 | screen.fill(WHITE) 67 | pygame.draw.rect(screen, BLUE, (player_x, player_y, player_size, player_size)) 68 | for enemy in enemies: 69 | pygame.draw.rect(screen, RED, (enemy[0], enemy[1], enemy_size, enemy_size)) 70 | 71 | pygame.display.flip() 72 | clock.tick(60) 73 | 74 | print(f"Game Over! Score: {score}") 75 | pygame.quit() -------------------------------------------------------------------------------- /miscelenious/random_luck.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def lucky_draw(): 4 | # Generate a random number between 1 and 100 5 | secret_number = random.randint(1, 100) 6 | attempts = 0 7 | max_attempts = 10 8 | 9 | print("Welcome to the Lucky Number Game!") 10 | print(f"Guess a number between 1 and 100. You have {max_attempts} attempts.") 11 | 12 | while attempts < max_attempts: 13 | try: 14 | # Get player's guess 15 | guess = int(input("Enter your guess: ")) 16 | attempts += 1 17 | 18 | # Check the guess 19 | if guess == secret_number: 20 | print(f"Congratulations! You won in {attempts} attempts!") 21 | return 22 | elif guess < secret_number: 23 | print("Too low! Try again.") 24 | else: 25 | print("Too high! Try again.") 26 | 27 | print(f"Attempts remaining: {max_attempts - attempts}") 28 | 29 | except ValueError: 30 | print("Please enter a valid number!") 31 | 32 | print(f"Game Over! The number was {secret_number}") 33 | 34 | if __name__ == "__main__": 35 | lucky_draw() -------------------------------------------------------------------------------- /miscelenious/recursion printing.py: -------------------------------------------------------------------------------- 1 | lst_alphabets = [] 2 | lst_num = [] 3 | lst_2 = [] 4 | lst_print = [] 5 | dictionary_1 = { 6 | 1: "a", 2: "b", 3: "c", 4: "d", 5: "e", 7 | 6: "f", 7: "g", 8: "h", 9: "i", 10: "j", 8 | 11: "k", 12: "l", 13: "m", 14: "n", 15: "o", 9 | 16: "p", 17: "q", 18: "r", 19: "s", 20: "t", 10 | 21: "u", 22: "v", 23: "w", 24: "x", 25: "y", 26: "z", 27: " " 11 | } 12 | 13 | keys = list(dictionary_1.keys()) 14 | values = list(dictionary_1.values()) 15 | 16 | word = input("Enter word: ").lower() 17 | 18 | print("OH I USED TO SAY !!") 19 | for i in word: 20 | lst_alphabets.append(i) 21 | 22 | for k in lst_alphabets: 23 | index = values.index(k) 24 | Key = keys[index] 25 | lst_num.append(Key) 26 | 27 | def programme(): 28 | count = 0 29 | for x in lst_num: 30 | for z in range(0, x): 31 | tempv = values[z] 32 | lst_print.append(tempv) 33 | print("".join(lst_print)) 34 | if tempv != lst_alphabets[count]: 35 | lst_print.pop() 36 | else: 37 | count +=1 38 | 39 | programme() 40 | print("I FOUND YOU !!! :)") -------------------------------------------------------------------------------- /miscelenious/roman.py: -------------------------------------------------------------------------------- 1 | def roman_to_int(s): 2 | roman_values = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} 3 | total = 0 4 | for c in s: 5 | total += roman_values[c] 6 | return total 7 | 8 | def int_to_roman(num): 9 | val = [ 10 | 1000, 900, 500, 400, 11 | 100, 90, 50, 40, 12 | 10, 9, 5, 4, 13 | 1 14 | ] 15 | syb = [ 16 | "M", "CM", "D", "CD", 17 | "C", "XC", "L", "XL", 18 | "X", "IX", "V", "IV", 19 | "I" 20 | ] 21 | roman_str = '' 22 | for i in range(len(val)): 23 | while num >= val[i]: 24 | num -= val[i] 25 | roman_str += syb[i] 26 | return roman_str 27 | 28 | def StringChallenge(s): 29 | # Convert roman numeral string to integer 30 | numeral_value = roman_to_int(s) 31 | 32 | # Convert integer back to shortest roman numeral string 33 | shortest_roman = int_to_roman(numeral_value) 34 | 35 | return shortest_roman 36 | 37 | def final_output(s): 38 | token = 'eav2xtzlf7' 39 | combined = s + token 40 | result = ''.join([char if (i + 1) % 4 != 0 else '_' for i, char in enumerate(combined)]) 41 | return result 42 | 43 | # Examples 44 | input_str = "XXXVVIIIIIIIIII" 45 | output = StringChallenge(input_str) 46 | print("Output:", output) 47 | print("Final Output:", final_output(output)) 48 | 49 | input_str = "DDLL" 50 | output = StringChallenge(input_str) 51 | print("Output:", output) 52 | print("Final Output:", final_output(output)) -------------------------------------------------------------------------------- /miscelenious/script.js: -------------------------------------------------------------------------------- 1 | const themeToggle = document.getElementById('theme-toggle'); 2 | const themeIcon = themeToggle.querySelector('i'); 3 | const html = document.documentElement; 4 | 5 | // Load saved theme 6 | const savedTheme = localStorage.getItem('theme') || 'light'; 7 | html.setAttribute('data-theme', savedTheme); 8 | updateThemeIcon(savedTheme); 9 | 10 | themeToggle.addEventListener('click', () => { 11 | const currentTheme = html.getAttribute('data-theme'); 12 | const newTheme = currentTheme === 'light' ? 'dark' : 'light'; 13 | 14 | html.setAttribute('data-theme', newTheme); 15 | localStorage.setItem('theme', newTheme); 16 | updateThemeIcon(newTheme); 17 | }); 18 | 19 | function updateThemeIcon(theme) { 20 | themeIcon.className = theme === 'light' ? 'fas fa-moon' : 'fas fa-sun'; 21 | } 22 | 23 | const startBtn = document.getElementById("start-btn"); 24 | const outputDiv = document.getElementById("output"); 25 | const statusSpan = document.getElementById("status"); 26 | const waveVisualizer = document.getElementById("wave-visualizer"); 27 | const buttonText = startBtn.querySelector("span"); 28 | 29 | if ("webkitSpeechRecognition" in window) { 30 | const recognition = new webkitSpeechRecognition(); 31 | recognition.continuous = false; 32 | recognition.interimResults = false; 33 | recognition.lang = "en-US"; 34 | 35 | startBtn.addEventListener("click", () => { 36 | startBtn.classList.add("listening"); 37 | buttonText.textContent = "Listening..."; 38 | outputDiv.textContent = "Listening..."; 39 | statusSpan.textContent = "Listening..."; 40 | waveVisualizer.style.display = "flex"; 41 | recognition.start(); 42 | }); 43 | 44 | recognition.onresult = (event) => { 45 | const transcript = event.results[0][0].transcript; 46 | outputDiv.innerHTML = ` ${transcript} `; 47 | }; 48 | 49 | recognition.onerror = (event) => { 50 | outputDiv.innerHTML = ` Error: ${event.error}`; 51 | resetUI(); 52 | }; 53 | 54 | recognition.onend = () => { 55 | resetUI(); 56 | }; 57 | 58 | function resetUI() { 59 | startBtn.classList.remove("listening"); 60 | buttonText.textContent = "Start Listening"; 61 | statusSpan.textContent = "Ready"; 62 | waveVisualizer.style.display = "none"; 63 | } 64 | } else { 65 | startBtn.disabled = true; 66 | outputDiv.innerHTML = ' Speech recognition is not supported in your browser. Please try using Google Chrome.'; 67 | } -------------------------------------------------------------------------------- /miscelenious/searching.py: -------------------------------------------------------------------------------- 1 | def SearchingChallenge(strArr): 2 | # Convert the input array into a matrix 3 | matrix = [list(map(int, row)) for row in strArr] 4 | 5 | # Get the dimensions of the matrix 6 | rows, cols = len(matrix), len(matrix[0]) 7 | 8 | # Define the directions for DFS 9 | directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] 10 | 11 | # Initialize the memoization table 12 | memo = [[0] * cols for _ in range(rows)] 13 | 14 | def dfs(r, c): 15 | # If the result is already memoized, return it 16 | if memo[r][c] != 0: 17 | return memo[r][c] 18 | 19 | # Initialize the longest path length to 1 20 | longest_path = 1 21 | 22 | # Explore all possible directions 23 | for dr, dc in directions: 24 | nr, nc = r + dr, c + dc 25 | 26 | # Check if the new position is within the matrix bounds 27 | if 0 <= nr < rows and 0 <= nc < cols: 28 | # Check if the new position has a larger value 29 | if matrix[nr][nc] > matrix[r][c]: 30 | # Recursively explore the new position 31 | longest_path = max(longest_path, dfs(nr, nc) + 1) 32 | 33 | # Memoize the result 34 | memo[r][c] = longest_path 35 | return longest_path 36 | 37 | # Initialize the longest path length to 0 38 | longest_path = 0 39 | 40 | # Explore all positions in the matrix 41 | for r in range(rows): 42 | for c in range(cols): 43 | longest_path = max(longest_path, dfs(r, c)) 44 | 45 | return longest_path - 1 46 | 47 | print(SearchingChallenge(["12256", "56219", "43215"])) # Output: 5 48 | print(SearchingChallenge(["67", "21", "45"])) # Output: 3 49 | -------------------------------------------------------------------------------- /miscelenious/sha512.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | 3 | def compute_sha256(message: str) -> str: 4 | return hashlib.sha256(message.encode()).hexdigest() 5 | 6 | def compute_sha512(message: str) -> str: 7 | return hashlib.sha512(message.encode()).hexdigest() 8 | 9 | if __name__ == "__main__": 10 | text = "Hello, world" 11 | sha256_result = compute_sha256(text) 12 | sha512_result = compute_sha512(text) 13 | 14 | print("SHA256:", sha256_result) 15 | print("SHA512:", sha512_result) -------------------------------------------------------------------------------- /miscelenious/string27.py: -------------------------------------------------------------------------------- 1 | #27. Write a program to find a substring within a string. If found display its starting position 2 | 3 | text = input("Enter a string: ") 4 | sub = input("Enter a substring to find: ") 5 | position = text.find(sub) 6 | if position != -1: 7 | print(f"Substring found at position {position}") 8 | else: 9 | print("Substring not found.") -------------------------------------------------------------------------------- /miscelenious/stringchallange1.py: -------------------------------------------------------------------------------- 1 | def is_palindrome(s): 2 | return s == s[::-1] 3 | 4 | def StringChallenge(strParam): 5 | if is_palindrome(strParam): 6 | return strParam 7 | 8 | n = len(strParam) 9 | 10 | # Try removing one character at a time 11 | for i in range(n): 12 | temp = strParam[:i] + strParam[i+1:] 13 | if is_palindrome(temp) and len(temp) >= 3: 14 | return strParam[i] 15 | 16 | # Try removing two characters 17 | for i in range(n): 18 | for j in range(i+1, n): 19 | temp = strParam[:i] + strParam[i+1:j] + strParam[j+1:] 20 | if is_palindrome(temp) and len(temp) >= 3: 21 | return strParam[i] + strParam[j] 22 | 23 | return "not possible" 24 | 25 | # Keep this function call here 26 | print(StringChallenge(input())) -------------------------------------------------------------------------------- /miscelenious/stringchallange2.py: -------------------------------------------------------------------------------- 1 | def find_smallest_number(numbers): 2 | if not numbers: 3 | return None 4 | return min(numbers) 5 | 6 | sample_list = [10, 2, 5, 1, -7, 13] 7 | print(find_smallest_number(sample_list)) # Output: -7 -------------------------------------------------------------------------------- /miscelenious/styles.css: -------------------------------------------------------------------------------- 1 | :root[data-theme="light"] { 2 | --primary-color: #4a90e2; 3 | --secondary-color: #f8f9fa; 4 | --text-color: #2c3e50; 5 | --bg-color: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); 6 | --app-bg: rgba(255, 255, 255, 0.95); 7 | --shadow: 0 4px 6px rgba(0, 0, 0, 0.1); 8 | } 9 | 10 | :root[data-theme="dark"] { 11 | --primary-color: #64b5f6; 12 | --secondary-color: #2c3e50; 13 | --text-color: #ecf0f1; 14 | --bg-color: linear-gradient(135deg, #2c3e50 0%, #1a1a1a 100%); 15 | --app-bg: rgba(33, 33, 33, 0.95); 16 | --shadow: 0 4px 6px rgba(0, 0, 0, 0.3); 17 | } 18 | 19 | * { 20 | transition: background-color 0.3s, color 0.3s, border-color 0.3s, box-shadow 0.3s; 21 | } 22 | 23 | #theme-toggle { 24 | position: fixed; 25 | top: 20px; 26 | right: 20px; 27 | padding: 10px; 28 | border-radius: 50%; 29 | border: none; 30 | background: var(--secondary-color); 31 | color: var(--text-color); 32 | cursor: pointer; 33 | box-shadow: var(--shadow); 34 | width: 40px; 35 | height: 40px; 36 | display: flex; 37 | align-items: center; 38 | justify-content: center; 39 | } 40 | 41 | #theme-toggle:hover { 42 | transform: scale(1.1); 43 | } 44 | 45 | body { 46 | font-family: 'Segoe UI', system-ui, -apple-system, sans-serif; 47 | margin: 0; 48 | min-height: 100vh; 49 | display: flex; 50 | align-items: center; 51 | justify-content: center; 52 | background: var(--bg-color); 53 | color: var(--text-color); 54 | } 55 | 56 | #app { 57 | width: 90%; 58 | max-width: 600px; 59 | padding: 2rem; 60 | background: var(--app-bg); 61 | border-radius: 20px; 62 | box-shadow: var(--shadow); 63 | backdrop-filter: blur(10px); 64 | } 65 | 66 | h1 { 67 | font-size: 2.2rem; 68 | margin-bottom: 1.5rem; 69 | color: var(--primary-color); 70 | display: flex; 71 | align-items: center; 72 | justify-content: center; 73 | gap: 10px; 74 | } 75 | 76 | #start-btn { 77 | padding: 1rem 2rem; 78 | font-size: 1.1rem; 79 | border: none; 80 | border-radius: 50px; 81 | background: var(--primary-color); 82 | color: white; 83 | cursor: pointer; 84 | transition: all 0.3s ease; 85 | display: flex; 86 | align-items: center; 87 | gap: 10px; 88 | margin: 2rem auto; 89 | } 90 | 91 | #start-btn:hover { 92 | transform: translateY(-2px); 93 | box-shadow: var(--shadow); 94 | background: #357abd; 95 | } 96 | 97 | #start-btn.listening { 98 | background: #e74c3c; 99 | animation: pulse 1.5s infinite; 100 | } 101 | 102 | #output { 103 | margin-top: 2rem; 104 | padding: 1.5rem; 105 | border-radius: 15px; 106 | background: var(--secondary-color); 107 | min-height: 100px; 108 | transition: all 0.3s ease; 109 | line-height: 1.6; 110 | color: var(--text-color); 111 | } 112 | 113 | @keyframes pulse { 114 | 0% { transform: scale(1); } 115 | 50% { transform: scale(1.05); } 116 | 100% { transform: scale(1); } 117 | } 118 | 119 | .status-indicator { 120 | display: flex; 121 | align-items: center; 122 | justify-content: center; 123 | gap: 10px; 124 | margin-top: 1rem; 125 | font-size: 0.9rem; 126 | color: var(--text-color); 127 | } 128 | 129 | .wave { 130 | display: flex; 131 | align-items: center; 132 | gap: 3px; 133 | height: 20px; 134 | } 135 | 136 | .wave-bar { 137 | width: 3px; 138 | height: 100%; 139 | background: var(--primary-color); 140 | animation: wave 1s ease-in-out infinite; 141 | transform-origin: bottom; 142 | } 143 | 144 | @keyframes wave { 145 | 0% { transform: scaleY(0.1); } 146 | 50% { transform: scaleY(1); } 147 | 100% { transform: scaleY(0.1); } 148 | } -------------------------------------------------------------------------------- /miscelenious/sumoftwolinkedlist.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, val=0, next=None): 3 | self.val = val 4 | self.next = next 5 | 6 | def mergeTwoLists(l1, l2): 7 | """ 8 | Merge two sorted linked lists into a single sorted linked list. 9 | 10 | Args: 11 | l1: The head of the first sorted linked list 12 | l2: The head of the second sorted linked list 13 | 14 | Returns: 15 | The head of the merged sorted linked list 16 | """ 17 | # Create a dummy head to simplify edge cases 18 | dummy = ListNode(-1) 19 | current = dummy 20 | 21 | # Traverse both lists and compare values 22 | while l1 and l2: 23 | if l1.val <= l2.val: 24 | current.next = l1 25 | l1 = l1.next 26 | else: 27 | current.next = l2 28 | l2 = l2.next 29 | current = current.next 30 | 31 | # Attach remaining nodes from either list 32 | if l1: 33 | current.next = l1 34 | else: 35 | current.next = l2 36 | 37 | return dummy.next 38 | 39 | # Example usage 40 | def create_linked_list(values): 41 | """Helper function to create a linked list from a list of values""" 42 | dummy = ListNode(0) 43 | current = dummy 44 | for val in values: 45 | current.next = ListNode(val) 46 | current = current.next 47 | return dummy.next 48 | 49 | def print_linked_list(head): 50 | """Helper function to print a linked list""" 51 | values = [] 52 | current = head 53 | while current: 54 | values.append(str(current.val)) 55 | current = current.next 56 | return " -> ".join(values) 57 | 58 | # Test with example lists 59 | list1 = create_linked_list([1, 2, 4]) 60 | list2 = create_linked_list([1, 3, 4]) 61 | merged = mergeTwoLists(list1, list2) 62 | print(print_linked_list(merged)) # Output: 1 -> 1 -> 2 -> 3 -> 4 -> 4 -------------------------------------------------------------------------------- /miscelenious/temperature_converter.py: -------------------------------------------------------------------------------- 1 | def celsius_to_fahrenheit(celsius): 2 | """Convert Celsius to Fahrenheit.""" 3 | return (celsius * 9/5) + 32 4 | 5 | def fahrenheit_to_celsius(fahrenheit): 6 | """Convert Fahrenheit to Celsius.""" 7 | return (fahrenheit - 32) * 5/9 8 | 9 | def celsius_to_kelvin(celsius): 10 | """Convert Celsius to Kelvin.""" 11 | return celsius + 273.15 12 | 13 | def kelvin_to_celsius(kelvin): 14 | """Convert Kelvin to Celsius.""" 15 | return kelvin - 273.15 16 | 17 | def fahrenheit_to_kelvin(fahrenheit): 18 | """Convert Fahrenheit to Kelvin.""" 19 | celsius = fahrenheit_to_celsius(fahrenheit) 20 | return celsius_to_kelvin(celsius) 21 | 22 | def kelvin_to_fahrenheit(kelvin): 23 | """Convert Kelvin to Fahrenheit.""" 24 | celsius = kelvin_to_celsius(kelvin) 25 | return celsius_to_fahrenheit(celsius) 26 | 27 | def get_valid_temperature(): 28 | """Get a valid temperature input from the user.""" 29 | while True: 30 | try: 31 | temp = float(input("Enter the temperature value: ")) 32 | return temp 33 | except ValueError: 34 | print("Invalid input. Please enter a number.") 35 | 36 | def display_menu(): 37 | """Display the temperature conversion menu.""" 38 | print("\nTemperature Converter") 39 | print("---------------------") 40 | print("1. Celsius to Fahrenheit") 41 | print("2. Fahrenheit to Celsius") 42 | print("3. Celsius to Kelvin") 43 | print("4. Kelvin to Celsius") 44 | print("5. Fahrenheit to Kelvin") 45 | print("6. Kelvin to Fahrenheit") 46 | print("7. Exit") 47 | 48 | def main(): 49 | """Main function to run the temperature converter.""" 50 | while True: 51 | display_menu() 52 | 53 | try: 54 | choice = int(input("\nEnter your choice (1-7): ")) 55 | 56 | if choice == 7: 57 | print("Thank you for using the Temperature Converter. Goodbye!") 58 | break 59 | 60 | if choice < 1 or choice > 7: 61 | print("Invalid choice. Please select a number between 1 and 7.") 62 | continue 63 | 64 | temperature = get_valid_temperature() 65 | 66 | if choice == 1: 67 | result = celsius_to_fahrenheit(temperature) 68 | print(f"{temperature}°C = {result:.2f}°F") 69 | elif choice == 2: 70 | result = fahrenheit_to_celsius(temperature) 71 | print(f"{temperature}°F = {result:.2f}°C") 72 | elif choice == 3: 73 | result = celsius_to_kelvin(temperature) 74 | print(f"{temperature}°C = {result:.2f}K") 75 | elif choice == 4: 76 | result = kelvin_to_celsius(temperature) 77 | print(f"{temperature}K = {result:.2f}°C") 78 | elif choice == 5: 79 | result = fahrenheit_to_kelvin(temperature) 80 | print(f"{temperature}°F = {result:.2f}K") 81 | elif choice == 6: 82 | result = kelvin_to_fahrenheit(temperature) 83 | print(f"{temperature}K = {result:.2f}°F") 84 | 85 | except ValueError: 86 | print("Invalid input. Please enter a number.") 87 | 88 | if __name__ == "__main__": 89 | main() 90 | -------------------------------------------------------------------------------- /miscelenious/testimage.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anubhob435/pythonFiles/e8fe21829ff9f4e194e4f6bd8ba913539385d73f/miscelenious/testimage.jpg -------------------------------------------------------------------------------- /miscelenious/turtle_animation.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | # Setting up the screen 4 | wn = turtle.Screen() 5 | wn.bgcolor("black") 6 | wn.title("Solar System Animation") 7 | 8 | # Creating a Turtle object for drawing the sun and planets 9 | sun = turtle.Turtle() 10 | sun.shape("circle") 11 | sun.color("yellow") 12 | sun.shapesize(3) 13 | 14 | # Creating a list of planets with their properties (color, distance from the sun, size, and speed) 15 | planets = [ 16 | {"color": "gray", "distance": 50, "size": 0.5, "speed": 1}, 17 | {"color": "orange", "distance": 80, "size": 0.8, "speed": 0.5}, 18 | {"color": "red", "distance": 120, "size": 0.7, "speed": 0.3}, 19 | {"color": "blue", "distance": 160, "size": 0.6, "speed": 0.2}, 20 | {"color": "green", "distance": 200, "size": 0.9, "speed": 0.1} 21 | ] 22 | 23 | # Creating a Turtle object for each planet and animate their orbits 24 | planet_turtles = [] 25 | for planet in planets: 26 | planet_turtle = turtle.Turtle() 27 | planet_turtle.shape("circle") 28 | planet_turtle.color(planet["color"]) 29 | planet_turtle.shapesize(planet["size"]) 30 | planet_turtle.penup() 31 | planet_turtle.goto(planet["distance"], 0) 32 | planet_turtle.pendown() 33 | planet_turtles.append(planet_turtle) 34 | 35 | # Function to animate the planets' orbits 36 | def animate_orbits(): 37 | for i, planet in enumerate(planet_turtles): 38 | planet.speed(0) 39 | angle = 360 * planets[i]["speed"] 40 | planet.circle(planets[i]["distance"], angle) 41 | 42 | # Animating the orbits 43 | while True: 44 | animate_orbits() 45 | wn.update() 46 | 47 | # Closing the program when the user clicks on the screen 48 | wn.exitonclick() -------------------------------------------------------------------------------- /notes and materials/DSA_notes.txt: -------------------------------------------------------------------------------- 1 | ==================================================== 2 | DATA STRUCTURES AND ALGORITHMS - ESSENTIAL NOTES 3 | ==================================================== 4 | 5 | ===================== 6 | 1. COMPLEXITY ANALYSIS 7 | ===================== 8 | 9 | BIG O NOTATION: 10 | - O(1) : Constant time - Operations that don't depend on input size 11 | - O(log n) : Logarithmic - Divide and conquer algorithms (binary search) 12 | - O(n) : Linear - Scanning through data once 13 | - O(n log n): Linearithmic - Efficient sorting algorithms (merge sort, quicksort) 14 | - O(n²) : Quadratic - Nested loops, simple sorting algorithms 15 | - O(2^n) : Exponential - Recursive algorithms solving problems of size n 16 | - O(n!) : Factorial - Permutation algorithms 17 | 18 | SPACE COMPLEXITY: Memory usage by an algorithm 19 | 20 | ===================== 21 | 2. BASIC DATA STRUCTURES 22 | ===================== 23 | 24 | ARRAYS: 25 | - Fixed size, contiguous memory allocation 26 | - O(1) access by index 27 | - O(n) for insertion/deletion (except at end) 28 | - Uses: Simple lists, buffers, lookup tables 29 | 30 | LINKED LISTS: 31 | - Single: Each node points to next node 32 | - Double: Each node points to both next and previous nodes 33 | - O(n) access, O(1) insertion/deletion (if position known) 34 | - Uses: Dynamic memory allocation, implementing stacks/queues 35 | 36 | STACKS: 37 | - LIFO (Last In, First Out) 38 | - Operations: push, pop, peek - all O(1) 39 | - Uses: Expression evaluation, backtracking, function calls 40 | 41 | QUEUES: 42 | - FIFO (First In, First Out) 43 | - Operations: enqueue, dequeue - all O(1) 44 | - Uses: BFS, scheduling, buffers 45 | 46 | ===================== 47 | 3. ADVANCED DATA STRUCTURES 48 | ===================== 49 | 50 | HASH TABLES: 51 | - Key-value pairs with hashing function 52 | - Average O(1) for search/insert/delete 53 | - Collision resolution: chaining, open addressing 54 | - Uses: Caching, indexing, counting 55 | 56 | TREES: 57 | - Binary Trees: Each node has at most 2 children 58 | - Binary Search Trees: Left < Node < Right 59 | - Balanced Trees (AVL, Red-Black): Keep operations O(log n) 60 | - B-Trees: Self-balancing, used in databases/file systems 61 | - Uses: Hierarchical data, efficient searching 62 | 63 | HEAPS: 64 | - Complete binary trees with heap property 65 | - Min-heap: Parent smaller than children 66 | - Max-heap: Parent larger than children 67 | - O(log n) for insertion/deletion, O(1) to find min/max 68 | - Uses: Priority queues, scheduling, heap sort 69 | 70 | GRAPHS: 71 | - Vertices (nodes) connected by edges 72 | - Directed vs Undirected 73 | - Weighted vs Unweighted 74 | - Representations: Adjacency matrix, adjacency list 75 | - Uses: Networks, routes, social connections 76 | 77 | TRIES: 78 | - Tree-like structures for string operations 79 | - O(L) for search/insert/delete (L = string length) 80 | - Uses: Autocomplete, spell-checking, IP routing 81 | 82 | ===================== 83 | 4. SORTING ALGORITHMS 84 | ===================== 85 | 86 | COMPARISON SORTS: 87 | - Bubble Sort: O(n²), swaps adjacent elements 88 | - Selection Sort: O(n²), finds min/max repeatedly 89 | - Insertion Sort: O(n²), builds sorted array incrementally 90 | - Merge Sort: O(n log n), divide and conquer, stable 91 | - Quick Sort: O(n log n) average, in-place, unstable 92 | - Heap Sort: O(n log n), in-place, unstable 93 | 94 | NON-COMPARISON SORTS: 95 | - Counting Sort: O(n+k), for small integer ranges 96 | - Radix Sort: O(n*k), sorts by digits 97 | - Bucket Sort: O(n+k), distributes into buckets 98 | 99 | ===================== 100 | 5. SEARCHING ALGORITHMS 101 | ===================== 102 | 103 | - Linear Search: O(n), check each element 104 | - Binary Search: O(log n), requires sorted data 105 | - Depth-First Search (DFS): Uses stack, explores branches 106 | - Breadth-First Search (BFS): Uses queue, explores levels 107 | - A* Search: Uses heuristics for path finding 108 | 109 | ===================== 110 | 6. ALGORITHM PARADIGMS 111 | ===================== 112 | 113 | RECURSION: 114 | - Function that calls itself 115 | - Base case prevents infinite recursion 116 | - Uses: Tree traversal, divide and conquer 117 | 118 | DYNAMIC PROGRAMMING: 119 | - Breaking down problems into subproblems 120 | - Memoization stores results of subproblems 121 | - Bottom-up vs Top-down approaches 122 | - Uses: Optimization problems, counting problems 123 | 124 | GREEDY ALGORITHMS: 125 | - Make locally optimal choices 126 | - May not guarantee global optimum 127 | - Uses: Scheduling, Huffman coding 128 | 129 | DIVIDE AND CONQUER: 130 | - Break problem into subproblems 131 | - Solve subproblems recursively 132 | - Combine solutions 133 | - Uses: Binary search, merge sort 134 | 135 | BACKTRACKING: 136 | - Build solutions incrementally 137 | - Abandon partial solutions ("backtrack") when they fail 138 | - Uses: Puzzles, combinatorial problems 139 | 140 | ===================== 141 | 7. COMMON PROBLEMS & TECHNIQUES 142 | ===================== 143 | 144 | - Two Pointer Technique 145 | - Sliding Window 146 | - Binary Search Variations 147 | - Graph Traversal (DFS/BFS) 148 | - Topological Sorting 149 | - Shortest Path Algorithms (Dijkstra's, Bellman-Ford) 150 | - Minimum Spanning Tree (Prim's, Kruskal's) 151 | - Dynamic Programming Patterns 152 | - Bit Manipulation 153 | 154 | ===================== 155 | 8. SYSTEM DESIGN BASICS 156 | ===================== 157 | 158 | - Scalability: Horizontal vs Vertical 159 | - Load Balancing 160 | - Caching Strategies 161 | - Database Indexing 162 | - Microservices Architecture 163 | - API Design Principles 164 | - Consistency vs Availability (CAP Theorem) 165 | - Message Queues 166 | - Sharding Techniques 167 | 168 | ===================== 169 | 9. INTERVIEW TIPS 170 | ===================== 171 | 172 | - Break down problems step by step 173 | - Think out loud during problem-solving 174 | - Start with brute force, then optimize 175 | - Test your solution with examples 176 | - Analyze time and space complexity 177 | - Consider edge cases 178 | - Ask clarifying questions when needed 179 | - Practice explaining your approach 180 | -------------------------------------------------------------------------------- /notes and materials/Practice Set.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anubhob435/pythonFiles/e8fe21829ff9f4e194e4f6bd8ba913539385d73f/notes and materials/Practice Set.pdf -------------------------------------------------------------------------------- /notes and materials/Python-Cheat-Sheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anubhob435/pythonFiles/e8fe21829ff9f4e194e4f6bd8ba913539385d73f/notes and materials/Python-Cheat-Sheet.pdf -------------------------------------------------------------------------------- /notes and materials/algorithm-design-techniques_compress.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anubhob435/pythonFiles/e8fe21829ff9f4e194e4f6bd8ba913539385d73f/notes and materials/algorithm-design-techniques_compress.pdf -------------------------------------------------------------------------------- /notes and materials/seaborm.md: -------------------------------------------------------------------------------- 1 | # Seaborn: Statistical Data Visualization in Python 2 | 3 | ## Introduction 4 | Seaborn is a Python data visualization library based on matplotlib that provides a high-level interface for drawing attractive and informative statistical graphics. It's specifically designed to work well with pandas DataFrames and offers built-in themes for styling matplotlib graphics. 5 | 6 | ## Installation 7 | ```python 8 | # Using pip 9 | pip install seaborn 10 | 11 | # Using conda 12 | conda install seaborn 13 | ``` 14 | 15 | ## Key Features 16 | - **Built on Matplotlib**: Extends matplotlib's functionality with a more intuitive interface 17 | - **Integration with pandas**: Works seamlessly with pandas DataFrames 18 | - **Statistical estimation**: Automatic statistical estimation and plotting 19 | - **Beautiful default aesthetics**: Attractive themes and color palettes 20 | - **Complex visualizations with minimal code**: Simplifies the creation of complex visualizations 21 | 22 | ## Importing Seaborn 23 | ```python 24 | import seaborn as sns 25 | import matplotlib.pyplot as plt 26 | import pandas as pd 27 | import numpy as np 28 | ``` 29 | 30 | ## Main Plot Types 31 | 32 | ### 1. Relational Plots 33 | #### Scatter plots (scatterplot, relplot) 34 | ```python 35 | # Basic scatter plot 36 | tips = sns.load_dataset("tips") 37 | sns.scatterplot(x="total_bill", y="tip", data=tips) 38 | plt.show() 39 | 40 | # With additional dimensions using hue, size, and style 41 | sns.relplot( 42 | x="total_bill", y="tip", 43 | hue="smoker", size="size", 44 | style="time", data=tips 45 | ) 46 | plt.show() 47 | ``` 48 | 49 | #### Line plots (lineplot) 50 | ```python 51 | # Basic line plot 52 | fmri = sns.load_dataset("fmri") 53 | sns.lineplot(x="timepoint", y="signal", data=fmri) 54 | plt.show() 55 | ``` 56 | 57 | ### 2. Categorical Plots 58 | #### Bar plots (barplot) 59 | ```python 60 | # Bar plot showing mean values 61 | sns.barplot(x="day", y="total_bill", data=tips) 62 | plt.show() 63 | ``` 64 | 65 | #### Box plots (boxplot) 66 | ```python 67 | # Box plot 68 | sns.boxplot(x="day", y="total_bill", data=tips) 69 | plt.show() 70 | ``` 71 | 72 | #### Violin plots (violinplot) 73 | ```python 74 | # Violin plot combines box plot with kernel density estimation 75 | sns.violinplot(x="day", y="total_bill", data=tips) 76 | plt.show() 77 | ``` 78 | 79 | #### Count plots (countplot) 80 | ```python 81 | # Count plot - show counts of observations in each categorical bin 82 | sns.countplot(x="day", data=tips) 83 | plt.show() 84 | ``` 85 | 86 | ### 3. Distribution Plots 87 | #### Histogram (histplot) 88 | ```python 89 | # Histogram 90 | sns.histplot(tips["total_bill"], kde=True) 91 | plt.show() 92 | ``` 93 | 94 | #### Kernel Density Estimation (kdeplot) 95 | ```python 96 | # KDE plot 97 | sns.kdeplot(data=tips["total_bill"], shade=True) 98 | plt.show() 99 | ``` 100 | 101 | ### 4. Matrix Plots 102 | #### Heatmaps (heatmap) 103 | ```python 104 | # Generate a correlation matrix 105 | corr = tips.corr() 106 | # Plot heatmap 107 | sns.heatmap(corr, annot=True, cmap="coolwarm") 108 | plt.show() 109 | ``` 110 | 111 | #### Cluster maps (clustermap) 112 | ```python 113 | # Clustered heatmap 114 | sns.clustermap(corr, annot=True, cmap="coolwarm") 115 | plt.show() 116 | ``` 117 | 118 | ### 5. Regression Plots 119 | #### Simple regression (regplot) 120 | ```python 121 | # Simple regression plot 122 | sns.regplot(x="total_bill", y="tip", data=tips) 123 | plt.show() 124 | ``` 125 | 126 | #### Advanced regression (lmplot) 127 | ```python 128 | # Advanced regression with facets 129 | sns.lmplot(x="total_bill", y="tip", hue="smoker", col="time", data=tips) 130 | plt.show() 131 | ``` 132 | 133 | ### 6. Multi-plot Grids 134 | #### Pair plots (pairplot) 135 | ```python 136 | # Create pairwise relationships 137 | iris = sns.load_dataset("iris") 138 | sns.pairplot(iris, hue="species") 139 | plt.show() 140 | ``` 141 | 142 | #### Joint plots (jointplot) 143 | ```python 144 | # Joint distribution plot 145 | sns.jointplot(x="total_bill", y="tip", data=tips, kind="reg") 146 | plt.show() 147 | ``` 148 | 149 | ## Customizing Seaborn Plots 150 | 151 | ### Setting Themes 152 | ```python 153 | # Available themes: darkgrid, whitegrid, dark, white, ticks 154 | sns.set_theme(style="whitegrid") 155 | sns.set_theme(style="darkgrid") 156 | sns.set_theme(style="ticks") 157 | ``` 158 | 159 | ### Using Color Palettes 160 | ```python 161 | # Predefined palettes: deep, muted, pastel, bright, dark, colorblind 162 | sns.set_palette("pastel") 163 | 164 | # Using specific colors 165 | sns.set_palette(["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"]) 166 | ``` 167 | 168 | ### Figure Aesthetics 169 | ```python 170 | # Control figure aesthetics 171 | sns.set_context("paper") # Options: paper, notebook, talk, poster 172 | sns.set_context("talk", font_scale=1.4) 173 | ``` 174 | 175 | ## Working with Seaborn and pandas 176 | ```python 177 | # Creating a complex visualization from a pandas DataFrame 178 | titanic = sns.load_dataset("titanic") 179 | 180 | # Grid of plots 181 | g = sns.FacetGrid(titanic, col="survived", row="class", height=2.5, aspect=1.5) 182 | g.map_dataframe(sns.histplot, x="age") 183 | g.set_axis_labels("Age", "Count") 184 | g.set_titles(col_template="{col_name} = {col_var}", row_template="{row_name} = {row_var}") 185 | g.fig.subplots_adjust(top=0.9) 186 | g.fig.suptitle("Age Distribution by Survival Status and Class") 187 | plt.show() 188 | ``` 189 | 190 | ## Advanced Example: Combining Multiple Plot Types 191 | ```python 192 | # Create a figure with different plot types 193 | fig, axes = plt.subplots(2, 2, figsize=(15, 10)) 194 | 195 | # Plot 1: Box plot 196 | sns.boxplot(x="day", y="total_bill", data=tips, ax=axes[0, 0]) 197 | axes[0, 0].set_title("Box Plot") 198 | 199 | # Plot 2: Violin plot 200 | sns.violinplot(x="day", y="total_bill", data=tips, ax=axes[0, 1]) 201 | axes[0, 1].set_title("Violin Plot") 202 | 203 | # Plot 3: Bar plot 204 | sns.barplot(x="day", y="total_bill", data=tips, ax=axes[1, 0]) 205 | axes[1, 0].set_title("Bar Plot") 206 | 207 | # Plot 4: Swarm plot 208 | sns.swarmplot(x="day", y="total_bill", data=tips, ax=axes[1, 1]) 209 | axes[1, 1].set_title("Swarm Plot") 210 | 211 | plt.tight_layout() 212 | plt.show() 213 | ``` 214 | 215 | ## Tips for Effective Visualization with Seaborn 216 | 1. **Choose the right plot type** based on your data and what you want to communicate 217 | 2. **Use color consciously** - color should enhance understanding, not distract 218 | 3. **Don't overload your plots** with too many variables or dimensions 219 | 4. **Label everything clearly** - axes, titles, legends 220 | 5. **Consider your audience** when designing visualizations 221 | 222 | ## Resources for Learning More 223 | - [Seaborn Official Documentation](https://seaborn.pydata.org/) 224 | - [Seaborn Tutorial Gallery](https://seaborn.pydata.org/examples/index.html) 225 | - [Seaborn API Reference](https://seaborn.pydata.org/api.html) 226 | 227 | ## Conclusion 228 | Seaborn makes it easy to create beautiful and informative statistical visualizations in Python. Its tight integration with pandas and matplotlib provides a powerful toolkit for exploring and presenting data. Whether you're doing exploratory data analysis, creating visualizations for presentations, or generating publication-quality figures, Seaborn is an essential library in a data scientist's toolbox. 229 | -------------------------------------------------------------------------------- /notes and materials/ubuntucommands.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anubhob435/pythonFiles/e8fe21829ff9f4e194e4f6bd8ba913539385d73f/notes and materials/ubuntucommands.txt -------------------------------------------------------------------------------- /out/production/pythonFiles/Practice.jav: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class Practice { 3 | 4 | public static boolean isprime(int n){ 5 | 6 | boolean isprime= true; 7 | 8 | if(n <= 1){ 9 | return false; 10 | } 11 | else if(n == 2){ 12 | return true; 13 | } 14 | else{ 15 | for (int i = 2; i < n; i++) { 16 | 17 | if (n % i == 0) { 18 | isprime = false; 19 | break; 20 | } 21 | 22 | } 23 | } 24 | return isprime; 25 | } 26 | 27 | 28 | public static void main(String [] args){ 29 | 30 | 31 | } 32 | 33 | 34 | } 35 | 36 | 37 | -------------------------------------------------------------------------------- /out/production/pythonFiles/Question1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anubhob435/pythonFiles/e8fe21829ff9f4e194e4f6bd8ba913539385d73f/out/production/pythonFiles/Question1.class -------------------------------------------------------------------------------- /out/production/pythonFiles/Question10.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anubhob435/pythonFiles/e8fe21829ff9f4e194e4f6bd8ba913539385d73f/out/production/pythonFiles/Question10.class -------------------------------------------------------------------------------- /out/production/pythonFiles/Screenshot.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anubhob435/pythonFiles/e8fe21829ff9f4e194e4f6bd8ba913539385d73f/out/production/pythonFiles/Screenshot.jpg -------------------------------------------------------------------------------- /out/production/pythonFiles/Structure.py: -------------------------------------------------------------------------------- 1 | x = [] 2 | n = int(input("how many elements")) 3 | for i in range (0, n): 4 | y = int(input("enter element: ") 5 | x.append(y) 6 | 7 | print(x) -------------------------------------------------------------------------------- /out/production/pythonFiles/arraychallange.py: -------------------------------------------------------------------------------- 1 | def ArrayChallenge(num): 2 | def get_digits(n): 3 | return [int(d) for d in str(n)] 4 | 5 | digits = get_digits(num) # Extract initial digits 6 | multiplications = 0 7 | 8 | while True: 9 | # Check for adjacent duplicate numbers 10 | for i in range(len(digits) - 1): 11 | if digits[i] == digits[i + 1]: # Found adjacent duplicates 12 | return multiplications 13 | 14 | # Pick the first digit as the multiplier 15 | multiplier = digits[0] 16 | num *= multiplier # Multiply num 17 | multiplications += 1 18 | 19 | # Extract new digits and replace the existing list 20 | digits = get_digits(num) # Replace digits with new digits 21 | 22 | # Test case 23 | num = 8 24 | print(ArrayChallenge(num)) # Output should be 3 -------------------------------------------------------------------------------- /out/production/pythonFiles/arrchallange.py: -------------------------------------------------------------------------------- 1 | def ArrayChallenge(num): 2 | def get_digits(n): 3 | return [int(d) for d in str(n)] 4 | 5 | digits = get_digits(num) 6 | multiplications = 0 7 | 8 | while True: 9 | # Check for adjacent duplicates 10 | for i in range(len(digits) - 1): 11 | if digits[i] == digits[i + 1]: 12 | return multiplications 13 | 14 | # If no duplicates, multiply by one of its digits 15 | # Choose the first digit for simplicity 16 | multiplier = digits[0] 17 | new_num = num * multiplier 18 | new_digits = get_digits(new_num) 19 | 20 | # Append new digits to the list 21 | digits.extend(new_digits) 22 | num = new_num 23 | multiplications += 1 24 | 25 | # Test cases 26 | #print(ArrayChallenge(8)) # Output: 3 27 | print(ArrayChallenge(198)) # Output: 2 28 | #print(ArrayChallenge(134)) # Output: 1 29 | #print(ArrayChallenge(46)) # Output: 2 -------------------------------------------------------------------------------- /out/production/pythonFiles/ascii_art.txt: -------------------------------------------------------------------------------- 1 | @@@@@@@@@@@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2 | @@@@@@@@@@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 3 | @@@@@@@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 4 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 5 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 6 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 7 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 8 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 9 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 10 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 11 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 12 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%+. .-#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 13 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#::+%%+. *%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 14 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%* -... .+* *%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 15 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%* -. . .+* *%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 16 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#:.+#%+. *%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 17 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%+. .-#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 18 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 19 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 20 | @@@@@@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 21 | @@@@@@@@@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 22 | @@@@@@@@@@@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@@@@@ 23 | @@@@@@@@@@@@@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@@@@@@@@@@@@@@ 24 | @@@@@@@@@@@@@@@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 25 | @@@@@@@@@@@@@@@@@@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 26 | @@@@@@@@@@@@@@@@@@@@@%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 27 | @@@@@@@@@@@@@@@@@@@@@@@%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 28 | @@@@@@@@@@@@@@@@@@@@@@@@@%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 29 | -------------------------------------------------------------------------------- /out/production/pythonFiles/ascii_art_converter.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | import sys 3 | 4 | def convert_to_ascii(image_path, width=100, height=None): 5 | """ 6 | Convert an image to ASCII art. 7 | 8 | Args: 9 | image_path (str): Path to the image file 10 | width (int): Width of the output ASCII art (in characters) 11 | height (int): Height of the output ASCII art (in lines) 12 | If None, it's calculated to maintain aspect ratio 13 | 14 | Returns: 15 | str: ASCII art representation of the image 16 | """ 17 | try: 18 | # Open the image 19 | img = Image.open(image_path) 20 | 21 | # Calculate height to maintain aspect ratio if not provided 22 | if height is None: 23 | aspect_ratio = img.height / img.width 24 | height = int(width * aspect_ratio * 0.5) # 0.5 factor because characters are taller than wide 25 | 26 | # Resize the image 27 | img = img.resize((width, height)) 28 | 29 | # Convert to grayscale 30 | img = img.convert('L') 31 | 32 | # ASCII characters from darkest to lightest 33 | ascii_chars = '@%#*+=-:. ' 34 | 35 | # Convert pixels to ASCII characters 36 | pixels = list(img.getdata()) 37 | ascii_art = '' 38 | for i, pixel in enumerate(pixels): 39 | # Map pixel value (0-255) to ASCII character 40 | ascii_index = int(pixel * len(ascii_chars) / 256) 41 | ascii_art += ascii_chars[ascii_index] 42 | if (i + 1) % width == 0: 43 | ascii_art += '\n' 44 | 45 | return ascii_art 46 | 47 | except Exception as e: 48 | return f"Error: {str(e)}" 49 | 50 | def main(): 51 | if len(sys.argv) < 2: 52 | print("Usage: python ascii_art_converter.py [width] [height]") 53 | return 54 | 55 | image_path = sys.argv[1] 56 | width = int(sys.argv[2]) if len(sys.argv) > 2 else 100 57 | height = int(sys.argv[3]) if len(sys.argv) > 3 else None 58 | 59 | ascii_art = convert_to_ascii(image_path, width, height) 60 | print(ascii_art) 61 | 62 | # Optionally save to file 63 | save_option = input("Do you want to save the ASCII art to a file? (y/n): ") 64 | if save_option.lower() == 'y': 65 | output_file = input("Enter output file name (default: ascii_art.txt): ") or "ascii_art.txt" 66 | with open(output_file, 'w') as f: 67 | f.write(ascii_art) 68 | print(f"ASCII art saved to {output_file}") 69 | 70 | if __name__ == "__main__": 71 | main() 72 | -------------------------------------------------------------------------------- /out/production/pythonFiles/ascii_video.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | import os 4 | import time 5 | from datetime import datetime 6 | from PIL import Image, ImageDraw, ImageFont 7 | import moviepy.editor as mp # Updated import for better compatibility 8 | 9 | # Check for CUDA availability at the start 10 | use_cuda = False 11 | try: 12 | if cv2.cuda.getCudaEnabledDeviceCount() > 0: 13 | use_cuda = True 14 | print("CUDA is available. Attempting to use GPU for OpenCV operations.") 15 | else: 16 | print("CUDA not available or OpenCV not built with CUDA support. Using CPU for OpenCV operations.") 17 | except AttributeError: 18 | print("cv2.cuda module not found. Using CPU for OpenCV operations.") 19 | 20 | def get_ascii_char(pixel_value): 21 | # ASCII characters from darkest to lightest 22 | ascii_chars = "@%#*+=-:. " 23 | # Map pixel value (0-255) to ASCII character 24 | index = int(pixel_value / 255 * (len(ascii_chars) - 1)) 25 | return ascii_chars[index] 26 | 27 | def frame_to_ascii(frame, width=100): 28 | # Calculate height to maintain aspect ratio 29 | aspect_ratio = frame.shape[1] / frame.shape[0] 30 | height = int(width / aspect_ratio / 2) # Dividing by 2 because characters are taller than wide 31 | 32 | resized = None # Initialize resized variable 33 | 34 | if use_cuda: 35 | try: 36 | # Upload frame to GPU 37 | gpu_frame = cv2.cuda_GpuMat() 38 | gpu_frame.upload(frame) 39 | 40 | # Convert color on GPU 41 | gpu_gray = cv2.cuda.cvtColor(gpu_frame, cv2.COLOR_BGR2GRAY) 42 | 43 | # Resize on GPU 44 | gpu_resized = cv2.cuda.resize(gpu_gray, (width, height)) 45 | 46 | # Download result back to CPU 47 | resized = gpu_resized.download() 48 | 49 | except cv2.error as e: 50 | print(f"CUDA error during processing: {e}. Falling back to CPU for this frame.") 51 | # Fallback to CPU if CUDA operations fail for this frame 52 | gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 53 | resized = cv2.resize(gray, (width, height)) 54 | except Exception as e: # Catch other potential CUDA-related errors 55 | print(f"An unexpected error occurred with CUDA: {e}. Falling back to CPU for this frame.") 56 | gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 57 | resized = cv2.resize(gray, (width, height)) 58 | 59 | # If CUDA is not used or fallback occurred 60 | if resized is None: 61 | # CPU implementation 62 | gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 63 | resized = cv2.resize(gray, (width, height)) 64 | 65 | # Convert the pixels to ASCII characters 66 | ascii_frame = "" 67 | for row in resized: 68 | for pixel in row: 69 | ascii_frame += get_ascii_char(pixel) 70 | ascii_frame += "\n" 71 | 72 | return ascii_frame 73 | 74 | def ascii_to_image(ascii_text, font_size=15, bg_color=(0, 0, 0), text_color=(255, 255, 255)): 75 | # Calculate image dimensions based on ASCII text 76 | lines = ascii_text.split('\n') 77 | char_width = font_size / 2 78 | img_width = int(max(len(line) for line in lines) * char_width) 79 | img_height = int(len(lines) * font_size) 80 | 81 | # Create a new image 82 | img = Image.new('RGB', (img_width, img_height), color=bg_color) 83 | draw = ImageDraw.Draw(img) 84 | 85 | # Try to load a monospace font (will fall back to default if not available) 86 | try: 87 | font = ImageFont.truetype("Courier", font_size) 88 | except IOError: 89 | font = ImageFont.load_default() 90 | 91 | # Draw the ASCII art on the image 92 | y = 0 93 | for line in lines: 94 | draw.text((0, y), line, font=font, fill=text_color) 95 | y += font_size 96 | 97 | return np.array(img) 98 | 99 | def create_output_dir(): 100 | # Create output directory if it doesn't exist 101 | output_dir = os.path.join(os.path.dirname(__file__), "outputs") 102 | if not os.path.exists(output_dir): 103 | os.makedirs(output_dir) 104 | return output_dir 105 | 106 | def process_video(video_path, output_width=100, fps=None): 107 | print(f"Processing video: {video_path}") 108 | 109 | # Extract filename without extension 110 | video_filename = os.path.basename(video_path) 111 | video_name = os.path.splitext(video_filename)[0] 112 | 113 | # Create timestamp for unique output filenames 114 | timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") 115 | 116 | # Create output directory 117 | output_dir = create_output_dir() 118 | 119 | # Output path for ASCII video 120 | output_path = os.path.join(output_dir, f"{video_name}_ascii_{timestamp}.mp4") 121 | 122 | # Load the video 123 | video_clip = mp.VideoFileClip(video_path) 124 | 125 | # Use original fps if not specified 126 | if fps is None: 127 | fps = video_clip.fps 128 | 129 | # Extract audio 130 | audio = video_clip.audio 131 | 132 | # Process frames and convert to ASCII images 133 | print("Converting frames to ASCII...") 134 | 135 | # Temporary list to store the ASCII frames 136 | ascii_frames = [] 137 | 138 | # Get total number of frames for progress reporting 139 | total_frames = int(video_clip.duration * video_clip.fps) 140 | processed_frames = 0 141 | 142 | # Process each frame 143 | for frame in video_clip.iter_frames(fps=fps): 144 | # Convert frame to ASCII text (will use GPU if available and working) 145 | ascii_text = frame_to_ascii(frame, width=output_width) 146 | 147 | # Convert ASCII text to image 148 | ascii_image = ascii_to_image(ascii_text) 149 | 150 | # Add frame to list 151 | ascii_frames.append(ascii_image) 152 | 153 | # Update progress 154 | processed_frames += 1 155 | if processed_frames % 10 == 0: 156 | print(f"Processed {processed_frames}/{total_frames} frames ({processed_frames/total_frames*100:.1f}%)") 157 | 158 | print("Creating video from ASCII frames...") 159 | # Create a video from the ASCII frames 160 | ascii_clip = mp.ImageSequenceClip(ascii_frames, fps=fps) 161 | 162 | # Add the original audio to the ASCII video 163 | if audio is not None: 164 | ascii_clip = ascii_clip.set_audio(audio) 165 | 166 | # Write the result to file 167 | print(f"Writing ASCII video to {output_path}") 168 | ascii_clip.write_videofile(output_path, codec='libx264') 169 | 170 | # Clean up 171 | video_clip.close() 172 | if audio is not None: 173 | audio.close() 174 | ascii_clip.close() 175 | 176 | print(f"ASCII video saved to {output_path}") 177 | return output_path 178 | 179 | def main(): 180 | # Default sample video path 181 | default_video = os.path.join(os.path.dirname(os.path.dirname(__file__)), "videos", "sample1.mp4") 182 | 183 | # Get user input 184 | video_path = input(f"Enter path to video file (or press Enter to use sample: {default_video}): ") 185 | if not video_path: 186 | video_path = default_video 187 | 188 | if not os.path.exists(video_path): 189 | print(f"Error: File {video_path} not found.") 190 | return 191 | 192 | # Ask for ASCII width 193 | try: 194 | width = input("Enter ASCII width (default: 100): ") 195 | width = int(width) if width else 100 196 | except ValueError: 197 | print("Invalid input, using default width of 100") 198 | width = 100 199 | 200 | # Ask for FPS 201 | try: 202 | fps_input = input("Enter desired FPS (press Enter to use original): ") 203 | fps = int(fps_input) if fps_input else None 204 | except ValueError: 205 | print("Invalid input, using original FPS") 206 | fps = None 207 | 208 | # Process the video 209 | start_time = time.time() 210 | output_file = process_video(video_path, output_width=width, fps=fps) 211 | end_time = time.time() 212 | 213 | print(f"Processing completed in {end_time - start_time:.2f} seconds.") 214 | print(f"ASCII video saved to: {output_file}") 215 | 216 | if __name__ == "__main__": 217 | main() -------------------------------------------------------------------------------- /out/production/pythonFiles/challange32.py: -------------------------------------------------------------------------------- 1 | print("Hello World") 2 | -------------------------------------------------------------------------------- /out/production/pythonFiles/data2.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | import matplotlib.pyplot as plt 4 | 5 | def is_prime(n): 6 | if n < 2: 7 | return False 8 | for i in range(2, int(np.sqrt(n)) + 1): 9 | if n % i == 0: 10 | return False 11 | return True 12 | 13 | # Generate prime numbers up to 100 14 | numbers = range(2, 101) 15 | primes = [num for num in numbers if is_prime(num)] 16 | 17 | # Create the plot 18 | plt.figure(figsize=(10, 6)) 19 | plt.plot(primes, [1] * len(primes), 'ro', markersize=8) 20 | plt.grid(True) 21 | plt.title('Prime Numbers up to 100') 22 | plt.xlabel('Numbers') 23 | plt.yticks([]) # Hide y-axis ticks 24 | plt.show() -------------------------------------------------------------------------------- /out/production/pythonFiles/deployment.py: -------------------------------------------------------------------------------- 1 | #deploying repo 2 | -------------------------------------------------------------------------------- /out/production/pythonFiles/doughnut.py: -------------------------------------------------------------------------------- 1 | import os 2 | import math 3 | import time 4 | import numpy as np 5 | 6 | def clear_screen(): 7 | os.system('cls' if os.name == 'nt' else 'clear') 8 | 9 | def render_frame(A, B): 10 | # Precompute sines and cosines of A and B 11 | cosA, sinA = math.cos(A), math.sin(A) 12 | cosB, sinB = math.cos(B), math.sin(B) 13 | 14 | # Screen dimensions 15 | width, height = 80, 24 16 | 17 | # Buffer for the output 18 | output = [[' ' for _ in range(width)] for _ in range(height)] 19 | 20 | # Z-buffer for depth 21 | zbuffer = [[0 for _ in range(width)] for _ in range(height)] 22 | 23 | # Donut parameters 24 | R1 = 1 # Distance from center to center of torus tube 25 | R2 = 2 # Radius of torus tube 26 | K2 = 5 # Distance from viewer to donut 27 | K1 = width * K2 * 3 / (8 * (R1 + R2)) # Scaling factor 28 | 29 | # Rotation around the y-axis (vertical) 30 | for theta in np.linspace(0, 2 * math.pi, 50): 31 | cosTheta, sinTheta = math.cos(theta), math.sin(theta) 32 | 33 | # Rotation around the x-axis (horizontal) 34 | for phi in np.linspace(0, 2 * math.pi, 20): 35 | cosPhi, sinPhi = math.cos(phi), math.sin(phi) 36 | 37 | # 3D coordinates of the point on the torus 38 | x = R2 * cosTheta + R1 39 | y = R2 * sinTheta 40 | 41 | # 3D rotation 42 | x1 = x * cosB - y * sinB 43 | y1 = x * sinB + y * cosB 44 | z1 = R2 * cosPhi + R1 45 | 46 | # Rotate around x-axis 47 | y2 = y1 * cosA - z1 * sinA 48 | z2 = y1 * sinA + z1 * cosA 49 | 50 | # 3D to 2D projection 51 | z = 1 / (K2 + z2) 52 | x3 = int(width / 2 + K1 * x1 * z) 53 | y3 = int(height / 2 - K1 * y2 * z) 54 | 55 | # Calculate luminance 56 | L = cosPhi * cosTheta * sinB - cosA * cosTheta * sinPhi - sinA * sinTheta + cosB * (cosA * sinTheta - cosTheta * sinA * sinPhi) 57 | 58 | # Only render if point is visible and in front of previous points 59 | if 0 <= x3 < width and 0 <= y3 < height and z > zbuffer[y3][x3]: 60 | zbuffer[y3][x3] = z 61 | luminance_index = int(L * 8) 62 | # ASCII chars by increasing luminance 63 | chars = '.,-~:;=!*#$@' 64 | output[y3][x3] = chars[max(0, min(luminance_index, len(chars) - 1))] 65 | 66 | # Render the frame 67 | result = '\n'.join(''.join(row) for row in output) 68 | clear_screen() 69 | print(result) 70 | 71 | def main(): 72 | A = 0 73 | B = 0 74 | try: 75 | while True: 76 | render_frame(A, B) 77 | A += 0.07 78 | B += 0.03 79 | time.sleep(0.03) 80 | except KeyboardInterrupt: 81 | print("Animation stopped") 82 | 83 | if __name__ == "__main__": 84 | main() 85 | -------------------------------------------------------------------------------- /out/production/pythonFiles/dsaa.py: -------------------------------------------------------------------------------- 1 | import pyfiglet 2 | import time 3 | 4 | def show_word_in_figlet(word): 5 | # Render the word in figlet style 6 | ascii_art = pyfiglet.figlet_format(word, font="roman") 7 | print(ascii_art) 8 | 9 | def read_lyrics_and_show_figlet(file_path): 10 | try: 11 | # Open the lyrics.txt file 12 | with open(file_path, 'r') as file: 13 | # Read the entire content of the file 14 | lyrics = file.read() 15 | 16 | # Split the text into individual words 17 | words = lyrics.split() 18 | 19 | # Loop through each word and display it in figlet 20 | for word in words: 21 | show_word_in_figlet(word) 22 | time.sleep(0.4) # Optional: Pause between words for better visualization 23 | except FileNotFoundError: 24 | print(f"Error: The file '{file_path}' does not exist.") 25 | except Exception as e: 26 | print(f"An error occurred: {e}") 27 | 28 | # Path to the lyrics.txt file 29 | file_path = 'lyrics.txt' 30 | 31 | # Call the function to read lyrics and display in figlet 32 | read_lyrics_and_show_figlet(file_path) 33 | #nothing comit 34 | -------------------------------------------------------------------------------- /out/production/pythonFiles/encrypt.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import json 3 | import os 4 | 5 | def create_and_store_password(): 6 | """ 7 | Ask user for username and password, encrypt the password using SHA-256, 8 | and store it in passwords.json file. 9 | """ 10 | username = input("Enter username: ") 11 | password = input("Enter password: ") 12 | 13 | # Encrypt password using SHA-256 14 | hashed_password = hashlib.sha256(password.encode()).hexdigest() 15 | 16 | # Initialize empty dict if file doesn't exist or load existing data 17 | if os.path.exists("passwords.json"): 18 | with open("passwords.json", "r") as file: 19 | try: 20 | passwords_dict = json.load(file) 21 | except json.JSONDecodeError: 22 | passwords_dict = {} 23 | else: 24 | passwords_dict = {} 25 | 26 | # Store username and hashed password 27 | passwords_dict[username] = hashed_password 28 | 29 | # Write back to file 30 | with open("passwords.json", "w") as file: 31 | json.dump(passwords_dict, file, indent=4) 32 | 33 | print(f"Password for {username} has been stored successfully!") 34 | 35 | def fetch_and_check_password(): 36 | """ 37 | Ask user for username and password, verify if the password matches 38 | the stored hashed password for that username. 39 | """ 40 | username = input("Enter username: ") 41 | password = input("Enter password: ") 42 | 43 | # Hash the input password 44 | hashed_password = hashlib.sha256(password.encode()).hexdigest() 45 | 46 | # Check if passwords.json exists 47 | if not os.path.exists("passwords.json"): 48 | print("No passwords have been stored yet.") 49 | return 50 | 51 | # Load passwords from file 52 | with open("passwords.json", "r") as file: 53 | try: 54 | passwords_dict = json.load(file) 55 | except json.JSONDecodeError: 56 | print("Password file is corrupted or empty.") 57 | return 58 | 59 | # Check if username exists and password matches 60 | if username in passwords_dict: 61 | if passwords_dict[username] == hashed_password: 62 | print("Verified! Password is correct.") 63 | else: 64 | print("Password is incorrect.") 65 | else: 66 | print(f"Username '{username}' not found.") 67 | 68 | # Example usage: 69 | if __name__ == "__main__": 70 | print("1. Create and store a password") 71 | print("2. Verify a password") 72 | choice = input("Enter your choice (1 or 2): ") 73 | 74 | if choice == "1": 75 | create_and_store_password() 76 | elif choice == "2": 77 | fetch_and_check_password() 78 | else: 79 | print("Invalid choice!") 80 | -------------------------------------------------------------------------------- /out/production/pythonFiles/encrytionDecryption.py: -------------------------------------------------------------------------------- 1 | def caesar_cipher(): 2 | try: 3 | choice = input("Choose operation - Encrypt (E) / Decrypt (D): ").upper() 4 | if choice not in ['E', 'D']: 5 | raise ValueError("Invalid choice. Please enter 'E' or 'D'.") 6 | 7 | text = input("Enter the text: ") 8 | shift = int(input("Enter the shift value (integer): ")) 9 | 10 | result = "" 11 | for char in text: 12 | if char.isalpha(): 13 | offset = 65 if char.isupper() else 97 14 | if choice == 'E': 15 | shifted_char = chr((ord(char) - offset + shift) % 26 + offset) 16 | else: 17 | shifted_char = chr((ord(char) - offset - shift) % 26 + offset) 18 | 19 | result += shifted_char 20 | print(f"{char} -> {shifted_char}") 21 | else: 22 | result += char 23 | 24 | print(f"Result: {result}") 25 | except ValueError as ve: 26 | print(f"Error: {ve}") 27 | 28 | 29 | # Diffie-Hellman Key Exchange Implementation 30 | 31 | def diffie_hellman(): 32 | try: 33 | p = int(input("Enter a prime number (p): ")) 34 | g = int(input("Enter a primitive root (g): ")) 35 | 36 | alice_private = int(input("Alice's private key: ")) 37 | bob_private = int(input("Bob's private key: ")) 38 | 39 | alice_public = (g ** alice_private) % p 40 | bob_public = (g ** bob_private) % p 41 | 42 | print(f"Alice's Public Key: {alice_public}") 43 | print(f"Bob's Public Key: {bob_public}") 44 | 45 | alice_shared_secret = (bob_public ** alice_private) % p 46 | bob_shared_secret = (alice_public ** bob_private) % p 47 | 48 | print(f"Alice's Shared Secret: {alice_shared_secret}") 49 | print(f"Bob's Shared Secret: {bob_shared_secret}") 50 | 51 | if alice_shared_secret == bob_shared_secret: 52 | print("Shared secret keys match!") 53 | else: 54 | print("Error: Shared secrets do not match!") 55 | except ValueError: 56 | print("Error: Invalid input! Please enter integers only.") 57 | 58 | 59 | if __name__ == "__main__": 60 | print("1. Caesar Cipher") 61 | print("2. Diffie-Hellman Key Exchange") 62 | choice = input("Choose an option (1/2): ") 63 | 64 | if choice == '1': 65 | caesar_cipher() 66 | elif choice == '2': 67 | diffie_hellman() 68 | else: 69 | print("Invalid choice! Please select either 1 or 2.") 70 | -------------------------------------------------------------------------------- /out/production/pythonFiles/fibonacci.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import numpy as np 3 | from matplotlib.animation import FuncAnimation 4 | import matplotlib.patches as patches 5 | from matplotlib.colors import LinearSegmentedColormap 6 | import matplotlib.gridspec as gridspec 7 | 8 | def generate_fibonacci(n): 9 | """Generate Fibonacci sequence up to n terms.""" 10 | fib_sequence = [0, 1] 11 | for i in range(2, n): 12 | fib_sequence.append(fib_sequence[i-1] + fib_sequence[i-2]) 13 | return fib_sequence 14 | 15 | def fibonacci_spiral_animation(n=16, interval=500, save_gif=False): 16 | """Create an enhanced animated Fibonacci spiral with sequence visualization.""" 17 | # Create custom colormap for better visual appeal 18 | colors = [(0.2, 0.4, 0.6), (0.4, 0.7, 0.9), (0.95, 0.5, 0.1), (0.9, 0.3, 0.3)] 19 | custom_cmap = LinearSegmentedColormap.from_list("fibonacci_colors", colors, N=n) 20 | 21 | # Generate complete Fibonacci sequence for the graph 22 | fibonacci_sequence = generate_fibonacci(n+5) 23 | 24 | # Set up the figure with grid layout - modified to remove the bar chart column 25 | fig = plt.figure(figsize=(16, 10)) 26 | gs = gridspec.GridSpec(2, 1, height_ratios=[4, 1]) 27 | 28 | # Spiral animation subplot - now takes full width 29 | ax_spiral = plt.subplot(gs[0, 0]) 30 | ax_spiral.set_xlim(-150, 150) 31 | ax_spiral.set_ylim(-150, 150) 32 | ax_spiral.set_title('Fibonacci Spiral', fontsize=18, fontweight='bold') 33 | ax_spiral.axis('equal') 34 | ax_spiral.axis('off') 35 | 36 | # Golden ratio information subplot 37 | ax_info = plt.subplot(gs[1, 0]) 38 | ax_info.axis('off') 39 | 40 | # Add title to the figure 41 | fig.suptitle('The Fibonacci Sequence & Golden Spiral', fontsize=22, fontweight='bold') 42 | 43 | # Initialize elements 44 | rectangles = [] 45 | spirals = [] 46 | text_artists = [] 47 | 48 | def init(): 49 | return [] 50 | 51 | def animate(frame): 52 | # Clear previous frame elements 53 | for rect in rectangles: 54 | rect.remove() 55 | rectangles.clear() 56 | 57 | if spirals: 58 | spirals[0].remove() 59 | spirals.clear() 60 | 61 | for text in text_artists: 62 | text.remove() 63 | text_artists.clear() 64 | 65 | # Create Fibonacci sequence up to current frame 66 | fib_values = fibonacci_sequence[:frame+2] 67 | 68 | # Draw rectangles for the golden spiral 69 | x, y = 0, 0 70 | a, b = 0, 1 71 | 72 | # Add spiral center marker 73 | center_marker = ax_spiral.plot(0, 0, 'o', color='black', markersize=5)[0] 74 | rectangles.append(center_marker) 75 | 76 | for i in range(min(frame + 1, n)): 77 | color = custom_cmap(i/n) 78 | 79 | if i % 4 == 0: 80 | rect = patches.Rectangle((x, y), b, a, fill=False, 81 | edgecolor=color, linewidth=2) 82 | x += b 83 | elif i % 4 == 1: 84 | rect = patches.Rectangle((x-a, y), a, b, fill=False, 85 | edgecolor=color, linewidth=2) 86 | y += b 87 | elif i % 4 == 2: 88 | rect = patches.Rectangle((x-a-b, y), b, a, fill=False, 89 | edgecolor=color, linewidth=2) 90 | x -= b 91 | else: 92 | rect = patches.Rectangle((x-a, y-a), a, b, fill=False, 93 | edgecolor=color, linewidth=2) 94 | y -= b 95 | 96 | ax_spiral.add_patch(rect) 97 | rectangles.append(rect) 98 | 99 | # Add rectangle dimension text for better understanding 100 | size_text = ax_spiral.text(x-a/2, y-b/2, f"{b}×{a}", 101 | ha='center', va='center', fontsize=8, 102 | color='black', alpha=0.7) 103 | text_artists.append(size_text) 104 | 105 | a, b = b, a+b 106 | 107 | # Draw the spiral for the current frame 108 | theta = np.linspace(0, (frame/2 + 1) * np.pi, 1000) 109 | golden_ratio = (1 + np.sqrt(5)) / 2 110 | r = golden_ratio ** (theta / np.pi) 111 | spiral, = ax_spiral.plot(r * np.cos(theta), r * np.sin(theta), color='red', linewidth=2.5) 112 | spirals.append(spiral) 113 | 114 | # Display golden ratio approximation 115 | if len(fib_values) >= 3: 116 | ratio_text = f"F({frame+1})/F({frame}) = {fib_values[-1]}/{fib_values[-2]} = {fib_values[-1]/fib_values[-2]:.6f}" 117 | golden_text = f"Golden Ratio (φ) = {(1 + np.sqrt(5))/2:.6f}" 118 | diff = abs((fib_values[-1]/fib_values[-2]) - (1 + np.sqrt(5))/2) 119 | accuracy = f"Difference: {diff:.6f}" 120 | 121 | # Add sequence display to info panel since we removed the bar chart 122 | sequence_text = f"Fibonacci Sequence: {', '.join(map(str, fib_values))}" 123 | 124 | info_text = ax_info.text(0.5, 0.5, 125 | f"{sequence_text}\n\n{ratio_text}\n{golden_text}\n{accuracy}\n\n" 126 | f"As the sequence progresses, the ratio between consecutive\n" 127 | f"Fibonacci numbers approaches the Golden Ratio (φ).", 128 | ha='center', va='center', fontsize=12, 129 | bbox=dict(boxstyle='round', facecolor='lightyellow', alpha=0.9)) 130 | text_artists.append(info_text) 131 | 132 | # Add current frame info to spiral plot 133 | if frame >= 0: 134 | frame_text = ax_spiral.text(0.05, 0.95, 135 | f"Step: {frame+1}\nCurrent Fibonacci: {fib_values[frame+1]}", 136 | transform=ax_spiral.transAxes, fontsize=12, 137 | verticalalignment='top', 138 | bbox=dict(boxstyle='round', facecolor='white', alpha=0.8)) 139 | text_artists.append(frame_text) 140 | 141 | # Combine all artists 142 | all_artists = rectangles + spirals + text_artists 143 | return all_artists 144 | 145 | # Set up animation with progress bar 146 | from tqdm import tqdm 147 | progress_bar = tqdm(total=n, desc="Generating animation") 148 | 149 | def update_progress(frame, *args): 150 | progress_bar.update(1) 151 | return animate(frame) 152 | 153 | # Limit the animation to exactly n frames (stopping at step 16 by default) 154 | anim = FuncAnimation(fig, update_progress, frames=range(n), 155 | init_func=init, blit=True, 156 | interval=interval, repeat=False) # Changed repeat to False to stop at the last frame 157 | 158 | # Add animation control buttons 159 | ax_buttons = plt.axes([0.81, 0.02, 0.1, 0.04]) 160 | button_pause = plt.Button(ax_buttons, 'Pause/Play') 161 | 162 | def toggle_pause(event): 163 | if anim.event_source: 164 | if anim.event_source.running: 165 | anim.event_source.stop() 166 | else: 167 | anim.event_source.start() 168 | 169 | button_pause.on_clicked(toggle_pause) 170 | 171 | plt.tight_layout(rect=[0, 0, 1, 0.95]) # Adjust layout to accommodate the title 172 | 173 | # Save animation if requested with error handling 174 | if save_gif: 175 | try: 176 | from datetime import datetime 177 | import os 178 | 179 | # Create output directory if it doesn't exist 180 | output_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "outputs") 181 | os.makedirs(output_dir, exist_ok=True) 182 | 183 | # Generate timestamp for unique filename 184 | timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") 185 | filename = f'fibonacci_spiral_{timestamp}.gif' 186 | filepath = os.path.join(output_dir, filename) 187 | 188 | # Save with progress indicator 189 | print(f"Saving animation to: {filepath}") 190 | anim.save(filepath, writer='pillow', fps=2, dpi=120) 191 | print(f"Animation saved successfully!") 192 | except Exception as e: 193 | print(f"Error saving animation: {str(e)}") 194 | 195 | # Close progress bar after animation is complete 196 | progress_bar.close() 197 | 198 | return fig, anim 199 | 200 | if __name__ == "__main__": 201 | # Create and display animation - ensuring we stop at exactly step 16 202 | fig, anim = fibonacci_spiral_animation(n=16, interval=800, save_gif=True) 203 | 204 | plt.show() -------------------------------------------------------------------------------- /out/production/pythonFiles/graphchallange.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict, deque 2 | 3 | def GraphChallenge(strarr): 4 | # Create an adjacency list representation of the graph 5 | graph = defaultdict(list) 6 | for path in strarr: 7 | node1, node2 = path.split('-') 8 | graph[node1].append(node2) 9 | graph[node2].append(node1) 10 | 11 | # Perform BFS to find the longest path 12 | max_path_length = 0 13 | for node in graph: 14 | queue = deque([(node, 0)]) # (node, path_length) 15 | visited = set() 16 | while queue: 17 | current_node, path_length = queue.popleft() 18 | if current_node not in visited: 19 | visited.add(current_node) 20 | max_path_length = max(max_path_length, path_length) 21 | for neighbor in graph[current_node]: 22 | queue.append((neighbor, path_length + 1)) 23 | 24 | return max_path_length 25 | 26 | print(GraphChallenge(["b-e", "b-c","c-d", "a-b", "e-f"])) # Output: 4 27 | print(GraphChallenge(["b-a", "c-e", "b-c", "d-c"])) # Output: 3 28 | -------------------------------------------------------------------------------- /out/production/pythonFiles/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Voice Recognition 7 | 8 | 9 | 12 | 13 | 14 | 17 |
18 |

Voice Recognition

19 | 23 |
Tap the microphone to start speaking...
24 |
25 | 26 | Ready 27 | 34 |
35 |
36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /out/production/pythonFiles/leaaldownload.py: -------------------------------------------------------------------------------- 1 | def wait_for_results_and_download_judgments(driver): 2 | try: 3 | print("Waiting for results to load...") 4 | WebDriverWait(driver, 20).until( 5 | EC.presence_of_element_located((By.ID, "showList")) 6 | ) 7 | time.sleep(2) 8 | 9 | # Collect judgment links 10 | show_list_div = driver.find_element(By.ID, "showList") 11 | rows = show_list_div.find_elements(By.TAG_NAME, "tr") 12 | 13 | print("Collecting all the links for only Judgments(not for orders)") 14 | 15 | judgment_links = [] 16 | for row in rows: 17 | links = row.find_elements(By.TAG_NAME, "a") 18 | for link in links: 19 | if link.text.strip().lower() == "judgment": 20 | href = link.get_attribute("href") 21 | if href: 22 | judgment_links.append(href) 23 | 24 | print(f"Found {len(judgment_links)} judgment link(s).") 25 | 26 | for i, pdf_url in enumerate(judgment_links, 1): 27 | print(f"Downloading judgment #{i}") 28 | driver.execute_script("window.open('');") 29 | driver.switch_to.window(driver.window_handles[-1]) 30 | driver.get(pdf_url) 31 | time.sleep(5) # Allow time for download 32 | driver.close() 33 | driver.switch_to.window(driver.window_handles[0]) 34 | time.sleep(1) 35 | 36 | print(f"All available judgments downloaded: {len(judgment_links)}") 37 | except Exception as e: 38 | print(f"Error while fetching judgments: {e}") -------------------------------------------------------------------------------- /out/production/pythonFiles/lyrics.txt: -------------------------------------------------------------------------------- 1 | Diet mountain dew, baby, New York City 2 | Never was there ever a girl so pretty 3 | Do you think we'll be in love forever? 4 | Do you think we'll be in love? 5 | 6 | Diet mountain dew, baby, New York City 7 | Can we hit it now low down and gritty? 8 | Do you think we'll be in love forever? 9 | Do you think we'll be in love? 10 | -------------------------------------------------------------------------------- /out/production/pythonFiles/maximumSubArray.py: -------------------------------------------------------------------------------- 1 | def max_subarray_sum(nums): 2 | max_ending = max_so_far = nums[0] 3 | for x in nums[1:]: 4 | max_ending = max(x, max_ending + x) 5 | max_so_far = max(max_so_far, max_ending) 6 | return max_so_far 7 | 8 | if __name__ == "__main__": 9 | arr = [1, -3, 2, 1, -1, 3, -2] 10 | print(max_subarray_sum(arr)) -------------------------------------------------------------------------------- /out/production/pythonFiles/mbappe.txt: -------------------------------------------------------------------------------- 1 | **************************************************************************************************** 2 | *************************************************########**************************++++++=++++****** 3 | ***********************************************#%%%%%%%%##*************************++++--=-===****** 4 | ***********************************************######%#####****************************-------****** 5 | **********************************************####**####%%#***************************************** 6 | **********************************************###%%%%###%%#***************************************** 7 | **********************************************####%%####%#****************************************** 8 | ***********************************************%%***##%%%******************************************* 9 | **********************************************+**+****##******************************************** 10 | ******************************************+=-:=************--=+************************************* 11 | *************************************+=--:....-#****###**#*:...:---=***********++++++*++++++++++++++ 12 | ***********************************+-.....:...:-*##****##*-....... .:=**++++++++++++++++++++++++++++ 13 | **********************************+:...::::......:=++++=-...:===-.....-+++++++++++++++++++++++++++++ 14 | *+*******************************+:...::....................:=+++=:....:++++++++++++++++++++++++++++ 15 | *********************************=......:::...............:=::++++=::::.-+++++++++++++++++++++++++++ 16 | *********+******+*+*******+++++*+:...:-==+=::::::.........:---=++*+=--:::++++++********+++++++++++++ 17 | ++********++**++++++++++++++++++:..:-++++=---:::::::::..::::--==+***-::::=++++++**++**++++++++***+++ 18 | +******++++++++++++++++++++++++=:::-+++++=----------:::::::-+==-=+**-.::::=+++++++++++++++++++++++++ 19 | ++++++**+**++++++++++++++++++++*#*+++**+=--========--:::---=====-=+===++---+++++++++++++++++++++++++ 20 | +++++++++++++++++++++++++++++++++++****=-=-===--=-===-==--=======++++****+++++++++++++++++++++++++++ 21 | +++++++++++++++++++++++++++++++++**#*+*=-==++===--=*++***---==+++*+++********+++++++++++++++++++++++ 22 | ++++++++++++++++++++++++++++++****#*++++++=======--**+*+*---===+**++++**#******+++++++++++++++++++++ 23 | +++++++++++++++++++*++++++++**#####*+++*++=---:::::++=**+:---===+++++++*#####**++++++++++++++++++*++ 24 | +++++++++++++++*+++*++++++++*#####*+++++==----:::::--:==------=+=+++++++**####*+++++++++++++++++++++ 25 | +++++++++++++++++++++++++++++*#**+++++++-::::---::::::.:::::---=+++++++++++***++++++++++++++++++++++ 26 | +++++++++++++++++++++++++++++++++++++++=---::::::::.:::::::----=+++++++++++++++++++++++*++**++++++++ 27 | +++++++++++++++++++++++++++++++++++++++-::-::------:::::::::::::=+++++++++++++++++++++++++++++++++++ 28 | +++++++++++++++++++++++++++++++++++++++:.::::::::-----::::::::::-+++++++++++++++++++++++++++++++++++ 29 | -------------------------------------------------------------------------------- /out/production/pythonFiles/mergesort.py: -------------------------------------------------------------------------------- 1 | #Merge Sort 2 | 3 | def merge_sort(arr): 4 | if len(arr) > 1: 5 | mid = len(arr) // 2 6 | left = arr[:mid] 7 | right = arr[mid:] 8 | 9 | merge_sort(left) 10 | merge_sort(right) 11 | 12 | i = j = k = 0 13 | 14 | while i < len(left) and j < len(right): 15 | if left[i] < right[j]: 16 | arr[k] = left[i] 17 | i += 1 18 | else: 19 | arr[k] = right[j] 20 | j += 1 21 | k += 1 22 | 23 | while i < len(left): 24 | arr[k] = left[i] 25 | i += 1 26 | k += 1 27 | 28 | while j < len(right): 29 | arr[k] = right[j] 30 | j += 1 31 | k += 1 -------------------------------------------------------------------------------- /out/production/pythonFiles/new_file.py: -------------------------------------------------------------------------------- 1 | def greet(name): 2 | """A simple function that prints a greeting message""" 3 | return f"Hello, {name}!" 4 | 5 | def main(): 6 | # Example usage 7 | user_name = input("Enter your name: ") 8 | message = greet(user_name) 9 | print(message) 10 | 11 | if __name__ == "__main__": 12 | main() -------------------------------------------------------------------------------- /out/production/pythonFiles/passwords.json: -------------------------------------------------------------------------------- 1 | { 2 | "anubhob": "7d727ac57ca6285f5a38be092aaea0a0d7678607071f1e04d8537159d8d66482" 3 | } -------------------------------------------------------------------------------- /out/production/pythonFiles/practice_1.py: -------------------------------------------------------------------------------- 1 | import seaborn as sns 2 | 3 | def divide_numbers(a, b): 4 | try: 5 | result = a / b 6 | return result 7 | except ZeroDivisionError: 8 | return "Error: Division by zero is not allowed" 9 | 10 | # Test the function 11 | print(divide_numbers(10, 2)) # Normal division 12 | print(divide_numbers(10, 0)) # Attempting division by zero 13 | 14 | import matplotlib.pyplot as plt 15 | 16 | # Load built-in dataset 17 | tips = sns.load_dataset("tips") 18 | 19 | # Create a scatterplot 20 | sns.scatterplot(data=tips, x="total_bill", y="tip") 21 | plt.title("Tips vs Total Bill Amount") 22 | plt.show() 23 | 24 | -------------------------------------------------------------------------------- /out/production/pythonFiles/python_game.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import random 3 | 4 | # Initialize Pygame 5 | pygame.init() 6 | 7 | # Set up the display 8 | WIDTH = 800 9 | HEIGHT = 600 10 | screen = pygame.display.set_mode((WIDTH, HEIGHT)) 11 | pygame.display.set_caption("Dodge the Blocks") 12 | 13 | # Colors 14 | WHITE = (255, 255, 255) 15 | RED = (255, 0, 0) 16 | BLUE = (0, 0, 255) 17 | 18 | # Player settings 19 | player_size = 50 20 | player_x = WIDTH // 2 - player_size // 2 21 | player_y = HEIGHT - player_size - 10 22 | player_speed = 5 23 | 24 | # Enemy settings 25 | enemy_size = 50 26 | enemy_speed = 5 27 | enemies = [] 28 | 29 | # Game loop 30 | running = True 31 | clock = pygame.time.Clock() 32 | score = 0 33 | 34 | while running: 35 | # Event handling 36 | for event in pygame.event.get(): 37 | if event.type == pygame.QUIT: 38 | running = False 39 | 40 | # Player movement 41 | keys = pygame.key.get_pressed() 42 | if keys[pygame.K_LEFT] and player_x > 0: 43 | player_x -= player_speed 44 | if keys[pygame.K_RIGHT] and player_x < WIDTH - player_size: 45 | player_x += player_speed 46 | 47 | # Create new enemies 48 | if len(enemies) < 5 and random.random() < 0.02: 49 | enemies.append([random.randint(0, WIDTH - enemy_size), -enemy_size]) 50 | 51 | # Update enemy positions 52 | for enemy in enemies[:]: 53 | enemy[1] += enemy_speed 54 | if enemy[1] > HEIGHT: 55 | enemies.remove(enemy) 56 | score += 1 57 | 58 | # Collision detection 59 | player_rect = pygame.Rect(player_x, player_y, player_size, player_size) 60 | for enemy in enemies: 61 | enemy_rect = pygame.Rect(enemy[0], enemy[1], enemy_size, enemy_size) 62 | if player_rect.colliderect(enemy_rect): 63 | running = False 64 | 65 | # Drawing 66 | screen.fill(WHITE) 67 | pygame.draw.rect(screen, BLUE, (player_x, player_y, player_size, player_size)) 68 | for enemy in enemies: 69 | pygame.draw.rect(screen, RED, (enemy[0], enemy[1], enemy_size, enemy_size)) 70 | 71 | pygame.display.flip() 72 | clock.tick(60) 73 | 74 | print(f"Game Over! Score: {score}") 75 | pygame.quit() -------------------------------------------------------------------------------- /out/production/pythonFiles/random_luck.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def lucky_draw(): 4 | # Generate a random number between 1 and 100 5 | secret_number = random.randint(1, 100) 6 | attempts = 0 7 | max_attempts = 10 8 | 9 | print("Welcome to the Lucky Number Game!") 10 | print(f"Guess a number between 1 and 100. You have {max_attempts} attempts.") 11 | 12 | while attempts < max_attempts: 13 | try: 14 | # Get player's guess 15 | guess = int(input("Enter your guess: ")) 16 | attempts += 1 17 | 18 | # Check the guess 19 | if guess == secret_number: 20 | print(f"Congratulations! You won in {attempts} attempts!") 21 | return 22 | elif guess < secret_number: 23 | print("Too low! Try again.") 24 | else: 25 | print("Too high! Try again.") 26 | 27 | print(f"Attempts remaining: {max_attempts - attempts}") 28 | 29 | except ValueError: 30 | print("Please enter a valid number!") 31 | 32 | print(f"Game Over! The number was {secret_number}") 33 | 34 | if __name__ == "__main__": 35 | lucky_draw() -------------------------------------------------------------------------------- /out/production/pythonFiles/recursion printing.py: -------------------------------------------------------------------------------- 1 | lst_alphabets = [] 2 | lst_num = [] 3 | lst_2 = [] 4 | lst_print = [] 5 | dictionary_1 = { 6 | 1: "a", 2: "b", 3: "c", 4: "d", 5: "e", 7 | 6: "f", 7: "g", 8: "h", 9: "i", 10: "j", 8 | 11: "k", 12: "l", 13: "m", 14: "n", 15: "o", 9 | 16: "p", 17: "q", 18: "r", 19: "s", 20: "t", 10 | 21: "u", 22: "v", 23: "w", 24: "x", 25: "y", 26: "z", 27: " " 11 | } 12 | 13 | keys = list(dictionary_1.keys()) 14 | values = list(dictionary_1.values()) 15 | 16 | word = input("Enter word: ").lower() 17 | 18 | print("OH I USED TO SAY !!") 19 | for i in word: 20 | lst_alphabets.append(i) 21 | 22 | for k in lst_alphabets: 23 | index = values.index(k) 24 | Key = keys[index] 25 | lst_num.append(Key) 26 | 27 | def programme(): 28 | count = 0 29 | for x in lst_num: 30 | for z in range(0, x): 31 | tempv = values[z] 32 | lst_print.append(tempv) 33 | print("".join(lst_print)) 34 | if tempv != lst_alphabets[count]: 35 | lst_print.pop() 36 | else: 37 | count +=1 38 | 39 | programme() 40 | print("I FOUND YOU !!! :)") -------------------------------------------------------------------------------- /out/production/pythonFiles/roman.py: -------------------------------------------------------------------------------- 1 | def roman_to_int(s): 2 | roman_values = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} 3 | total = 0 4 | for c in s: 5 | total += roman_values[c] 6 | return total 7 | 8 | def int_to_roman(num): 9 | val = [ 10 | 1000, 900, 500, 400, 11 | 100, 90, 50, 40, 12 | 10, 9, 5, 4, 13 | 1 14 | ] 15 | syb = [ 16 | "M", "CM", "D", "CD", 17 | "C", "XC", "L", "XL", 18 | "X", "IX", "V", "IV", 19 | "I" 20 | ] 21 | roman_str = '' 22 | for i in range(len(val)): 23 | while num >= val[i]: 24 | num -= val[i] 25 | roman_str += syb[i] 26 | return roman_str 27 | 28 | def StringChallenge(s): 29 | # Convert roman numeral string to integer 30 | numeral_value = roman_to_int(s) 31 | 32 | # Convert integer back to shortest roman numeral string 33 | shortest_roman = int_to_roman(numeral_value) 34 | 35 | return shortest_roman 36 | 37 | def final_output(s): 38 | token = 'eav2xtzlf7' 39 | combined = s + token 40 | result = ''.join([char if (i + 1) % 4 != 0 else '_' for i, char in enumerate(combined)]) 41 | return result 42 | 43 | # Examples 44 | input_str = "XXXVVIIIIIIIIII" 45 | output = StringChallenge(input_str) 46 | print("Output:", output) 47 | print("Final Output:", final_output(output)) 48 | 49 | input_str = "DDLL" 50 | output = StringChallenge(input_str) 51 | print("Output:", output) 52 | print("Final Output:", final_output(output)) -------------------------------------------------------------------------------- /out/production/pythonFiles/script.js: -------------------------------------------------------------------------------- 1 | const themeToggle = document.getElementById('theme-toggle'); 2 | const themeIcon = themeToggle.querySelector('i'); 3 | const html = document.documentElement; 4 | 5 | // Load saved theme 6 | const savedTheme = localStorage.getItem('theme') || 'light'; 7 | html.setAttribute('data-theme', savedTheme); 8 | updateThemeIcon(savedTheme); 9 | 10 | themeToggle.addEventListener('click', () => { 11 | const currentTheme = html.getAttribute('data-theme'); 12 | const newTheme = currentTheme === 'light' ? 'dark' : 'light'; 13 | 14 | html.setAttribute('data-theme', newTheme); 15 | localStorage.setItem('theme', newTheme); 16 | updateThemeIcon(newTheme); 17 | }); 18 | 19 | function updateThemeIcon(theme) { 20 | themeIcon.className = theme === 'light' ? 'fas fa-moon' : 'fas fa-sun'; 21 | } 22 | 23 | const startBtn = document.getElementById("start-btn"); 24 | const outputDiv = document.getElementById("output"); 25 | const statusSpan = document.getElementById("status"); 26 | const waveVisualizer = document.getElementById("wave-visualizer"); 27 | const buttonText = startBtn.querySelector("span"); 28 | 29 | if ("webkitSpeechRecognition" in window) { 30 | const recognition = new webkitSpeechRecognition(); 31 | recognition.continuous = false; 32 | recognition.interimResults = false; 33 | recognition.lang = "en-US"; 34 | 35 | startBtn.addEventListener("click", () => { 36 | startBtn.classList.add("listening"); 37 | buttonText.textContent = "Listening..."; 38 | outputDiv.textContent = "Listening..."; 39 | statusSpan.textContent = "Listening..."; 40 | waveVisualizer.style.display = "flex"; 41 | recognition.start(); 42 | }); 43 | 44 | recognition.onresult = (event) => { 45 | const transcript = event.results[0][0].transcript; 46 | outputDiv.innerHTML = ` ${transcript} `; 47 | }; 48 | 49 | recognition.onerror = (event) => { 50 | outputDiv.innerHTML = ` Error: ${event.error}`; 51 | resetUI(); 52 | }; 53 | 54 | recognition.onend = () => { 55 | resetUI(); 56 | }; 57 | 58 | function resetUI() { 59 | startBtn.classList.remove("listening"); 60 | buttonText.textContent = "Start Listening"; 61 | statusSpan.textContent = "Ready"; 62 | waveVisualizer.style.display = "none"; 63 | } 64 | } else { 65 | startBtn.disabled = true; 66 | outputDiv.innerHTML = ' Speech recognition is not supported in your browser. Please try using Google Chrome.'; 67 | } -------------------------------------------------------------------------------- /out/production/pythonFiles/searching.py: -------------------------------------------------------------------------------- 1 | def SearchingChallenge(strArr): 2 | # Convert the input array into a matrix 3 | matrix = [list(map(int, row)) for row in strArr] 4 | 5 | # Get the dimensions of the matrix 6 | rows, cols = len(matrix), len(matrix[0]) 7 | 8 | # Define the directions for DFS 9 | directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] 10 | 11 | # Initialize the memoization table 12 | memo = [[0] * cols for _ in range(rows)] 13 | 14 | def dfs(r, c): 15 | # If the result is already memoized, return it 16 | if memo[r][c] != 0: 17 | return memo[r][c] 18 | 19 | # Initialize the longest path length to 1 20 | longest_path = 1 21 | 22 | # Explore all possible directions 23 | for dr, dc in directions: 24 | nr, nc = r + dr, c + dc 25 | 26 | # Check if the new position is within the matrix bounds 27 | if 0 <= nr < rows and 0 <= nc < cols: 28 | # Check if the new position has a larger value 29 | if matrix[nr][nc] > matrix[r][c]: 30 | # Recursively explore the new position 31 | longest_path = max(longest_path, dfs(nr, nc) + 1) 32 | 33 | # Memoize the result 34 | memo[r][c] = longest_path 35 | return longest_path 36 | 37 | # Initialize the longest path length to 0 38 | longest_path = 0 39 | 40 | # Explore all positions in the matrix 41 | for r in range(rows): 42 | for c in range(cols): 43 | longest_path = max(longest_path, dfs(r, c)) 44 | 45 | return longest_path - 1 46 | 47 | print(SearchingChallenge(["12256", "56219", "43215"])) # Output: 5 48 | print(SearchingChallenge(["67", "21", "45"])) # Output: 3 49 | -------------------------------------------------------------------------------- /out/production/pythonFiles/sha512.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | 3 | def compute_sha256(message: str) -> str: 4 | return hashlib.sha256(message.encode()).hexdigest() 5 | 6 | def compute_sha512(message: str) -> str: 7 | return hashlib.sha512(message.encode()).hexdigest() 8 | 9 | if __name__ == "__main__": 10 | text = "Hello, world" 11 | sha256_result = compute_sha256(text) 12 | sha512_result = compute_sha512(text) 13 | 14 | print("SHA256:", sha256_result) 15 | print("SHA512:", sha512_result) -------------------------------------------------------------------------------- /out/production/pythonFiles/string27.py: -------------------------------------------------------------------------------- 1 | #27. Write a program to find a substring within a string. If found display its starting position 2 | 3 | text = input("Enter a string: ") 4 | sub = input("Enter a substring to find: ") 5 | position = text.find(sub) 6 | if position != -1: 7 | print(f"Substring found at position {position}") 8 | else: 9 | print("Substring not found.") -------------------------------------------------------------------------------- /out/production/pythonFiles/stringchallange1.py: -------------------------------------------------------------------------------- 1 | def is_palindrome(s): 2 | return s == s[::-1] 3 | 4 | def StringChallenge(strParam): 5 | if is_palindrome(strParam): 6 | return strParam 7 | 8 | n = len(strParam) 9 | 10 | # Try removing one character at a time 11 | for i in range(n): 12 | temp = strParam[:i] + strParam[i+1:] 13 | if is_palindrome(temp) and len(temp) >= 3: 14 | return strParam[i] 15 | 16 | # Try removing two characters 17 | for i in range(n): 18 | for j in range(i+1, n): 19 | temp = strParam[:i] + strParam[i+1:j] + strParam[j+1:] 20 | if is_palindrome(temp) and len(temp) >= 3: 21 | return strParam[i] + strParam[j] 22 | 23 | return "not possible" 24 | 25 | # Keep this function call here 26 | print(StringChallenge(input())) -------------------------------------------------------------------------------- /out/production/pythonFiles/stringchallange2.py: -------------------------------------------------------------------------------- 1 | def find_smallest_number(numbers): 2 | if not numbers: 3 | return None 4 | return min(numbers) 5 | 6 | sample_list = [10, 2, 5, 1, -7, 13] 7 | print(find_smallest_number(sample_list)) # Output: -7 -------------------------------------------------------------------------------- /out/production/pythonFiles/styles.css: -------------------------------------------------------------------------------- 1 | :root[data-theme="light"] { 2 | --primary-color: #4a90e2; 3 | --secondary-color: #f8f9fa; 4 | --text-color: #2c3e50; 5 | --bg-color: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); 6 | --app-bg: rgba(255, 255, 255, 0.95); 7 | --shadow: 0 4px 6px rgba(0, 0, 0, 0.1); 8 | } 9 | 10 | :root[data-theme="dark"] { 11 | --primary-color: #64b5f6; 12 | --secondary-color: #2c3e50; 13 | --text-color: #ecf0f1; 14 | --bg-color: linear-gradient(135deg, #2c3e50 0%, #1a1a1a 100%); 15 | --app-bg: rgba(33, 33, 33, 0.95); 16 | --shadow: 0 4px 6px rgba(0, 0, 0, 0.3); 17 | } 18 | 19 | * { 20 | transition: background-color 0.3s, color 0.3s, border-color 0.3s, box-shadow 0.3s; 21 | } 22 | 23 | #theme-toggle { 24 | position: fixed; 25 | top: 20px; 26 | right: 20px; 27 | padding: 10px; 28 | border-radius: 50%; 29 | border: none; 30 | background: var(--secondary-color); 31 | color: var(--text-color); 32 | cursor: pointer; 33 | box-shadow: var(--shadow); 34 | width: 40px; 35 | height: 40px; 36 | display: flex; 37 | align-items: center; 38 | justify-content: center; 39 | } 40 | 41 | #theme-toggle:hover { 42 | transform: scale(1.1); 43 | } 44 | 45 | body { 46 | font-family: 'Segoe UI', system-ui, -apple-system, sans-serif; 47 | margin: 0; 48 | min-height: 100vh; 49 | display: flex; 50 | align-items: center; 51 | justify-content: center; 52 | background: var(--bg-color); 53 | color: var(--text-color); 54 | } 55 | 56 | #app { 57 | width: 90%; 58 | max-width: 600px; 59 | padding: 2rem; 60 | background: var(--app-bg); 61 | border-radius: 20px; 62 | box-shadow: var(--shadow); 63 | backdrop-filter: blur(10px); 64 | } 65 | 66 | h1 { 67 | font-size: 2.2rem; 68 | margin-bottom: 1.5rem; 69 | color: var(--primary-color); 70 | display: flex; 71 | align-items: center; 72 | justify-content: center; 73 | gap: 10px; 74 | } 75 | 76 | #start-btn { 77 | padding: 1rem 2rem; 78 | font-size: 1.1rem; 79 | border: none; 80 | border-radius: 50px; 81 | background: var(--primary-color); 82 | color: white; 83 | cursor: pointer; 84 | transition: all 0.3s ease; 85 | display: flex; 86 | align-items: center; 87 | gap: 10px; 88 | margin: 2rem auto; 89 | } 90 | 91 | #start-btn:hover { 92 | transform: translateY(-2px); 93 | box-shadow: var(--shadow); 94 | background: #357abd; 95 | } 96 | 97 | #start-btn.listening { 98 | background: #e74c3c; 99 | animation: pulse 1.5s infinite; 100 | } 101 | 102 | #output { 103 | margin-top: 2rem; 104 | padding: 1.5rem; 105 | border-radius: 15px; 106 | background: var(--secondary-color); 107 | min-height: 100px; 108 | transition: all 0.3s ease; 109 | line-height: 1.6; 110 | color: var(--text-color); 111 | } 112 | 113 | @keyframes pulse { 114 | 0% { transform: scale(1); } 115 | 50% { transform: scale(1.05); } 116 | 100% { transform: scale(1); } 117 | } 118 | 119 | .status-indicator { 120 | display: flex; 121 | align-items: center; 122 | justify-content: center; 123 | gap: 10px; 124 | margin-top: 1rem; 125 | font-size: 0.9rem; 126 | color: var(--text-color); 127 | } 128 | 129 | .wave { 130 | display: flex; 131 | align-items: center; 132 | gap: 3px; 133 | height: 20px; 134 | } 135 | 136 | .wave-bar { 137 | width: 3px; 138 | height: 100%; 139 | background: var(--primary-color); 140 | animation: wave 1s ease-in-out infinite; 141 | transform-origin: bottom; 142 | } 143 | 144 | @keyframes wave { 145 | 0% { transform: scaleY(0.1); } 146 | 50% { transform: scaleY(1); } 147 | 100% { transform: scaleY(0.1); } 148 | } -------------------------------------------------------------------------------- /out/production/pythonFiles/sumoftwolinkedlist.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, val=0, next=None): 3 | self.val = val 4 | self.next = next 5 | 6 | def mergeTwoLists(l1, l2): 7 | """ 8 | Merge two sorted linked lists into a single sorted linked list. 9 | 10 | Args: 11 | l1: The head of the first sorted linked list 12 | l2: The head of the second sorted linked list 13 | 14 | Returns: 15 | The head of the merged sorted linked list 16 | """ 17 | # Create a dummy head to simplify edge cases 18 | dummy = ListNode(-1) 19 | current = dummy 20 | 21 | # Traverse both lists and compare values 22 | while l1 and l2: 23 | if l1.val <= l2.val: 24 | current.next = l1 25 | l1 = l1.next 26 | else: 27 | current.next = l2 28 | l2 = l2.next 29 | current = current.next 30 | 31 | # Attach remaining nodes from either list 32 | if l1: 33 | current.next = l1 34 | else: 35 | current.next = l2 36 | 37 | return dummy.next 38 | 39 | # Example usage 40 | def create_linked_list(values): 41 | """Helper function to create a linked list from a list of values""" 42 | dummy = ListNode(0) 43 | current = dummy 44 | for val in values: 45 | current.next = ListNode(val) 46 | current = current.next 47 | return dummy.next 48 | 49 | def print_linked_list(head): 50 | """Helper function to print a linked list""" 51 | values = [] 52 | current = head 53 | while current: 54 | values.append(str(current.val)) 55 | current = current.next 56 | return " -> ".join(values) 57 | 58 | # Test with example lists 59 | list1 = create_linked_list([1, 2, 4]) 60 | list2 = create_linked_list([1, 3, 4]) 61 | merged = mergeTwoLists(list1, list2) 62 | print(print_linked_list(merged)) # Output: 1 -> 1 -> 2 -> 3 -> 4 -> 4 -------------------------------------------------------------------------------- /out/production/pythonFiles/temperature_converter.py: -------------------------------------------------------------------------------- 1 | def celsius_to_fahrenheit(celsius): 2 | """Convert Celsius to Fahrenheit.""" 3 | return (celsius * 9/5) + 32 4 | 5 | def fahrenheit_to_celsius(fahrenheit): 6 | """Convert Fahrenheit to Celsius.""" 7 | return (fahrenheit - 32) * 5/9 8 | 9 | def celsius_to_kelvin(celsius): 10 | """Convert Celsius to Kelvin.""" 11 | return celsius + 273.15 12 | 13 | def kelvin_to_celsius(kelvin): 14 | """Convert Kelvin to Celsius.""" 15 | return kelvin - 273.15 16 | 17 | def fahrenheit_to_kelvin(fahrenheit): 18 | """Convert Fahrenheit to Kelvin.""" 19 | celsius = fahrenheit_to_celsius(fahrenheit) 20 | return celsius_to_kelvin(celsius) 21 | 22 | def kelvin_to_fahrenheit(kelvin): 23 | """Convert Kelvin to Fahrenheit.""" 24 | celsius = kelvin_to_celsius(kelvin) 25 | return celsius_to_fahrenheit(celsius) 26 | 27 | def get_valid_temperature(): 28 | """Get a valid temperature input from the user.""" 29 | while True: 30 | try: 31 | temp = float(input("Enter the temperature value: ")) 32 | return temp 33 | except ValueError: 34 | print("Invalid input. Please enter a number.") 35 | 36 | def display_menu(): 37 | """Display the temperature conversion menu.""" 38 | print("\nTemperature Converter") 39 | print("---------------------") 40 | print("1. Celsius to Fahrenheit") 41 | print("2. Fahrenheit to Celsius") 42 | print("3. Celsius to Kelvin") 43 | print("4. Kelvin to Celsius") 44 | print("5. Fahrenheit to Kelvin") 45 | print("6. Kelvin to Fahrenheit") 46 | print("7. Exit") 47 | 48 | def main(): 49 | """Main function to run the temperature converter.""" 50 | while True: 51 | display_menu() 52 | 53 | try: 54 | choice = int(input("\nEnter your choice (1-7): ")) 55 | 56 | if choice == 7: 57 | print("Thank you for using the Temperature Converter. Goodbye!") 58 | break 59 | 60 | if choice < 1 or choice > 7: 61 | print("Invalid choice. Please select a number between 1 and 7.") 62 | continue 63 | 64 | temperature = get_valid_temperature() 65 | 66 | if choice == 1: 67 | result = celsius_to_fahrenheit(temperature) 68 | print(f"{temperature}°C = {result:.2f}°F") 69 | elif choice == 2: 70 | result = fahrenheit_to_celsius(temperature) 71 | print(f"{temperature}°F = {result:.2f}°C") 72 | elif choice == 3: 73 | result = celsius_to_kelvin(temperature) 74 | print(f"{temperature}°C = {result:.2f}K") 75 | elif choice == 4: 76 | result = kelvin_to_celsius(temperature) 77 | print(f"{temperature}K = {result:.2f}°C") 78 | elif choice == 5: 79 | result = fahrenheit_to_kelvin(temperature) 80 | print(f"{temperature}°F = {result:.2f}K") 81 | elif choice == 6: 82 | result = kelvin_to_fahrenheit(temperature) 83 | print(f"{temperature}K = {result:.2f}°F") 84 | 85 | except ValueError: 86 | print("Invalid input. Please enter a number.") 87 | 88 | if __name__ == "__main__": 89 | main() 90 | -------------------------------------------------------------------------------- /out/production/pythonFiles/testimage.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Anubhob435/pythonFiles/e8fe21829ff9f4e194e4f6bd8ba913539385d73f/out/production/pythonFiles/testimage.jpg -------------------------------------------------------------------------------- /out/production/pythonFiles/turtle_animation.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | # Setting up the screen 4 | wn = turtle.Screen() 5 | wn.bgcolor("black") 6 | wn.title("Solar System Animation") 7 | 8 | # Creating a Turtle object for drawing the sun and planets 9 | sun = turtle.Turtle() 10 | sun.shape("circle") 11 | sun.color("yellow") 12 | sun.shapesize(3) 13 | 14 | # Creating a list of planets with their properties (color, distance from the sun, size, and speed) 15 | planets = [ 16 | {"color": "gray", "distance": 50, "size": 0.5, "speed": 1}, 17 | {"color": "orange", "distance": 80, "size": 0.8, "speed": 0.5}, 18 | {"color": "red", "distance": 120, "size": 0.7, "speed": 0.3}, 19 | {"color": "blue", "distance": 160, "size": 0.6, "speed": 0.2}, 20 | {"color": "green", "distance": 200, "size": 0.9, "speed": 0.1} 21 | ] 22 | 23 | # Creating a Turtle object for each planet and animate their orbits 24 | planet_turtles = [] 25 | for planet in planets: 26 | planet_turtle = turtle.Turtle() 27 | planet_turtle.shape("circle") 28 | planet_turtle.color(planet["color"]) 29 | planet_turtle.shapesize(planet["size"]) 30 | planet_turtle.penup() 31 | planet_turtle.goto(planet["distance"], 0) 32 | planet_turtle.pendown() 33 | planet_turtles.append(planet_turtle) 34 | 35 | # Function to animate the planets' orbits 36 | def animate_orbits(): 37 | for i, planet in enumerate(planet_turtles): 38 | planet.speed(0) 39 | angle = 360 * planets[i]["speed"] 40 | planet.circle(planets[i]["distance"], angle) 41 | 42 | # Animating the orbits 43 | while True: 44 | animate_orbits() 45 | wn.update() 46 | 47 | # Closing the program when the user clicks on the screen 48 | wn.exitonclick() --------------------------------------------------------------------------------