├── Python3-Learn ├── Kadane_Algo_Fatema110.py ├── tempCodeRunnerFile.py ├── lettersearch │ ├── lettersearch.egg-info │ │ ├── dependency_links.txt │ │ ├── top_level.txt │ │ ├── SOURCES.txt │ │ └── PKG-INFO │ ├── dist │ │ ├── lettersearch-1.0.tar.gz │ │ └── lettersearch-1.0-py3-none-any.whl │ ├── lettersearch.py │ ├── build │ │ └── lib │ │ │ └── lettersearch.py │ ├── setup.py │ └── README.txt ├── Searching │ ├── README.md │ ├── Linear_Search.py │ └── Binary_Search.py ├── hello_world_shruti49.py ├── list_comprehension_willidert.py ├── Example-Aman22sharma.py ├── Hello-World_erarijit.py ├── Find-IP-Address-Using-Pyhton.py ├── dnd-dice-roller │ ├── README.txt │ └── diceroll_SoWrongImRight.py ├── sum_of _digits_dharmateja03.py ├── even_odd_mayankgoyal.py ├── MultiplicationTable_erarijit.py ├── dharmateja03_whatsapp.py ├── set_bits_count_dharmateja03.py ├── AddBinary-SnehaRautmare.py ├── StringCopies-SanaaShah.py.py ├── circle-area_bonifasiustrg.py ├── SortAlphabeticalOrder_erarijit.py ├── IP-tracker.py ├── mersenne_guruprasanna02.py ├── fibonacci_lucasli233.py ├── Capitalize_first_alphabet_AadityaKumra.py ├── rotate_list.py ├── Rainbow_Benzene using Python Turtle Programming ├── Seperate_word_by#_mayankgoyal.py ├── finding_greatest.py ├── Palindrome_github-dev21.py ├── palindromicstring_RUDRANSH_HUB.py ├── Palindrome_Shyam-2001.py ├── TwoSum.py ├── python3-multipleAssignments-Sahilnegi-code.py ├── spambot.py ├── CountWordWithPySpark_skinnycoders.py ├── InsertionSort.py ├── some modules │ ├── wikipedia_avyayjain.py │ ├── sendmail_avyayjain.py │ ├── speechrecognition_avyayjain.py │ ├── calculator_avyayjain.py │ ├── weather_avyayjain.py │ ├── random_avyayjain.py │ ├── texttospeech_avyayjain.py │ └── playmusic_avyayjain.py ├── Try-Except_Ramptl.py ├── simple_intrest_mayankgoyal.py ├── python3-all_primes_Dude-901.py ├── Python3-Learn-Palindrome_Rishav00.py ├── Fibonacci-VishnuRamV.py ├── tipcalculator_neethujojigeorge.py ├── Josephus-problem_Tanmay-901.py ├── voice_reciever_Mgeethabhargava.py ├── Armstrong_number_Ajit.py ├── OOP_sample_program_priyajames.py ├── python3_list_in_python_manasisaiba.py ├── Audio_Text_to_Speech_Dhallod07.py ├── Sort_Luckysopyantoro.py ├── discount_calculator.py ├── find_substrings_AadityaKumra.py ├── matplotlib-plot_dalonlobo.py ├── datatypes.py ├── Factorial_erarijit.py ├── fibonacciSequence.py ├── Inheritance_ADHIL-MOHAMMED-P-N.py ├── clock_Mgeethabhargava.py ├── BiggestNumberOutOf3_erarijit.py ├── python3-randomnumbergenerator_aadyar882.py ├── quadratic_equation_solver_mayank.py ├── covid19api_guptadev21.py ├── python3-ArrayRotation-mephisto2975.py ├── scrape.py ├── command-line-arguments_Bhairavi-shah.py ├── quicksort_srikar999.py ├── heapq_akki-1211.py ├── Bubblesort_debajyoti22.py ├── create SQL table_passionlord.py ├── matrix_transpose_akash435.py ├── reverse-nparray_Christy538.py ├── find_string_duplicates_edusanketdk.py ├── welcome_square_pattern_AadityaKumra.py ├── mergesort.py ├── cleaner-dates_JoaquinMontesinos.py ├── chess_gouravchawla334.py ├── matrix_spiral_traversal_edusanketdk.py ├── send_email.py ├── prime-or-not_Christy538.py ├── Matrix_Multi_SumanthBajjuri07.py ├── sieve_of_eratosthenes_Developer-R-7.py ├── OTP-verification-system_santanukumar666.py ├── Python Lambda.py ├── python3-DetectCycles_barlerer.py ├── python3-EvenOddSegregation-mephisto2975.py ├── Merge2_dicts_SumanthBajjuri07.py ├── magic_number-sumitbro.py ├── sort_012_array_edusanketdk.py ├── movie_flight_CharalambosIoannou.py ├── 4Sum_Fatema110.py ├── list_manipulation_DFRICHARD.py ├── file_handling_durgeshahire07.py ├── working-with-images_Harshil333.py ├── sms-bomber.py ├── first_last_position_edusanketdk.py ├── rock_paper_scissors.py ├── Heap_Sort_Algorithm_MMVonnSeek.py ├── Stonepaperscissorsgame_varsha080.py ├── control-structures_InfernapeXavier.py ├── Longest_Common_Prefix_Yakuta110.py ├── python3-quicksort-dwiputrias.py ├── Rock_paper_scissor_mayankgoyal.py ├── Itertools.py ├── password_generator_Princekumaraj.py ├── snake.py ├── ATM_krosskid12.py ├── Queue_Ananya2003Gupta.py ├── python3-InverseBurrowWheeler_DeepthiSudharsan.py ├── mergeSort_rbb-99.py ├── Majority_Element_Fatema110.py ├── python3-Stacks-priyanshu-28.py ├── BasicArtificialNeuralNetwork_Mgeethabhargava.py ├── Merge sort.py ├── ArrayCode_Pankaj05011998.py ├── Linkedlist_ShreyaDayma-cse.py ├── Oops_shruticode81.py ├── concept-Datatypes_PP6975H.py ├── telegramScraper_rakeshchauhan │ ├── detailtelegram.py │ └── addmember.py ├── CompoundInterestCalculator_JirroReo.py ├── Decorators_dsrathore1.py ├── Creating-Custom-Exceptions_muneersyed156.py ├── Set-Operations_Aman22sharma.py ├── face_and_body_detection_swairik.py ├── String-Manipulations_muneersyed156.py ├── list-methods_awsheeshh.py ├── crud_csv_ninefyi.py ├── TIC_TAC_TOE game.py ├── AdventureWithRio.py ├── Matrix-Calculator-Andy-Ra.py ├── Breast Cancer Detection System.py ├── sha384_Guruprasanna02.py ├── Math-module_praneethacl.py ├── basic-concepts-drishyadamodaran.py └── python3-Basics-Concept_Vaishnavi-101.py ├── Update Your Python with Latest Version.docx ├── LICENSE.md └── README.md /Python3-Learn/Kadane_Algo_Fatema110.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Python3-Learn/tempCodeRunnerFile.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Python3-Learn/lettersearch/lettersearch.egg-info/dependency_links.txt: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Python3-Learn/Searching/README.md: -------------------------------------------------------------------------------- 1 | ### Searching Implementation using python. 2 | -------------------------------------------------------------------------------- /Python3-Learn/lettersearch/lettersearch.egg-info/top_level.txt: -------------------------------------------------------------------------------- 1 | lettersearch 2 | -------------------------------------------------------------------------------- /Update Your Python with Latest Version.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aman22sharma/Hacktoberfest2021_beginner/HEAD/Update Your Python with Latest Version.docx -------------------------------------------------------------------------------- /Python3-Learn/hello_world_shruti49.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Shruti Shastri 2 | //Python3 Concept: Hello World Program 3 | // GITHUB: https://github.com/shruti49 4 | 5 | print("Hello World") -------------------------------------------------------------------------------- /Python3-Learn/lettersearch/dist/lettersearch-1.0.tar.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aman22sharma/Hacktoberfest2021_beginner/HEAD/Python3-Learn/lettersearch/dist/lettersearch-1.0.tar.gz -------------------------------------------------------------------------------- /Python3-Learn/list_comprehension_willidert.py: -------------------------------------------------------------------------------- 1 | if __name__ == "__main__": 2 | # 1 2 3 3 | arr = list(map(int, input().split())) 4 | print([i**2 for i in arr]) # [1 4 9] 5 | -------------------------------------------------------------------------------- /Python3-Learn/Example-Aman22sharma.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Aman Kumar sharma 2 | // Python3 Concept: Demo Example 3 | // GITHUB: https://github.com/Aman22sharma 4 | 5 | //Add your python3 concept below 6 | -------------------------------------------------------------------------------- /Python3-Learn/Hello-World_erarijit.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Arijit Mukherjee 2 | //Python3 Concept: Hello World Program 3 | // GITHUB: https://github.com/erarijit 4 | 5 | print("Hello World! Welcome to Github") 6 | -------------------------------------------------------------------------------- /Python3-Learn/lettersearch/dist/lettersearch-1.0-py3-none-any.whl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Aman22sharma/Hacktoberfest2021_beginner/HEAD/Python3-Learn/lettersearch/dist/lettersearch-1.0-py3-none-any.whl -------------------------------------------------------------------------------- /Python3-Learn/Find-IP-Address-Using-Pyhton.py: -------------------------------------------------------------------------------- 1 | import socket 2 | hostname = socket.gethostname() 3 | IPAddr = socket.gethostbyname(hostname) 4 | print("Your Computer Name is:" + hostname) 5 | print("Your Computer IP Address is:" + IPAddr) 6 | -------------------------------------------------------------------------------- /Python3-Learn/lettersearch/lettersearch.egg-info/SOURCES.txt: -------------------------------------------------------------------------------- 1 | README.txt 2 | lettersearch.py 3 | setup.py 4 | lettersearch.egg-info/PKG-INFO 5 | lettersearch.egg-info/SOURCES.txt 6 | lettersearch.egg-info/dependency_links.txt 7 | lettersearch.egg-info/top_level.txt -------------------------------------------------------------------------------- /Python3-Learn/lettersearch/lettersearch.py: -------------------------------------------------------------------------------- 1 | def lettersearch(phrase:str, letters:str) -> set: 2 | """This module takes a phrase provided by the user and searches it for letters that the user provides""" 3 | return set(letters).intersection(set(phrase)) 4 | -------------------------------------------------------------------------------- /Python3-Learn/dnd-dice-roller/README.txt: -------------------------------------------------------------------------------- 1 | This ia a program that prompts the user to enter a die type (d4 through d100) and a quantity and then provides the results of those dice rolls. If nothing is entered the program defaults to "d6" for die type and 1 for quantity. 2 | -------------------------------------------------------------------------------- /Python3-Learn/lettersearch/build/lib/lettersearch.py: -------------------------------------------------------------------------------- 1 | def lettersearch(phrase:str, letters:str) -> set: 2 | """This module takes a phrase provided by the user and searches it for letters that the user provides""" 3 | return set(letters).intersection(set(phrase)) 4 | -------------------------------------------------------------------------------- /Python3-Learn/sum_of _digits_dharmateja03.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Dharma Teja 2 | # Python3 Concept:sum of digits in given number 3 | # GITHUB: https://github.com/dharmateja03 4 | number=int(input()) #enter input 5 | l=list(str(number)) 6 | nums=list(map(int,l)) 7 | print(sum(nums)) 8 | -------------------------------------------------------------------------------- /Python3-Learn/even_odd_mayankgoyal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : Even odd 3 | Author : [Mayank Goyal) [https://github.com/mayankgoyal-13] 4 | """ 5 | num = int(input("Enter your number: ")) 6 | if num % 2 == 0: 7 | print('The given number is even') 8 | else: 9 | print('The given number is odd') 10 | -------------------------------------------------------------------------------- /Python3-Learn/lettersearch/lettersearch.egg-info/PKG-INFO: -------------------------------------------------------------------------------- 1 | Metadata-Version: 1.0 2 | Name: lettersearch 3 | Version: 1.0 4 | Summary: Letter search tool 5 | Home-page: UNKNOWN 6 | Author: Russ Carroll 7 | Author-email: dev.ops.rc.1980@gmail.com 8 | License: UNKNOWN 9 | Description: UNKNOWN 10 | Platform: UNKNOWN 11 | -------------------------------------------------------------------------------- /Python3-Learn/lettersearch/setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup ( 4 | name='lettersearch', 5 | version='1.0', 6 | description='Letter search tool', 7 | author='Russ Carroll', 8 | author_email="dev.ops.rc.1980@gmail.com", 9 | py_modules=['lettersearch'] 10 | ) 11 | -------------------------------------------------------------------------------- /Python3-Learn/MultiplicationTable_erarijit.py: -------------------------------------------------------------------------------- 1 | # Python program to find the multiplication table (from 1 to 10) of a number input by the user 2 | 3 | # take input from the user 4 | num = int(input("Display multiplication table of? ")) 5 | 6 | # use for loop to iterate 10 times 7 | for i in range(1,11): 8 | print(num,'x',i,'=',num*i) 9 | -------------------------------------------------------------------------------- /Python3-Learn/dharmateja03_whatsapp.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Dharma Teja 2 | # Python3 Concept: Merge Sort 3 | # GITHUB: https://github.com/dharmateja03 4 | #https://pypi.org/project/pywhatkit/ 5 | #make sure you are loggedin WhatsappWeb. 6 | import pywhatkit 7 | number=input() #enter the number 8 | pywhatkit.sendwhatmsg(number,"This is a message",12,00) 9 | -------------------------------------------------------------------------------- /Python3-Learn/set_bits_count_dharmateja03.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Dharma Teja 2 | # Python3 Concept:counting number of set bits in a number 3 | # GITHUB: https://github.com/dharmateja03 4 | nunber=int(input()) #enter input 5 | result=0 6 | while number: 7 | if number % 2 == 1: 8 | result += 1 9 | number = number >> 1 10 | print(result) 11 | 12 | -------------------------------------------------------------------------------- /Python3-Learn/AddBinary-SnehaRautmare.py: -------------------------------------------------------------------------------- 1 | 2 | def addBinary(num1: str, num2: str) -> str: 3 | """ 4 | Method to add to binary numbers 5 | Parameters: Two binary numbers num1 and num2 (string) 6 | Output: Addition in binary 7 | """ 8 | sumnum = int(num1,2) + int(num2,2) 9 | print(bin(sumnum)[2:]) 10 | 11 | addBinary("11", "1") -------------------------------------------------------------------------------- /Python3-Learn/StringCopies-SanaaShah.py.py: -------------------------------------------------------------------------------- 1 | # 9. Write a Python program to get a string which is n (non-negative integer) copies of a given string 2 | 3 | str = input('Enter any String value: ') 4 | num = int(input('Enter the number of copies you want of the string: ')) 5 | final = '' 6 | for i in range(num): 7 | final = final + str 8 | 9 | print(final) 10 | -------------------------------------------------------------------------------- /Python3-Learn/circle-area_bonifasiustrg.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Bonifasius Tarigan 2 | // Python3 Concept: Area of circle 3 | // GITHUB: https://github.com/bonifasiustrg 4 | 5 | 6 | r=int(input("type what is the radius of the circle:")) 7 | if r%7==0: 8 | Area=(22/7)*r**2 9 | else: 10 | Area=3.14*r**2 11 | print("So, area of a circle with radius", r, "is","{:1}".format(Area)) 12 | -------------------------------------------------------------------------------- /Python3-Learn/SortAlphabeticalOrder_erarijit.py: -------------------------------------------------------------------------------- 1 | # Program to sort alphabetically the words form a string provided by the user 2 | 3 | # take input from the user 4 | my_str = input("Enter a string: ") 5 | 6 | # breakdown the string into a list of words 7 | words = my_str.split() 8 | 9 | # sort the list 10 | words.sort() 11 | 12 | # display the sorted words 13 | for word in words: 14 | print(word) 15 | -------------------------------------------------------------------------------- /Python3-Learn/IP-tracker.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import requests 3 | import json 4 | 5 | parser= argparse.ArgumentParse() 6 | 7 | parser.add_argument("-i", "--ipaddress", help="track IP address") 8 | 9 | args= parser.parse_args() 10 | 11 | ip= args.ipaddress 12 | 13 | url="http://ip-api.com/json"+ ip 14 | 15 | response= requests.get(url) 16 | data= json.loads(response) 17 | print(data.content) -------------------------------------------------------------------------------- /Python3-Learn/mersenne_guruprasanna02.py: -------------------------------------------------------------------------------- 1 | # // AUTHOR: Guruprasanna 2 | # // Python3 Concept: Mersenne numbers/functions 3 | # // GITHUB: https://github.com/Guruprasanna02 4 | 5 | # // Add your python3 concept below 6 | # To print first "n" mersenne numbers 7 | 8 | def mersenne(n): 9 | for i in range(2,n+2): 10 | print((2**i) - 1,end="\n") 11 | 12 | n = int(input("Enter an integer : ")) 13 | mersenne(n) -------------------------------------------------------------------------------- /Python3-Learn/fibonacci_lucasli233.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: lucasli233 2 | # Python3 Concept: Fibonacci Sequence 3 | # GITHUB: https://github.com/lucasli233 4 | 5 | def Fibonacci(n): 6 | if n < 0: 7 | print("Incorrect input") 8 | elif n == 0: 9 | return 0 10 | elif n == 1 or n == 2: 11 | return 1 12 | else: 13 | return Fibonacci(n-1) + Fibonacci(n-2) 14 | 15 | 16 | print(Fibonacci(9)) 17 | -------------------------------------------------------------------------------- /Python3-Learn/Capitalize_first_alphabet_AadityaKumra.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Aaditya Kumra 2 | # Python3 Concept:String traversing 3 | # GITHUB: https://github.com/AadityaKumra 4 | 5 | #capitalize first letter of each word. 6 | #input-elon musk 7 | #output-Elon Musk 8 | def solve(a): 9 | a = s.split(' ') 10 | n=(' '.join((word.capitalize() for word in a))) 11 | return n 12 | 13 | s = input() 14 | result = solve(s) 15 | print(result) 16 | -------------------------------------------------------------------------------- /Python3-Learn/rotate_list.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: prm1999 2 | # Python3 Concept: Rotate the word in the list. 3 | # GITHUB: https://github.com/prm1999 4 | 5 | # Function 6 | 7 | def rotate(arr, n): 8 | n = len(arr) 9 | i = 1 10 | x = arr[n - 1] 11 | for i in range(n - 1, 0, -1): 12 | arr[i] = arr[i - 1] 13 | 14 | arr[0] = x 15 | 16 | return arr 17 | 18 | 19 | #main 20 | 21 | A = [1, 2, 3, 4, 5] 22 | a=rotate(A,5) 23 | print(a) 24 | -------------------------------------------------------------------------------- /Python3-Learn/Rainbow_Benzene using Python Turtle Programming: -------------------------------------------------------------------------------- 1 | // AUTHOR: Vanshika 2 | // Python3 Concept: Breast Cancer Detection System 3 | // GITHUB: https://github.com/Vanshika-11 4 | 5 | 6 | import turtle 7 | colors = ['red', 'purple', 'blue', 'green', 'orange', 'yellow'] 8 | t = turtle.Pen() 9 | turtle.bgcolor('black') 10 | for x in range(360): 11 | t.pencolor(colors[x%6]) 12 | t.width(x/100 + 1) 13 | t.forward(x) 14 | t.left(59) 15 | 16 | -------------------------------------------------------------------------------- /Python3-Learn/Seperate_word_by#_mayankgoyal.py: -------------------------------------------------------------------------------- 1 | """ Aim: Read a text file line by line and display each word separated by a # 2 | Name: Mayank Goayl 3 | Github username: mayankgoyal-13 4 | """ 5 | #first creat a .txt file named list in the same directory.Then, add the content in it 6 | file_text = open("list.txt", 'r') 7 | for l in file_text: 8 | words = l.split() 9 | for i in words: 10 | print(i + '#', end='') 11 | print() 12 | file_text.close() 13 | -------------------------------------------------------------------------------- /Python3-Learn/finding_greatest.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Ankur 2 | # Python3 Concept: Finding greatest no amongst the following 3 | # GITHUB: https://github.com/ankur12-1610 4 | 5 | #Add your python3 concept below 6 | 7 | 8 | num1 = 10 9 | num2 = 14 10 | num3 = 12 11 | 12 | if (num1 >= num2) and (num1 >= num3): 13 | largest = num1 14 | elif (num2 >= num1) and (num2 >= num3): 15 | largest = num2 16 | else: 17 | largest = num3 18 | 19 | print("The largest number is", largest) 20 | -------------------------------------------------------------------------------- /Python3-Learn/Palindrome_github-dev21.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Devendra Patel 2 | //Python3 Concept: Palindrome 3 | // GITHUB: https://github.com/github-dev21 4 | 5 | print("Enter the Number ") 6 | num = int(input()) 7 | temp = num 8 | reverse = 0 9 | 10 | while(num>0): 11 | dig = num%10 12 | reverse = reverse*10+dig 13 | num = num//10 14 | 15 | print(reverse) 16 | if temp==reverse: 17 | print("Number is in Palindrome") 18 | else: 19 | print("Number is not in Palindrome") 20 | -------------------------------------------------------------------------------- /Python3-Learn/palindromicstring_RUDRANSH_HUB.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: RUDRANSH SRIVASTAVA 2 | // Python3 Concept: PALINDROME STRING OR NOT 3 | // GITHUB: https://github.com/RUDRANSH-hub 4 | 5 | '''TO FIND OUT WEATHER STRING IS PALINDROME OR NOT''' 6 | 7 | str=input("enter testing string:") 8 | reverse_str=str[::-1] #reverse slicing the original string 9 | if reverse_str==str: 10 | print("{} is palindrome".format(str)) 11 | else: 12 | print("{} is not palindrome".format(str)) 13 | 14 | -------------------------------------------------------------------------------- /Python3-Learn/Palindrome_Shyam-2001.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Devendra Patel 2 | //Python3 Concept: Palindrome 3 | // GITHUB: https://github.com/github-dev21 4 | 5 | print("Enter the Number ") 6 | num = int(input()) 7 | temp = num 8 | reverse = 0 9 | 10 | while(num>0): 11 | dig = num%10 12 | reverse = reverse*10+dig 13 | num = num//10 14 | 15 | print(reverse) 16 | if temp==reverse: 17 | print("Number is in Palindrome") 18 | else: 19 | print("Number is not in Palindrome") -------------------------------------------------------------------------------- /Python3-Learn/TwoSum.py: -------------------------------------------------------------------------------- 1 | #AUTHOR: Pornpimol Kaewphing 2 | #Python3 Concept: Twosum in Python 3 | #GITHUB: https://github.com/gympohnpimol 4 | 5 | class Solution: 6 | def twoSum(self, nums: List[int], target: int) -> List[int]: 7 | ls = [] 8 | for i in range(0, len(nums)): 9 | item = target - nums[i] 10 | nums[i] = "done" 11 | if item in nums: 12 | ls.append(i) 13 | ls.append(nums.index(item)) 14 | return ls -------------------------------------------------------------------------------- /Python3-Learn/python3-multipleAssignments-Sahilnegi-code.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Sahil Negi 2 | // Python3 Concept: (Multiple assignments in python) 3 | // GITHUB: https://github.com/Sahilnegi-code 4 | 5 | # Multiple assignments 6 | 7 | 8 | # 1- assigning same value to a multiple variable 9 | a=b=c=10; 10 | print(a); 11 | print(b); 12 | print(c); 13 | # 2- Assigning multiple values to multiple variable 14 | x,y,z =10,20,30; ## assigning the value in order wise. 15 | print(x); 16 | print(y); 17 | print(z); 18 | -------------------------------------------------------------------------------- /Python3-Learn/spambot.py: -------------------------------------------------------------------------------- 1 | //Author: Arayan Gupta 2 | //Python concept: Spam Bot 3 | //Github: https://github.com/Arayan1906 4 | 5 | import pyautogui, time 6 | time.sleep(5) 7 | f=open("spam.txt", 'r') 8 | for word in f: 9 | pyautogui.typewrite(word) 10 | pyautogui.press("enter") 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /Python3-Learn/CountWordWithPySpark_skinnycoders.py: -------------------------------------------------------------------------------- 1 | # // AUTHOR: Ristanto Rizki 2 | # // Python3 Concept: Count a word in file with pySpark 3 | # // GITHUB: https://github.com/SkinnyCoders 4 | 5 | from pyspark.sql import SparkSession 6 | 7 | # your file 8 | logfile = "/home/baskara/Downloads/cerpen.txt" 9 | spark = SparkSession.builder.appName("simpel spark").getOrCreate() 10 | logData = spark.read.text(logfile).cache() 11 | 12 | numAs = logData.filter(logData.value.contains('a')).count() 13 | 14 | print(numAs) 15 | -------------------------------------------------------------------------------- /Python3-Learn/InsertionSort.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Vinicius Saturnino 2 | # Python3 Concept: Insertion Sort 3 | # GITHUB: https://github.com/viniciussaturnino 4 | 5 | def insertionSort(arr): 6 | for i in range(1, len(arr)): 7 | key = arr[i] 8 | j = i-1 9 | while j >=0 and key < arr[j] : 10 | arr[j+1] = arr[j] 11 | j -= 1 12 | arr[j+1] = key 13 | 14 | arr = [12, 11, 13, 5, 6] 15 | insertionSort(arr) 16 | print ("Sorted array is:") 17 | for i in range(len(arr)): 18 | print ("%d" %arr[i]) -------------------------------------------------------------------------------- /Python3-Learn/some modules/wikipedia_avyayjain.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Avyay Jain 2 | // Python3 Concept: (calculator) 3 | // GITHUB: https://github.com/avyayjain 4 | 5 | import wikipedia as wiki 6 | 7 | n = input('Enter What You want to search : ') 8 | wresult = wiki.search(n) 9 | j=0 10 | 11 | for i in wresult: 12 | print('Enter ',j,' for search about ',i) 13 | j += 1 14 | 15 | ent = int(input('Enter Your Option : ')) 16 | print('you choose ',wresult[ent]) 17 | result = wiki.summary(wresult[ent],sentences=2) 18 | print(result) 19 | -------------------------------------------------------------------------------- /Python3-Learn/Try-Except_Ramptl.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Ram Patel 2 | // Python3 Concept: Try-Except in Python 3 | // GITHUB: https://github.com/Ramptl 4 | 5 | //# working of try() 6 | 7 | def divide(x, y): 8 | try: 9 | # Floor Division : Gives only Fractional Part as Answer 10 | result = x // y 11 | print("Yeah ! Your answer is :", result) 12 | except ZeroDivisionError: 13 | print("Sorry ! You are dividing by zero ") 14 | 15 | # Look at parameters and note the working of Program 16 | divide(3, 2) 17 | -------------------------------------------------------------------------------- /Python3-Learn/simple_intrest_mayankgoyal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : Simple Interest Calculator 3 | Author : [Mayank Goyal) [https://github.com/mayankgoyal-13] 4 | """ 5 | 6 | print('Welcome, to simple interest calculator') 7 | principal = int(input('Enter your principal amount: ')) 8 | roi = float(input('Enter your rate of interest: ')) 9 | time = float(input('Enter the time period/tenure in yrs: ')) 10 | simple_interest = (principal*roi*time)/100 11 | print('Your simple interest at the end of ' + str(time) + 'years will be: ' + str(simple_interest)) 12 | -------------------------------------------------------------------------------- /Python3-Learn/python3-all_primes_Dude-901.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Tanmay Khandelwal 2 | # Python3 Concept: all primes upto n 3 | # GITHUB: github.com/Dude-901 4 | 5 | # Sieve Theorem 6 | 7 | def sieve(p, n): 8 | for i in range(3, n+1, 2): 9 | p[i] = 1 10 | for i in range(3, n+1, 2): 11 | if p[i] == 1: 12 | for j in range(i*i, n+11, i): 13 | p[j] = 0 14 | 15 | p[2] = 1 16 | return p 17 | 18 | for _ in range(int(input())): 19 | n = int(input()) 20 | p = [0]*(n+1) 21 | p = sieve(p, n) 22 | -------------------------------------------------------------------------------- /Python3-Learn/Python3-Learn-Palindrome_Rishav00.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Rishav Dutta 2 | // Python3 Concept: Checking a string Palindrome or not 3 | // GITHUB: https://github.com/Rishav-00 4 | 5 | my_str = 'aIbohPhoBiA' 6 | 7 | # make it suitable for caseless comparison 8 | my_str = my_str.casefold() 9 | 10 | # reverse the string 11 | rev_str = reversed(my_str) 12 | 13 | # check if the string is equal to its reverse 14 | if list(my_str) == list(rev_str): 15 | print("The string is a palindrome.") 16 | else: 17 | print("The string is not a palindrome.") 18 | -------------------------------------------------------------------------------- /Python3-Learn/Fibonacci-VishnuRamV.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Vishnu Ram V 2 | // Python3 Concept: Fibonacci sequence 3 | // GITHUB: github.com/vishnuramv 4 | 5 | nterms = int(input("How many terms? ")) 6 | 7 | n1, n2 = 0, 1 8 | count = 0 9 | 10 | if nterms <= 0: 11 | print("Please enter a positive integer") 12 | elif nterms == 1: 13 | print("Fibonacci sequence upto",nterms,":") 14 | print(n1) 15 | else: 16 | print("Fibonacci sequence:") 17 | while count < nterms: 18 | print(n1) 19 | nth = n1 + n2 20 | n1 = n2 21 | n2 = nth 22 | count += 1 -------------------------------------------------------------------------------- /Python3-Learn/tipcalculator_neethujojigeorge.py: -------------------------------------------------------------------------------- 1 | 2 | # AUTHOR: Neethu Joji George 3 | # Python3 Concept: Tip Calculator Using Python 4 | # GITHUB: https://github.com/NeethuJojiGeorge 5 | 6 | #tip calculator code 7 | print("Bill Calculator With the Tip") 8 | 9 | def gettip(percentage, sub_total): 10 | tip = ((sub_total * percentage) / 100) 11 | total = (sub_total + tip) 12 | return total 13 | 14 | sub_total = int(input("How much is the bill?")) 15 | 16 | percentage = float(input("What percentage should the tip be?")) 17 | 18 | print (gettip(percentage, sub_total)) -------------------------------------------------------------------------------- /Python3-Learn/Josephus-problem_Tanmay-901.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Tanmay Khandelwal 2 | # Python3 Concept: The Josephus problem, where 100 people standing in a circle, 1 kills 2 passes the sword to 3….who survives in the end? 3 | # GITHUB: github.com/Tanmay-901 4 | 5 | from sys import stdin,stdout 6 | 7 | def Josephus_Prblm(n, k): 8 | if (n == 1): 9 | return 1 10 | else: 11 | return ((Josephus_Prblm(n - 1, k) + k-1) % n + 1) 12 | 13 | for _ in range(int(stdin.readline())): 14 | N = int(stdin.readline()) 15 | K = int(stdin.readline()) 16 | print(Josephus_Prblm(N,K) 17 | 18 | -------------------------------------------------------------------------------- /Python3-Learn/voice_reciever_Mgeethabhargava.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Mandava Geetha Bhargava 2 | # Python3 Concept: Voice Reciever using Python 3 | # GITHUB: https://github.com/Mgeethabhargava 4 | 5 | #Voice Reciever 6 | 7 | import speech_recognition as sr 8 | r = sr.Recognizer() 9 | with sr.Microphone as source: 10 | print("Speak Something") 11 | audio = r.listen(source) 12 | try: 13 | print("Your speech is:"+r.recognize_google(audio)) 14 | except sr.UnknownValueError: 15 | print("could not understand your speech") 16 | except sr.RequestError as e: 17 | print("could not request results:;{}".format(e)) 18 | -------------------------------------------------------------------------------- /Python3-Learn/Armstrong_number_Ajit.py: -------------------------------------------------------------------------------- 1 | #Author :- Ajit Varpe 2 | #Python Concept :- Python program to check if the number is an Armstrong number or not 3 | # GitLink :- https://github.com/AjitVarpe 4 | 5 | # take input from the user 6 | num = int(input("Enter a number: ")) 7 | 8 | # initialize sum 9 | sum = 0 10 | 11 | # find the sum of the cube of each digit 12 | temp = num 13 | while temp > 0: 14 | digit = temp % 10 15 | sum += digit ** 3 16 | temp //= 10 17 | 18 | # display the result 19 | if num == sum: 20 | print(num,"is an Armstrong number") 21 | else: 22 | print(num,"is not an Armstrong number") 23 | -------------------------------------------------------------------------------- /Python3-Learn/OOP_sample_program_priyajames.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: priyajames 2 | // Python3 Concept: oops in python 3 | // GITHUB: https://github.com/priyajames29 4 | 5 | //Add your python3 concept below 6 | 7 | 8 | 9 | 10 | 11 | class Cat: 12 | species = 'mammal' 13 | def __init__(self, name, age): 14 | self.name = name 15 | self.age = age 16 | 17 | 18 | 19 | cat1 = Cat("tutu" , 13) 20 | cat2 = Cat("aaa" , 5) 21 | cat3 = Cat("meow", 4) 22 | 23 | def oldest(*args): 24 | return max(args) 25 | 26 | print(f"The oldest cat is {oldest(cat1.age, cat2.age, cat3.age)} years old. ") 27 | 28 | -------------------------------------------------------------------------------- /Python3-Learn/python3_list_in_python_manasisaiba.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Manasi Saiba 2 | // Python3 Concept: LIST IN PYTHON 3 | // GITHUB: https://github.com/manasisaiba 4 | 5 | #Python offers a range of compound data types often referred to as sequences. 6 | # List is one of the most frequently used and very versatile data types used in Python. 7 | 8 | # empty list 9 | my_list = [] 10 | 11 | # list of integers 12 | my_list = [1, 2, 3] 13 | 14 | # list with mixed data types 15 | my_list = [1, "Hello", 3.4] 16 | #A list can also have another list as an item. This is called a nested list. 17 | # nested list 18 | my_list = ["mouse", [8, 4, 6], ['a']] -------------------------------------------------------------------------------- /Python3-Learn/Audio_Text_to_Speech_Dhallod07.py: -------------------------------------------------------------------------------- 1 | ''' 2 | AUTHOR: Ankush Dhallod 3 | Python3 Concept: Text to speech in Python 4 | GITHUB: https://www.github.com/Dhallod07 5 | ''' 6 | 7 | #pip install pyttsx3 8 | #This Library is used for TEXT TO SPEECH 9 | 10 | import pyttsx3 11 | 12 | speaker = pyttsx3.init() 13 | 14 | # Sets speed percent 15 | # Can be more than 100 16 | speaker.setProperty('rate', 120) 17 | 18 | voice_id = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_ZIRA_11.0" 19 | # Use female voice 20 | speaker.setProperty('voice', voice_id) 21 | speaker.say("Hello I can speak as well") 22 | speaker.runAndWait() -------------------------------------------------------------------------------- /Python3-Learn/Sort_Luckysopyantoro.py: -------------------------------------------------------------------------------- 1 | #AUTHOR: Lucky Sopyantoro 2 | #Python3 Concept: Sort in Python 3 | #GITHUB: https://github.com/luckysopyantoro 4 | # List of Integers 5 | numbers = [1, 3, 4, 2] 6 | 7 | # Sorting list of Integers 8 | numbers.sort() 9 | 10 | print(numbers) 11 | 12 | # List of Floating point numbers 13 | decimalnumber = [2.01, 2.00, 3.67, 3.28, 1.68] 14 | 15 | # Sorting list of Floating point numbers 16 | decimalnumber.sort() 17 | 18 | print(decimalnumber) 19 | 20 | # List of strings 21 | words = ["Luck", "For", "Luck"] 22 | 23 | # Sorting list of strings 24 | words.sort() 25 | 26 | print(words) -------------------------------------------------------------------------------- /Python3-Learn/discount_calculator.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Critical07 2 | # Python3 Concept: Discount calculator 3 | # GITHUB: https://github.com/Critical07 4 | 5 | #discount calculator code 6 | print("<----Count your final price after discount---->") 7 | 8 | # formation of the function 9 | def getFinalPrice(percentage, sub_total): 10 | final_price = (sub_total - ((sub_total * percentage) / 100)) 11 | return final_price 12 | 13 | sub_total = float(input("Total spending you did: ")) 14 | 15 | percentage = float(input("Total discount on the spending: ")) 16 | 17 | print("Your grandtotal after the discount is: ", getFinalPrice(percentage, sub_total)) 18 | -------------------------------------------------------------------------------- /Python3-Learn/find_substrings_AadityaKumra.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Aaditya Kumra 2 | # Python3 Concept:String traversing 3 | # GITHUB: https://github.com/AadityaKumra 4 | 5 | #print the number of times that the substring occurs in the given input string 6 | 7 | def count_substring(string, sub_string): 8 | counter,sum = 0,0 9 | for _ in range(0, len(string)): 10 | if string[counter:(len(sub_string)+counter)]==sub_string: 11 | sum = sum + 1 12 | counter=counter + 1 13 | return sum 14 | 15 | string = input().strip() 16 | sub_string = input().strip() 17 | 18 | count = count_substring(string, sub_string) 19 | print(count) -------------------------------------------------------------------------------- /Python3-Learn/matplotlib-plot_dalonlobo.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Dalon Lobo 2 | # Python3 Concept: Plotting line plot using matplotlib 3 | # GITHUB: https://github.com/dalonlobo 4 | 5 | import numpy as np 6 | import matplotlib.pyplot as plt 7 | 8 | # Create dummy x and y values. In this case I create values using numpy. 9 | # This graph will show sine wave 10 | x = np.arange(0, 10, 0.1) # Values for x coordinate 11 | y = np.sin(x) # Values for y coordinate using numpy sin function 12 | plt.plot(x, y) # Plots the x and y coordinates 13 | plt.xlabel("x - values") # show x label 14 | plt.ylabel("y = sin(x)") # show y label 15 | plt.show() # Displays the plot 16 | -------------------------------------------------------------------------------- /Python3-Learn/datatypes.py: -------------------------------------------------------------------------------- 1 | a = 5 2 | print(a, "is of type", type(a)) 3 | 4 | a = 2.0 5 | print(a, "is of type", type(a)) 6 | 7 | a = 1+2j 8 | print(a, "is complex number?", isinstance(1+2j,complex)) 9 | 10 | a = [5,10,15,20,25,30,35,40] 11 | 12 | # a[2] = 15 13 | print("a[2] = ", a[2]) 14 | 15 | # a[0:3] = [5, 10, 15] 16 | print("a[0:3] = ", a[0:3]) 17 | 18 | # a[5:] = [30, 35, 40] 19 | print("a[5:] = ", a[5:]) 20 | 21 | t = (5,'program', 1+3j) 22 | 23 | # t[1] = 'program' 24 | print("t[1] = ", t[1]) 25 | 26 | # t[0:3] = (5, 'program', (1+3j)) 27 | print("t[0:3] = ", t[0:3]) 28 | 29 | # Generates error 30 | # Tuples are immutable 31 | t[0] = 10 32 | -------------------------------------------------------------------------------- /Python3-Learn/Factorial_erarijit.py: -------------------------------------------------------------------------------- 1 | # Python program to find the factorial of a number using recursion 2 | 3 | def recur_factorial(n): 4 | """Function to return the factorial 5 | of a number using recursion""" 6 | if n == 1: 7 | return n 8 | else: 9 | return n*recur_factorial(n-1) 10 | 11 | 12 | # take input from the user 13 | num = int(input("Enter a number: ")) 14 | 15 | # check is the number is negative 16 | if num < 0: 17 | print("Sorry, factorial does not exist for negative numbers") 18 | elif num == 0: 19 | print("The factorial of 0 is 1") 20 | else: 21 | print("The factorial of",num,"is",recur_factorial(num)) 22 | -------------------------------------------------------------------------------- /Python3-Learn/fibonacciSequence.py: -------------------------------------------------------------------------------- 1 | # // AUTHOR: Devnarayan Patel 2 | # // Python3 Concept: Fibonacci Sequence 3 | # // GITHUB: https://github.com/devnarayanp02 4 | # Function for nth fibonacci number - Dynamic Programming 5 | # Taking 1st two fibonacci numbers as 0 and 1 6 | 7 | FibArray = [0, 1] 8 | 9 | def fibonacci(n): 10 | if n<0: 11 | print("Incorrect input") 12 | elif n<= len(FibArray): 13 | return FibArray[n-1] 14 | else: 15 | temp_fib = fibonacci(n-1)+fibonacci(n-2) 16 | FibArray.append(temp_fib) 17 | return temp_fib 18 | 19 | # Driver Program 20 | a = int(input("Enter Series Number to find Fibonacci Number : ")) 21 | print(fibonacci(a)) 22 | -------------------------------------------------------------------------------- /Python3-Learn/lettersearch/README.txt: -------------------------------------------------------------------------------- 1 | This module provids the lettersearch method that takes two strings, one for a phrase and one for a set of letters to search within that phrase. 2 | 3 | To create a package from your own material: 4 | 5 | 1) Create a setup.py file (check the included setup.py for an example) 6 | 7 | 2) Create a README.txt file. This file will provide details on the package 8 | 9 | 3) install setuptools and wheel 10 | python3 -m pip install --user --upgrade setuptools wheel 11 | 12 | 4) create the package 13 | python3 setup.py sdist bdist_wheel 14 | 15 | This will create a /dist directory that will include your package materials 16 | -------------------------------------------------------------------------------- /Python3-Learn/Inheritance_ADHIL-MOHAMMED-P-N.py: -------------------------------------------------------------------------------- 1 | #// AUTHOR: Adhil Mohammed P N 2 | #// Python3 Concept: Inheritance in python 3 | #// GITHUB: https://github.com/ADHIL-MOHAMMED-P-N 4 | 5 | #//Add your python3 concept below 6 | 7 | class Person(object): 8 | 9 | def __init__(self, name): 10 | self.name = name 11 | 12 | def getName(self): 13 | return self.name 14 | 15 | def isEmployee(self): 16 | return False 17 | 18 | 19 | class Employee(Person): 20 | 21 | def isEmployee(self): 22 | return True 23 | 24 | emp = Person("Geek1") 25 | print(emp.getName(), emp.isEmployee()) 26 | 27 | emp = Employee("Geek2") 28 | print(emp.getName(), emp.isEmployee()) 29 | -------------------------------------------------------------------------------- /Python3-Learn/clock_Mgeethabhargava.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Mandava Geetha Bhargava 2 | # Python3 Concept: Clock using python 3 | # GITHUB: https://github.com/Mgeethabhargava 4 | 5 | #Clock Code 6 | 7 | 8 | from tkinter import * 9 | from tkinter.ttk import * 10 | 11 | from time import strftime 12 | 13 | root=Tk() 14 | root.title('clock') 15 | 16 | def time(): 17 | string=strftime('%H:%M:%S ') 18 | label.config(text=string) 19 | label.after(1000,time) 20 | label= Label(root, font=('ds-digital',80), background="black",foreground='yellow') #install ds-digital font just searching on google 21 | label.pack(anchor='center') 22 | 23 | time() 24 | 25 | mainloop() 26 | -------------------------------------------------------------------------------- /Python3-Learn/BiggestNumberOutOf3_erarijit.py: -------------------------------------------------------------------------------- 1 | # Python program to find the largest number among the three input numbers 2 | 3 | # change the values of num1, num2 and num3 4 | # for a different result 5 | num1 = 10 6 | num2 = 14 7 | num3 = 12 8 | 9 | # uncomment following lines to take three numbers from user 10 | #num1 = float(input("Enter first number: ")) 11 | #num2 = float(input("Enter second number: ")) 12 | #num3 = float(input("Enter third number: ")) 13 | 14 | if (num1 >= num2) and (num1 >= num3): 15 | largest = num1 16 | elif (num2 >= num1) and (num2 >= num3): 17 | largest = num2 18 | else: 19 | largest = num3 20 | 21 | print("The largest number is", largest) 22 | -------------------------------------------------------------------------------- /Python3-Learn/python3-randomnumbergenerator_aadyar882.py: -------------------------------------------------------------------------------- 1 | """ 2 | // AUTHOR: Aadya Rangole 3 | // Python3 Concept: Random Number Generator (generates a list of random numbers given a list length and a minimum value) 4 | // GITHUB: github.com/aadyar882 5 | 6 | //Add your python3 concept below 7 | """ 8 | import random 9 | lis = [] 10 | def randnumbergenerator(): 11 | range_n = input("How many numbers do you want to generate?: ") 12 | minval = input("What is the minimum value you want to generate?: ") 13 | while len(lis) <= 10: 14 | lis.append(int(range_n)*random.random()+int(minval)) 15 | if len(lis) == 10 : 16 | break 17 | print(lis) 18 | -------------------------------------------------------------------------------- /Python3-Learn/quadratic_equation_solver_mayank.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : Quadratic equation solver 3 | Author : [Mayank Goyal) [https://github.com/mayankgoyal-13] 4 | """ 5 | 6 | from math import sqrt 7 | 8 | print("Quadratic function : (a * x\u00b2) + b*x + c") 9 | a = float(input("a: ")) 10 | b = float(input("b: ")) 11 | c = float(input("c: ")) 12 | 13 | disc = b ** 2 - 4 * a * c 14 | 15 | if disc > 0: 16 | x1 = ((-b) + sqrt(r)) // (2 * a) 17 | x2 = ((-b) - sqrt(r)) / (2 * a) 18 | print("There are 2 roots:", x1, x2) 19 | 20 | elif disc == 0: 21 | x = (-b) / 2 * a 22 | print("There is one root: ", x) 23 | 24 | else: 25 | print("No roots, discriminant < 0.") 26 | -------------------------------------------------------------------------------- /Python3-Learn/covid19api_guptadev21.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Dev Gupta 2 | // Python3 Concept: using covid19dh library to get data 3 | // GITHUB: https://github.com/guptadev21 4 | 5 | //Add your python3 concept below 6 | 7 | from covid19dh import covid19 8 | import datetime 9 | 10 | a, data = covid19(raw = True, verbose = False) 11 | 12 | country = input("For which country you want the data: \n") 13 | 14 | a, data = covid19(country, cache = False, verbose = False, start = datetime.date(2021,10,1)) 15 | 16 | 17 | #print(data.columns) #shows no. of total columns that can be accessed 18 | #print(data) #to show all the data 19 | print(data.iso_alpha_3) # to show only country and no. of cases 20 | -------------------------------------------------------------------------------- /Python3-Learn/some modules/sendmail_avyayjain.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Avyay Jain 2 | // Python3 Concept: (calculator) 3 | // GITHUB: https://github.com/avyayjain 4 | 5 | import smtplib 6 | from email.mime.multipart import MIMEMultipart 7 | 8 | msg = MIMEMultipart() 9 | 10 | 11 | sender = input('enter your email') 12 | password = input('enter your password') 13 | message = input('enter your message) 14 | 15 | recivers = ['enter recivers email'] 16 | 17 | a = smtplib.SMTP('smtp.gmail.com',587) 18 | 19 | a.starttls() 20 | 21 | msg['Subject'] = "hii this is mail" 22 | 23 | a.login('sender','password') 24 | 25 | a.sendmail('sender',recivers,'test message') 26 | 27 | a.quit() 28 | 29 | 30 | -------------------------------------------------------------------------------- /Python3-Learn/Searching/Linear_Search.py: -------------------------------------------------------------------------------- 1 | '''Linear Search Algorithm 2 | Step-1:Start from the leftmost element of arr[] and one by one compare x with each element of arr[] 3 | Step-2:If x matches with an element, return the index. 4 | Step-3:If x doesn’t match with any of elements, return -1.''' 5 | def search(arr, n, x): 6 | 7 | for i in range (0, n): 8 | if (arr[i] == x): 9 | return i; 10 | return -1; 11 | 12 | # Driver Code 13 | arr = [ 2, 3, 4, 10, 40 ]; 14 | x = 10; 15 | n = len(arr); 16 | result = search(arr, n, x) 17 | if(result == -1): 18 | print("Element is not present in array") 19 | else: 20 | print("Element is present at index", result); 21 | -------------------------------------------------------------------------------- /Python3-Learn/python3-ArrayRotation-mephisto2975.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Parth Kholkute 2 | # Python3 Concept: Array Rotation 3 | # GITHUB: github.com/mephisto2975 4 | 5 | # function to rotate array by d elements using temp array 6 | def rotateArray(arr, n, d): 7 | temp = [] 8 | i = 0 9 | while (i < d): 10 | temp.append(arr[i]) 11 | i = i + 1 12 | i = 0 13 | while (d < n): 14 | arr[i] = arr[d] 15 | i = i + 1 16 | d = d + 1 17 | arr[:] = arr[: i] + temp 18 | return arr 19 | 20 | 21 | # Driver function to test above function 22 | arr = [1, 2, 3, 4, 5, 6, 7] 23 | print("Array after left rotation is: ", end=' ') 24 | print(rotateArray(arr, len(arr), 2)) -------------------------------------------------------------------------------- /Python3-Learn/scrape.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import requests 4 | from bs4 import BeautifulSoup 5 | 6 | url = "https://www.flipkart.com/search?q=mobiles&as=on&as-show=on&otracker=AS_Query_TrendingAutoSuggest_1_0_na_na_na&otracker1=AS_Query_TrendingAutoSuggest_1_0_na_na_na&as-pos=1&as-type=TRENDING&suggestionId=mobiles&requestId=994e1fc4-4bee-4da2-83c9-ff6663b2e0da" 7 | 8 | #get the HTML 9 | r = requests.get(url) 10 | htmlContent = r.content 11 | #print(htmlContent) 12 | soup = BeautifulSoup(htmlContent, 'html.parser') 13 | 14 | job_elems = soup.find_all('div', class_='_1HmYoV _35HD7C') 15 | 16 | for job in job_elems: 17 | product = job.find_all('div', class_='_3wU53n') 18 | for pr in product: 19 | print(pr.text) 20 | -------------------------------------------------------------------------------- /Python3-Learn/command-line-arguments_Bhairavi-shah.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Bhairavi-shah 2 | // Python3 Concept: Command Line Arguments 3 | // GITHUB: github.com/Bhairavi-shah 4 | 5 | # Add integers that have been passed as arguments in the command line 6 | # For example, if you run: $python file-name.py 1 2 3 7 | # The output must be 6 8 | 9 | import sys 10 | try: 11 | # We convert each argument passed to int and then add it to sum. 12 | # sys.argv[0] is not taken because that returns the file name 13 | total = sum(int(arg) for arg in sys.argv[1:]) 14 | print('Sum = ', total) 15 | 16 | except ValueError: 17 | # When no arguments are passed, ValueError occurs 18 | print('Please supply integer arguments') 19 | -------------------------------------------------------------------------------- /Python3-Learn/quicksort_srikar999.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Srikar 2 | # Python3 Concept: quicksort 3 | # GITHUB: https://github.com/srikar999 4 | 5 | def partition(lst,start,end): 6 | pivot=lst[start] 7 | pivot_index=start 8 | while startpivot:end-=1 11 | if starta[j+1]): 14 | tmp = a[j] 15 | a[j]= a[j+1] 16 | a[j+1] = tmp 17 | for i in range(n): 18 | print(a[i],end=" ") 19 | 20 | 21 | 22 | 23 | a = input().split() 24 | bubble(a) 25 | 26 | -------------------------------------------------------------------------------- /Python3-Learn/create SQL table_passionlord.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Vighnesh 2 | // Python3 Concept: Creating SQL table using Python 3 | // GITHUB: github.com/passionlord 4 | 5 | 6 | 7 | import pymysql as ps 8 | 9 | try: 10 | cn = ps.connect(host='localhost',port=3306,user='root',password='123',db='tata') 11 | ''' 12 |     cursor() is used to create command 13 |     object, which is use to supply sql queries 14 |     to database engine 15 |     ''' 16 | cmd = cn.cursor() 17 | query = "create table products(productid varchar(10) primary key,productname varchar(45),productrate decimal(10),mfdate date)" 18 | cmd.execute(query) 19 | print("Table Created..") 20 | cn.commit() 21 | cn.close() 22 | except Exception as e: 23 | print("Error:",e) 24 | -------------------------------------------------------------------------------- /Python3-Learn/matrix_transpose_akash435.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Akash Rajak 2 | # Python3 Concept: Matrix Transpose 3 | # GITHUB: https://github.com/akash435 4 | 5 | # Add your python3 concept below 6 | 7 | def matrix_transpose(): 8 | for i in range(len(A)): 9 | for j in range(len(A[0])): 10 | res[i][j] = A[j][i] 11 | 12 | A=[] 13 | 14 | print("Enter N:") 15 | n = int(input()) 16 | 17 | print("Enter Matrix A:") 18 | for i in range(0, n): 19 | temp = [] 20 | for j in range(0, n): 21 | x = int(input()) 22 | temp.append(x) 23 | A.append(temp) 24 | 25 | res = [] 26 | for i in range(0, n): 27 | temp = [] 28 | for j in range(0, n): 29 | temp.append(0) 30 | res.append(temp) 31 | 32 | matrix_transpose() 33 | 34 | for r in res: 35 | print(r) 36 | -------------------------------------------------------------------------------- /Python3-Learn/reverse-nparray_Christy538.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Christy Thomas 2 | // Python3 Concept: Numpy array 3 | // GITHUB: https://github.com/Christy538 4 | 5 | 6 | ''' 7 | Task 8 | You are given a space separated list of numbers. 9 | Your task is to print a reversed NumPy array with the element type float. 10 | Input Format 11 | A single line of input containing space separated numbers. 12 | Output Format 13 | Print the reverse NumPy array with type float. 14 | Sample Input 15 | 1 2 3 4 -8 -10 16 | Sample Output 17 | [-10. -8. 4. 3. 2. 1.] 18 | ''' 19 | 20 | import numpy 21 | 22 | def arrays(arr): 23 | a = numpy.array(arr) 24 | a = a.astype('float64') 25 | return a[::-1] 26 | 27 | 28 | arr = input().strip().split(' ') 29 | result = arrays(arr) 30 | print(result) 31 | -------------------------------------------------------------------------------- /Python3-Learn/find_string_duplicates_edusanketdk.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Sanket Khadse 2 | # Python3 Concept: Find Duplicate characters in a string 3 | # GITHUB: https://github.com/edusanketdk 4 | 5 | def sol_1(s: str) -> dict: 6 | """using default dictionary""" 7 | from collections import defaultdict 8 | 9 | dct = defaultdict(int) 10 | for i in s: 11 | dct[i] += 1 12 | 13 | ans = dict() 14 | for i in dct: 15 | if dct[i] > 1: 16 | ans[i] = dct[i] 17 | 18 | return ans 19 | 20 | def sol_2(s: str) -> dict: 21 | """using ascii array""" 22 | ar = [0]*26 23 | for i in s: 24 | ar[ord(i)-97] += 1 25 | 26 | ans = {} 27 | for i in range(26): 28 | if ar[i] > 1: 29 | ans[chr(97+i)] = ans[i] 30 | 31 | return ans 32 | -------------------------------------------------------------------------------- /Python3-Learn/welcome_square_pattern_AadityaKumra.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Aaditya Kumra 2 | # Python3 Concept:String,patterns 3 | # GITHUB: https://github.com/AadityaKumra 4 | 5 | 6 | #Pattern size must be N X M. (N is an odd natural number,M and is 3 times N.) 7 | #Size constraints to ensure proper pattern implementation. 8 | #input example= 5 15 ,10 30 9 | t=input("Enter Dimension of pattern(a b):") 10 | s=list(map(int,(t.split(" ")))) 11 | a=s[0] 12 | b=s[1] 13 | z=list() 14 | for i in range(0,a): 15 | if i%2!=0: 16 | z.append(i) 17 | e=int((a-1)/2) 18 | c=int(b) 19 | for i in range(0,e): 20 | print("-"*int((c-3)/2)+".|."*int(z[i])+"-"*int((c-3)/2)) 21 | c-=6 22 | print("-"*int((b-7)/2)+"WELCOME"+"-"*int((b-7)/2)) 23 | 24 | for i in range(e-1,-1,-1): 25 | print("-"*int((c+3)/2)+".|."*int(z[i])+"-"*int((c+3)/2)) 26 | c+=6 27 | -------------------------------------------------------------------------------- /Python3-Learn/mergesort.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Dharma Teja 2 | # Python3 Concept: Merge Sort 3 | # GITHUB: https://github.com/dharmateja03 4 | def mergeSort(arr): 5 | if len(arr) > 1: 6 | mid = len(arr)//2 7 | L = arr[:mid] 8 | R = arr[mid:] 9 | mergeSort(L) 10 | mergeSort(R) 11 | i = j = k = 0 12 | while i < len(L) and j < len(R): 13 | if L[i] < R[j]: 14 | arr[k] = L[i] 15 | i += 1 16 | else: 17 | arr[k] = R[j] 18 | j += 1 19 | k += 1 20 | while i < len(L): 21 | arr[k] = L[i] 22 | i += 1 23 | k += 1 24 | 25 | while j < len(R): 26 | arr[k] = R[j] 27 | j += 1 28 | k += 1 29 | l=[3,4,1,5,6,1,0,4] 30 | mergeSort(l) 31 | print(l) 32 | 33 | 34 | -------------------------------------------------------------------------------- /Python3-Learn/cleaner-dates_JoaquinMontesinos.py: -------------------------------------------------------------------------------- 1 | #AUTHOR: JoaquinMontesinos 2 | #Python3 Concept: Normalice dates 3 | #GITHUB: https://github.com/JoaquinMontesinos 4 | 5 | import datetime 6 | from datetime import datetime 7 | import re 8 | import locale 9 | locale.setlocale(locale.LC_ALL, "") 10 | 11 | def clean_date(dates): 12 | possible_format = ['%d.%m.%y', '%d/%m/%y', '%d/%m/%Y'] 13 | convert_dates = [] 14 | ko = True 15 | for formats in possible_format: 16 | try: 17 | temp = datetime.strptime(dates, formats).strftime('%Y-%m-%d %H:%M:%S') 18 | convert_dates.append(temp) 19 | ko = False 20 | break 21 | except Exception as e: pass 22 | if ko: 23 | convert_dates.append(None) 24 | dates=convert_dates[0] 25 | return dates 26 | 27 | 28 | date=clean_date('03.05.19') 29 | print(date) -------------------------------------------------------------------------------- /Python3-Learn/chess_gouravchawla334.py: -------------------------------------------------------------------------------- 1 | #AUTHOR: Gourav chawla 2 | #Python3 Concept: Simple Chess using python 3 | #GITHUB: https://github.com/gouravchawla334 4 | 5 | import matplotlib.pyplot as plt 6 | import numpy as np 7 | from matplotlib.colors import LogNorm 8 | dx, dy = 0.015, 0.05 9 | x = np.arange(-4.0, 4.0,dx) 10 | y = np.arange(-4.0, 4.0,dx) 11 | X, Y = np.meshgrid(x,y) 12 | extent = np.min(x), np.max(x), np.min(y), np.max(y) 13 | Z1 = np.add.outer(range(8), range(8))%2 14 | plt.imshow(Z1,cmap="binary_r", 15 | interpolation='nearest', 16 | extent=extent,alpha=1) 17 | 18 | def copyassignment(x,y): 19 | return(1- x/ 2 + x**5 + y**6)*np.exp(-(x**2+y**2)) 20 | Z2 = copyassignment(X,Y) 21 | plt.imshow(Z2, alpha=0.7, interpolation='bilinear',extent=extent) 22 | plt.cool() 23 | plt.title('matplotlib.pyplot.cool() function Example', fontweight='bold') 24 | plt.show() -------------------------------------------------------------------------------- /Python3-Learn/matrix_spiral_traversal_edusanketdk.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Sanket Khadse 2 | // Python3 Concept: Spirally traversing a matrix 3 | // GITHUB: https://github.com/edusanketdk 4 | 5 | def sol_1(mat: list) -> list: 6 | u, r, d, l, dir = 0, len(mat[0]), len(mat), 0, 0 7 | ans = [] 8 | 9 | while u <= d and l <= r: 10 | if dir == 0: 11 | for i in range(l, r+1): 12 | ans.append(mat[u][i]) 13 | u += 1 14 | elif dir == 1: 15 | for i in range(u, d+1): 16 | ans.append(mat[i][r]) 17 | r -= 1 18 | elif dir == 2: 19 | for i in range(r, l-1, -1): 20 | ans.append(mat[d][i]) 21 | d -= 1 22 | else: 23 | for i in range(d, u-1, -1): 24 | ans.append(mat[i][l]) 25 | l += 1 26 | dir = (dir + 1)%4 27 | 28 | return ans 29 | -------------------------------------------------------------------------------- /Python3-Learn/send_email.py: -------------------------------------------------------------------------------- 1 | import smtplib 2 | import ssl 3 | from email.mime.multipart import MIMEMultipart 4 | from email.mime.text import MIMEText 5 | 6 | try: 7 | email = "<< Enter your email >>" 8 | password = "<< Enter your password" 9 | to = "<< Enter sender email >>" 10 | msg = """ << Email Body >>""" 11 | message = MIMEMultipart() 12 | message["From"] = email 13 | message["To"] = to 14 | message["Subject"] = "HacktoberFest 2019" 15 | message.attach(MIMEText(msg, "plain")) 16 | context = ssl.create_default_context() 17 | server = smtplib.SMTP("smtp.gmail.com") 18 | server.starttls() 19 | server.ehlo() 20 | server.login(email, password) 21 | server.sendmail(email, to, message.as_string()) 22 | print('Email have been successfully send') 23 | 24 | except Exception as ex: 25 | print(ex) 26 | 27 | finally: 28 | server.quit() 29 | © 2020 GitHub, Inc. 30 | -------------------------------------------------------------------------------- /Python3-Learn/prime-or-not_Christy538.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Christy Thomas 2 | // Python3 Concept: Basic concept (Condition and for loop) 3 | // GITHUB: https://github.com/Christy538 4 | 5 | 6 | '''Question: Python Program to check if a number is prime or not 7 | 8 | What is a prime number? 9 | A positive integer greater than 1 which has no other factors except 1 and the number itself is called a prime number. 10 | 2, 3, 5, 7 etc. are prime numbers as they do not have any other factors 11 | ''' 12 | 13 | num = int(input("Enter a number: ")) 14 | 15 | if num > 1: 16 | for i in range(2, num): 17 | if (num % i) == 0: 18 | print(num, "is not a prime number") 19 | break 20 | else: 21 | print(num, "is a prime number") 22 | else: 23 | print(num, "is not a prime number") 24 | 25 | ''' 26 | Input: 5 27 | Output: 5 is a prime number 28 | Input:10 29 | Output:10 is not a prime number 30 | 31 | ''' 32 | -------------------------------------------------------------------------------- /Python3-Learn/Matrix_Multi_SumanthBajjuri07.py: -------------------------------------------------------------------------------- 1 | """ 2 | AUTHOR: SumanthBajjuri07 3 | Python3 Concept: Matrix Multplication 4 | GITHUB: https://github.com/SumanthBajjuri07 5 | Matrix Multplication is a important algorithm it is sloved using nested loops and code is written in python. 6 | """ 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | # Program to multiply two matrices using nested loops 15 | 16 | # 3x3 matrix 17 | X = [[12,7,3], 18 | [4 ,5,6], 19 | [7 ,8,9]] 20 | # 3x4 matrix 21 | Y = [[5,8,1,2], 22 | [6,7,3,0], 23 | [4,5,9,1]] 24 | # result is 3x4 25 | result = [[0,0,0,0], 26 | [0,0,0,0], 27 | [0,0,0,0]] 28 | 29 | # iterate through rows of X 30 | for i in range(len(X)): 31 | # iterate through columns of Y 32 | for j in range(len(Y[0])): 33 | # iterate through rows of Y 34 | for k in range(len(Y)): 35 | result[i][j] += X[i][k] * Y[k][j] 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Python3-Learn/sieve_of_eratosthenes_Developer-R-7.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Rushi Patel 2 | # Python3 Concept: Sieve of Eratosthenes (To find prime number between given range) 3 | # GITHUB: https://github.com/Developer-R-7 4 | 5 | 6 | 7 | def SieveOfEratosthenes(n): 8 | prime = [True for i in range(n + 1)] 9 | p = 2 10 | while (p * p <= n): 11 | 12 | # If prime[p] is not changed, then it is a prime 13 | if (prime[p] == True): 14 | 15 | # Update all multiples of p 16 | for i in range(p ** 2, n + 1, p): 17 | prime[i] = False 18 | p += 1 19 | prime[0]= False 20 | prime[1]= False 21 | for p in range(n + 1): 22 | if prime[p]: 23 | print(p) 24 | 25 | # Run the program 26 | if __name__=='__main__': 27 | n = 30 # range 0-30 28 | print("Following are the prime numbers smaller than or equal to " + str(n)) 29 | SieveOfEratosthenes(n) -------------------------------------------------------------------------------- /Python3-Learn/OTP-verification-system_santanukumar666.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Santanu Kumar 2 | // Python3 Concept: OTP verification system 3 | // GITHUB: https://github.com/santanukumar666 4 | 5 | 6 | 7 | import os 8 | import math 9 | import smtplib 10 | import random 11 | 12 | 13 | digits="0123456789" 14 | OTP="" 15 | for i in range(6): 16 | OTP+=digits[math.floor(random.random()*10)] 17 | otp = OTP + " is your OTP" 18 | msg= otp 19 | 20 | #You need Google app password to be able to send emails using your Gmail account 21 | #After you create your app password for your Gmail account you will get a key.Paste it below. 22 | 23 | s = smtplib.SMTP('smtp.gmail.com', 587) 24 | s.starttls() 25 | s.login("Your Gmail Account", "You app password") 26 | emailid = input("Enter your email: ") 27 | s.sendmail('#########',emailid,msg) 28 | a = input("Enter the recieved OTP : ") 29 | if a == OTP: 30 | print("Verified") 31 | else: 32 | print("Please Check your OTP again") 33 | -------------------------------------------------------------------------------- /Python3-Learn/some modules/weather_avyayjain.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Avyay Jain 2 | // Python3 Concept: (calculator) 3 | // GITHUB: https://github.com/avyayjain 4 | 5 | import requests 6 | from bs4 import BeautifulSoup 7 | 8 | city = str(input("enter city name ")) 9 | 10 | url = "https://google.com/search?q="+"weather"+city 11 | html = requests.get(url).content 12 | 13 | soup = BeautifulSoup(html,'html.parser') 14 | 15 | temp = soup.find('div',attrs={'class': 'BNeawe iBp4i AP7Wnd'}).text 16 | 17 | time_skyDescription = soup.find('div',attrs={'class': 'BNeawe tAd8D AP7Wnd'}).text 18 | 19 | data = time_skyDescription.split('\n') 20 | time = data[0] 21 | sky = data[1] 22 | 23 | listdiv = soup.findAll('div',attrs={'class': 'BNeawe s3v9rd AP7Wnd'}) 24 | 25 | 26 | strd = listdiv[5].text 27 | 28 | pos = strd.find('wind') 29 | otherData= strd[pos:] 30 | 31 | print("Temperature is ",temp) 32 | print("time is ",time) 33 | print("sky description: ",sky) 34 | print(otherData) 35 | -------------------------------------------------------------------------------- /Python3-Learn/Python Lambda.py: -------------------------------------------------------------------------------- 1 | #AUTHOR: Ankita Mandal 2 | #Python3 Concept: Python Lambda 3 | #GITHUB: https://github.com/GoGi2712 4 | 5 | A lambda function is a small anonymous function. 6 | 7 | A lambda function can take any number of arguments, but can only have one expression. 8 | 9 | Syntax 10 | lambda arguments : expression 11 | The expression is executed and the result is returned: 12 | 13 | Example 14 | Add 10 to argument a, and return the result: 15 | 16 | x = lambda a : a + 10 17 | print(x(5)) 18 | Lambda functions can take any number of arguments: 19 | 20 | Example 21 | Multiply argument a with argument b and return the result: 22 | 23 | x = lambda a, b : a * b 24 | print(x(5, 6)) 25 | Example 26 | Summarize argument a, b, and c and return the result: 27 | 28 | x = lambda a, b, c : a + b + c 29 | print(x(5, 6, 2)) 30 | 31 | # Python program to demonstrate 32 | # lambda functions 33 | 34 | 35 | string ='Hacktoberfest2021' 36 | 37 | # lambda returns a function object 38 | print(lambda string : string) 39 | -------------------------------------------------------------------------------- /Python3-Learn/python3-DetectCycles_barlerer.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Bar Lerer 2 | # Python3 Concept: Algorithm to find if there is a circle in a singly linked list, and returns the start of that cycle 3 | # GITHUB: https://github.com/Barlerer 4 | 5 | # Definition for singly-linked list. 6 | # class ListNode: 7 | # def __init__(self, x): 8 | # self.val = x 9 | # self.next = None 10 | 11 | class Solution: 12 | def detectCycle(self, head: ListNode) -> ListNode: 13 | 14 | if not head or not head.next: 15 | return None 16 | slow = head 17 | fast = head 18 | 19 | while slow.next and fast.next and fast.next.next: 20 | slow = slow.next 21 | fast = fast.next.next 22 | if slow == fast: 23 | slow = head 24 | while (slow!=fast): 25 | fast=fast.next 26 | slow=slow.next 27 | return fast 28 | return None 29 | -------------------------------------------------------------------------------- /Python3-Learn/python3-EvenOddSegregation-mephisto2975.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Parth Kholkute 2 | # Python3 Concept: Array Rotation 3 | # GITHUB: github.com/mephisto2975 4 | 5 | def segregateEvenOdd(arr): 6 | 7 | # Initialize left and right indexes 8 | left = 0 9 | right = len(arr)-1 10 | 11 | while left < right: 12 | 13 | # Increment left index while we see 0 at left 14 | while (arr[left]%2==0 and left < right): 15 | left += 1 16 | 17 | # Decrement right index while we see 1 at right 18 | while (arr[right]%2 == 1 and left < right): 19 | right -= 1 20 | 21 | if (left < right): 22 | # Swap left element of arr with right element 23 | arr[left],arr[right] = arr[right],arr[left] 24 | left += 1 25 | right = right-1 26 | 27 | #Driver function 28 | arr = [29, 7, 98, 9, 30, 2, 74, 67] 29 | segregateEvenOdd(arr) 30 | print ("Array after segregation "), 31 | for i in range(0,len(arr)): 32 | print (arr[i], end=" ") -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Aman kumar sharma 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Python3-Learn/Merge2_dicts_SumanthBajjuri07.py: -------------------------------------------------------------------------------- 1 | 2 | #AUTHOR: SumanthBajjuri07 3 | #Python3 Concept: Merging 2 dictionaries 4 | #GITHUB: https://github.com/SumanthBajjuri07 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | dict1 = { 'Alexandra' : 27, # given the first dictionary in key-value pairs 18 | 'Shelina Gomez' : 22, 19 | 'James' : 29, 20 | 'Peterson' : 30 21 | } 22 | dict2 = { 23 | 'Jasmine' : 19, # given the second dictionary in key-value pairs 24 | 'Maria' : 26, 25 | 'Helena' : 30 26 | } 27 | print("Before merging the two dictionary ") 28 | print("Dictionary No. 1 is : ", dict1) # print the dict1 29 | print("Dictionary No. 1 is : ", dict2) # print the dict2 30 | 31 | dict3 = dict1.copy() # Copy the dict1 into the dict3 using copy() method 32 | 33 | for key, value in dict2.items(): # use for loop to iterate dict2 into the dict3 dictionary 34 | dict3[key] = value 35 | 36 | print("After merging of the two Dictionary ") 37 | print(dict3) # print the merge dictionary 38 | -------------------------------------------------------------------------------- /Python3-Learn/magic_number-sumitbro.py: -------------------------------------------------------------------------------- 1 | # Python3-Learn 2 | 3 | // AUTHOR: Sumit Sah 4 | // Python3 Concept: Check Magic number 5 | // GITHUB: https://github.com/sumitbro 6 | 7 | # Magic number concept 8 | #A magic number is that number whose repeated sum of its digits till we get a single digit is equal to 1. 9 | 10 | # Example: 11 | 12 | # original number= 1729 13 | # sum of digits= 1+7+2+9=19 14 | # 1+9=10 15 | # 1+0=1 16 | # 1729 is magic number 17 | 18 | #code 19 | 20 | import math 21 | 22 | num = int(input("Enter a Number \n")) 23 | digitCount = int(math.log10(num))+1 24 | sumOfDigits = 0 25 | 26 | temp = num #copying num 27 | 28 | #calculating sum of digits of temp(i.e num) until 29 | #sumOfDigits is a single digit 30 | while( digitCount > 1): 31 | 32 | sumOfDigits = 0 33 | 34 | while(temp > 0): 35 | sumOfDigits += temp%10 36 | temp = temp//10 37 | 38 | temp = sumOfDigits 39 | #count the digits of sumOfDigits 40 | digitCount = int(math.log10(sumOfDigits))+1 41 | 42 | 43 | #check whether sumOfDigits == 1 44 | if(sumOfDigits == 1): 45 | print("Magic number") 46 | else: 47 | print("Not a magic number") -------------------------------------------------------------------------------- /Python3-Learn/dnd-dice-roller/diceroll_SoWrongImRight.py: -------------------------------------------------------------------------------- 1 | """ 2 | // AUTHOR: Russ Carroll 3 | // Python3 Concept: Take die type and quantity arguments from user and then simulate those dice rolls and providing the results 4 | // GITHUB: your github profile link 5 | 6 | //Add your python3 concept below 7 | 8 | The purpose of this program is to roll a quantity number of die type dice and provide the user with the results""" 9 | import random 10 | 11 | die = input("What die type (default is d6): ") or "d6" 12 | quantity = input("How many (default is 1): ") or 1 13 | quantity = int(quantity) 14 | total = 0 15 | 16 | #There is probably a more eliegant way to do this but I don't know how 17 | if die == "d4": 18 | sides = 4 19 | elif die == "d6": 20 | sides = 6 21 | elif die == "d10": 22 | sides = 10 23 | elif die == "d12": 24 | sides = 12 25 | elif die == "d20": 26 | sides = 20 27 | elif die == "d100": 28 | sides = 100 29 | else: 30 | print("That is not a die type") 31 | 32 | for i in range(0, quantity): 33 | result = (random.randint(1, sides)) 34 | print(i+1, die, " = ", result) 35 | total += result 36 | print("This is the result of your roll: ", total) 37 | -------------------------------------------------------------------------------- /Python3-Learn/sort_012_array_edusanketdk.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Sanket Khadse 2 | # Python3 Concept: Given an array which consists of only 0, 1 and 2. Sort the array without using any sorting algo 3 | # Github: https://www.github.com/edusanketdk 4 | 5 | def sol_1(ar: list) -> list: 6 | """using count (not inplace)""" 7 | return [0]*ar.count(0) + [1]*ar.count(1) + [2]*ar.count(2) 8 | 9 | 10 | def sol_2(ar: list) -> list: 11 | """using count (inplace)""" 12 | cnt = [0, 0, 0] 13 | for i in ar: 14 | cnt[i] += 1 15 | 16 | for i in range(len(ar)): 17 | if cnt[0]: 18 | ar[i] = 0 19 | elif cnt[1]: 20 | ar[i] = 1 21 | else: 22 | ar[i] = 2 23 | 24 | cnt[ar[i]] -= 1 25 | 26 | return ar 27 | 28 | 29 | def sol_3(ar: list) -> list: 30 | """using three pointers""" 31 | i, l, h = 0, 0, n-1 32 | 33 | while i <= h: 34 | if arr[i] == 0: 35 | arr[i], arr[l] = arr[l], arr[i] 36 | l += 1 37 | i += 1 38 | elif arr[i] == 1: 39 | i += 1 40 | else: 41 | arr[i], arr[h] = arr[h], arr[i] 42 | h -= 1 43 | 44 | return arr -------------------------------------------------------------------------------- /Python3-Learn/movie_flight_CharalambosIoannou.py: -------------------------------------------------------------------------------- 1 | #AUTHOR: Charalambos Ioannou 2 | #Python3 Concept: 3 | """ 4 | You are on a flight and wanna watch two movies during this flight. 5 | You are given List movieDurations which includes all the movie durations. 6 | You are also given the duration of the flight which is k in minutes. 7 | Now, you need to pick two movies and the total duration of the two movies is less than or equal to (k - 30min). 8 | 9 | Find the pair of movies with the longest total duration and return they indexes. If multiple found, return the pair with the longest movie. 10 | """ 11 | 12 | #GITHUB: https://github.com/CharalambosIoannou 13 | 14 | # Function 15 | def flightDetails(arr, k): 16 | k-=30 17 | arr = sorted(arr) 18 | left = 0 19 | right = len(arr)-1 20 | max_val = 0 21 | while lefta): 16 | print("\n less") 17 | elif(guess==a): 18 | print("\nWIn") 19 | i+=1 20 | elif(level == 2): 21 | for y in range (0,3): 22 | a= random.randint(0,20) 23 | guess = int(input("\nEnter the no")) 24 | if(guessa): 27 | print("\n less") 28 | elif(guess==a): 29 | print("\n WIn") 30 | y+=1 31 | elif(level == 3): 32 | for k in range (0,3): 33 | a= random.randint(0,30) 34 | guess = int(input("\n Enter the no")) 35 | if(guessa): 38 | print("\n less") 39 | elif(guess==a): print("\n WIn") 40 | k+=1 41 | else: quit() 42 | -------------------------------------------------------------------------------- /Python3-Learn/working-with-images_Harshil333.py: -------------------------------------------------------------------------------- 1 | ''' 2 | // AUTHOR: Harshil Doshi 3 | // Python3 Concept: Working with Images in Python 4 | // GITHUB: https://github.com/Harshil333 5 | ''' 6 | 7 | # PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. 8 | # We’ll be working with Pillow which is a user-friendly PIL fork. 9 | 10 | # Installation: pip install Pillow 11 | 12 | # We can perform various tasks on the image using Pillow such as: 13 | 14 | # Retreiving size of the image: 15 | from PIL import Image 16 | 17 | filename = "image.png" 18 | with Image.open(filename) as image: 19 | #Image.size gives a 2-tuple and the width, height can be obtained 20 | width, height = image.size 21 | 22 | 23 | # Rotating an image: 24 | from PIL import Image 25 | 26 | #Relative Path 27 | img = Image.open("picture.jpg") 28 | #Angle given 29 | img = img.rotate(180) 30 | #Saved in the same relative location 31 | img.save("rotated_picture.jpg") 32 | 33 | 34 | #Cropping an image: 35 | from PIL import Image 36 | 37 | #Relative Path 38 | img = Image.open("picture.jpg") 39 | width, height = img.size 40 | 41 | area = (0, 0, width/2, height/2) 42 | img = img.crop(area) 43 | 44 | #Saved in the same relative location 45 | img.save("cropped_picture.jpg") -------------------------------------------------------------------------------- /Python3-Learn/sms-bomber.py: -------------------------------------------------------------------------------- 1 | from selenium import webdriver 2 | 3 | option= webdriver.ChromeOptions() 4 | option.binary_location= r'C:\\Program Files (x86)\\Google\Chrome\\Application\\chrome.exe' 5 | driver= webdriver.Chrome(executable_path='D:\\Softwares\\chromedriver.exe', chrome_options=option) 6 | 7 | driver.get('https://www.amazon.in/ap/signin?_encoding=UTF8&openid.assoc_handle=inflex&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.mode=checkid_setup&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.ns.pape=http%3A%2F%2Fspecs.openid.net%2Fextensions%2Fpape%2F1.0&openid.pape.max_auth_age=0&openid.return_to=https%3A%2F%2Fwww.amazon.in%2Fgp%2Fyourstore%2Fhome%3Fie%3DUTF8%26action%3Dsign-out%26path%3D%252Fgp%252Fyourstore%252Fhome%26ref_%3Dnav_AccountFlyout_signout%26signIn%3D1%26useRedirectOnSuccess%3D1') 8 | 9 | phone_no= input("Enter the phone number to blast") 10 | times= input("How many times to send OTP") 11 | 12 | driver.find_element_by_id('ap_email').send_keys("+91" + phone_no) 13 | driver.find_element_by_id('continue').click() 14 | driver.find_element_by_id('continue').click() 15 | 16 | for i in range(int(times)): 17 | driver.find_element_by_link_text('Resend OTP').click() 18 | 19 | -------------------------------------------------------------------------------- /Python3-Learn/some modules/texttospeech_avyayjain.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Avyay Jain 2 | // Python3 Concept: (calculator) 3 | // GITHUB: https://github.com/avyayjain 4 | 5 | import pyttsx3 6 | engine = pyttsx3.init() # object creation 7 | 8 | """ RATE""" 9 | engine.setProperty('rate', 125) # setting up new voice rate 10 | rate = engine.getProperty('rate') # getting details of current speaking rate 11 | print (rate) #printing current voice rate 12 | 13 | """VOLUME""" 14 | volume = engine.getProperty('volume') #getting to know current volume level (min=0 and max=1) 15 | print (volume) #printing current volume level 16 | engine.setProperty('volume',1.0) # setting up volume level between 0 and 1 17 | 18 | """VOICE""" 19 | voices = engine.getProperty('voices') #getting details of current voice 20 | #engine.setProperty('voice', voices[0].id) #changing index, changes voices. o for male 21 | engine.setProperty('voice', voices[1].id) #changing index, changes voices. 1 for female 22 | 23 | engine.say("Hello World!") 24 | engine.say('My current speaking rate is ' + str(rate)) 25 | engine.runAndWait() 26 | engine.stop() 27 | 28 | """Saving Voice to a file""" 29 | # On linux make sure that 'espeak' and 'ffmpeg' are installed 30 | engine.save_to_file('Hello World', 'test.mp3') 31 | engine.runAndWait() 32 | -------------------------------------------------------------------------------- /Python3-Learn/first_last_position_edusanketdk.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Sanket Khadse 2 | # Python3 Concept: Find first and last positions of an element in a sorted array 3 | # GITHUB: https://github.com/edusanketdk 4 | 5 | 6 | def sol_1(ar: list, x: int) -> tuple: 7 | """using index function""" 8 | return (ar.index(x), len(ar)-ar[::-1].index(x)-1) if x in ar else (-1, -1) 9 | 10 | 11 | def sol_2(ar: list, x: int) -> tuple: 12 | """using single traversal""" 13 | f, l = -1, -1 14 | 15 | for i in range(len(ar)): 16 | if ar[i] == x: 17 | if f == -1: f = i 18 | l = i 19 | 20 | return (f, l) 21 | 22 | 23 | def sol_3(ar: list, x: int) -> list: 24 | """using binary search""" 25 | ans = [-1, -1] 26 | 27 | l, r = 0, n-1 28 | while l <= r: 29 | m = l + (r-l)//2 30 | if ar[m] == x and (m == 0 or ar[m-1] < x): 31 | ans[0] = m 32 | break 33 | elif ar[m] < x: 34 | l, r = m+1, r 35 | else: 36 | l, r = l, m-1 37 | 38 | l, r = 0, n-1 39 | while l <= r: 40 | m = l + (r-l)//2 41 | if ar[m] == x and (m == n-1 or ar[(m+1)%n] > x): 42 | ans[1] = m 43 | break 44 | elif ar[m] > x: 45 | l, r = l, m-1 46 | else: 47 | l, r = m+1, r 48 | 49 | return ans 50 | -------------------------------------------------------------------------------- /Python3-Learn/rock_paper_scissors.py: -------------------------------------------------------------------------------- 1 | //Author : Arayan Gupta 2 | //Python concept : Rock Paper Scissors 3 | //Github : https://github.com/Arayan1906 4 | import random 5 | #initiating the values 6 | userWins=0 7 | compWins=0 8 | draw=0 9 | 10 | #defining the while loop 11 | while userWins<3 and compWins<3: 12 | #keep taking the inputs from the user 13 | user=eval(input("scissor(0), rock(1), paper(2):")) 14 | comp=random.randint(0,2) 15 | 16 | #Conversion of the number into a string 17 | if user==0: 18 | u="scissor" 19 | elif user==1: 20 | u="rock" 21 | else: 22 | u="paper" 23 | 24 | #Conversions for the computer 25 | if comp==0: 26 | c="scissor" 27 | elif user==1: 28 | c="rock" 29 | else: 30 | c="paper" 31 | 32 | #choosing the winners 33 | if user==(comp+1)%3: 34 | print("The computer is " +c+" You are "+u+". You won! Congrats!.\n") 35 | userWins+=1 36 | elif user==(comp-1)%3: 37 | print("The computer is " +c+" You are "+u+". You lose... Computer won!.\n") 38 | compWins+=1 39 | else: 40 | print("The match has drawed... Both you and the computer are "+u+".Better try again.\n") 41 | draw+=1 42 | totalGames=userWins+compWins+draw 43 | print("Game Ended..... You won ",userWins," times out of ",totalGames) 44 | -------------------------------------------------------------------------------- /Python3-Learn/Heap_Sort_Algorithm_MMVonnSeek.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Max Müller 2 | # Python3 Concept: Heap Sort Algorithm 3 | # GITHUB: https://github.com/MMVonnSeek 4 | 5 | # heapify tree rooted at index i 6 | 7 | def heapify(arr, n, i): 8 | largest = i # In max-heap largest is at root 9 | l = 2 * i + 1 # left child index = 2*i + 1 10 | r = 2 * i + 2 # right child index = 2*i + 2 11 | 12 | # See if left child of root exists and > root 13 | if l < n and arr[i] < arr[l]: 14 | largest = l 15 | 16 | # See if right child of root exists and > root 17 | if r < n and arr[largest] < arr[r]: 18 | largest = r 19 | 20 | # update root if required 21 | if largest != i: 22 | arr[i],arr[largest] = arr[largest],arr[i] # swap 23 | 24 | # Heapify the root 25 | heapify(arr, n, largest) 26 | 27 | 28 | # heap sort definition 29 | def heapSort(arr): 30 | n = len(arr) 31 | 32 | for i in range(n // 2 - 1, -1, -1): 33 | heapify(arr, n, i) 34 | 35 | # extracting elements 36 | for i in range(n-1, 0, -1): 37 | arr[i], arr[0] = arr[0], arr[i] # swap 38 | heapify(arr, i, 0) 39 | 40 | 41 | arr = [ 12, 11, 13, 5, 6, 7] 42 | heapSort(arr) 43 | n = len(arr) 44 | print ("Sorted array is") 45 | for i in range(n): 46 | print ("%d" %arr[i]) 47 | -------------------------------------------------------------------------------- /Python3-Learn/Stonepaperscissorsgame_varsha080.py: -------------------------------------------------------------------------------- 1 | #Author:Varsha Gupta 2 | #Python3 concept: Stone paper scissors game using python 3 | #GITHUB: https://github.com/varsha080 4 | 5 | 6 | 7 | import random 8 | b='y' 9 | 10 | while(b=='y'): 11 | def gamewin(comp,you): 12 | if comp==you: 13 | return None 14 | elif comp== 'st': 15 | if you== 'p': 16 | return True 17 | else: 18 | return False 19 | elif comp== 'p': 20 | if you== 'sc': 21 | return True 22 | else: 23 | return False 24 | else: 25 | if you== 'st': 26 | return True 27 | else: 28 | return False 29 | 30 | 31 | print("Computer's turn: Stone(st), Paper(p), Scissor(sc)") 32 | randon=random.randint(1,3) 33 | if randon==1: 34 | comp='st' 35 | elif randon==2: 36 | comp='p' 37 | else: 38 | comp='sc' 39 | 40 | 41 | you = input("Your Turn: Stone(st), Paper(p), Scissor(sc)") 42 | 43 | print("Computer chose: " +comp) 44 | print("You chose: "+you) 45 | 46 | a=gamewin(comp,you) 47 | 48 | if a==None: 49 | print("Match is draw!!:)") 50 | elif a==True: 51 | print("Hurray!! You win!!:D") 52 | else: 53 | print("Alas!You lose:(") 54 | 55 | b=input("Do you want to play again(y/n)") 56 | if(b=='n'): 57 | print("Thanks for playing :D") 58 | 'break' 59 | 60 | -------------------------------------------------------------------------------- /Python3-Learn/some modules/playmusic_avyayjain.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Avyay Jain 2 | // Python3 Concept: (calculator) 3 | // GITHUB: https://github.com/avyayjain 4 | 5 | import pyttsx3 6 | import speech_recognition as sr 7 | import pywhatkit 8 | 9 | engine = pyttsx3.init() 10 | 11 | def speech(audio): 12 | engine.say(audio) 13 | voices = engine.getProperty('voices') #getting details of current voice 14 | #engine.setProperty('voice', voices[0].id) #changing index, changes voices. o for male 15 | engine.setProperty('voice', voices[1].id) 16 | engine.runAndWait() 17 | 18 | def takeCommand(): 19 | #It takes microphone input from the user and returns string output 20 | 21 | r = sr.Recognizer() 22 | with sr.Microphone() as source: 23 | print() 24 | print("Listening...") 25 | print() 26 | #r.pause_threshold = 1 27 | audio = r.listen(source) 28 | 29 | try: 30 | print("Recognizing...") 31 | print() 32 | query = r.recognize_google(audio, language='en-in') 33 | print(f"User said: {query}\n") 34 | 35 | except Exception as e: 36 | print("Say that again please...") 37 | print() 38 | return "None" 39 | return query 40 | 41 | speech("what would you like to play ") 42 | song = takeCommand() 43 | speech('playing '+song) 44 | 45 | pywhatkit.playonyt(song) 46 | 47 | -------------------------------------------------------------------------------- /Python3-Learn/control-structures_InfernapeXavier.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: InfernapeXavier 2 | # Python3 Concept: Python Control Structures 3 | # GITHUB: https://github.com/InfernapeXavier 4 | 5 | 6 | #Change the number and check the outputs 7 | number = 5 8 | 9 | # If-Else 10 | if number <= 5: 11 | print ("Less than or equal to 5") 12 | else: 13 | print ("Greater than 5") 14 | 15 | 16 | # If-Elif-Else 17 | if number < 5: 18 | print ("Less than 5") 19 | elif number == 5: 20 | print ("Equal to 5") 21 | else: 22 | print ("Greater than 5") 23 | 24 | # For Loop 25 | 26 | # Variant 1: When you have a range 27 | 28 | for i in range(0, 5): 29 | print (i, end="") 30 | print() 31 | 32 | for i in range(0,5,2): #Step value of 2 33 | print (i, end="") 34 | print() 35 | 36 | for i in range(5, 0, -1): #Negative step value 37 | print (i, end="") 38 | print() 39 | 40 | # Variant 2: When you have a data structure to iterate through 41 | nums = [1,2,3,4,5,6,7,8] 42 | 43 | for num in nums: 44 | print (num, end="") 45 | print() 46 | 47 | # Variant 3: For-Else - The else block is executed when the for loop isn't entered 48 | 49 | for i in range(1, 5): 50 | print (i, end="") 51 | else: 52 | print ("\nExited the for loop") 53 | 54 | 55 | # While Loop 56 | 57 | i = 5 58 | 59 | while i > 0: 60 | print (i, end="") 61 | i -= 1 62 | else: 63 | print ("\nExited while loop") 64 | -------------------------------------------------------------------------------- /Python3-Learn/Searching/Binary_Search.py: -------------------------------------------------------------------------------- 1 | ''' Algorithm for Binary Search 2 | Step-1:Compare x with the middle element. 3 | Step-2:If x matches with middle element, we return the mid index. 4 | Step-3:Else If x is greater than the mid element, then x can only lie in right half subarray after the mid element. So we recur for right half. 5 | Step-4:Else (x is smaller) recur for the left half.''' 6 | def binarySearch (arr, l, r, x): 7 | 8 | # Check base case 9 | if r >= l: 10 | 11 | mid = l + (r - l) // 2 12 | 13 | # If element is present at the middle itself 14 | if arr[mid] == x: 15 | return mid 16 | 17 | # If element is smaller than mid, then it 18 | # can only be present in left subarray 19 | elif arr[mid] > x: 20 | return binarySearch(arr, l, mid-1, x) 21 | 22 | # Else the element can only be present 23 | # in right subarray 24 | else: 25 | return binarySearch(arr, mid + 1, r, x) 26 | 27 | else: 28 | # Element is not present in the array 29 | return -1 30 | 31 | # Driver Code 32 | arr = [ 2, 3, 4, 10, 40 ] 33 | x = 10 34 | 35 | # Function call 36 | result = binarySearch(arr, 0, len(arr)-1, x) 37 | 38 | if result != -1: 39 | print ("Element is present at index % d" % result) 40 | else: 41 | print ("Element is not present in array") 42 | -------------------------------------------------------------------------------- /Python3-Learn/Longest_Common_Prefix_Yakuta110.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | ''' 4 | AUTHOR: Yakuta Vajihee 5 | Python3 Concept:Longest common prefix string in Python 6 | GITHUB: https://github.com/Yakuta110 7 | 8 | 9 | 10 | Write a function to find the longest common prefix string amongst an array of strings. 11 | If there is no common prefix, return an empty string "". 12 | Example 1: 13 | Input: ["flower","flow","flight"] 14 | Output: "fl" 15 | 16 | 17 | ''' 18 | 19 | class Solution(object): 20 | def longestCommonPrefix(self, strs): 21 | """ 22 | :type strs: List[str] 23 | :rtype: str 24 | """ 25 | def prefix(strs, index): 26 | check_prefix = strs[0][:index] 27 | for index in range(1, len(strs)): 28 | if not strs[index].startswith(check_prefix): 29 | return False 30 | return True 31 | 32 | 33 | if not strs: 34 | return "" 35 | 36 | minLength = float('inf') 37 | for string in strs: 38 | minLength = min(minLength, len(string)) 39 | 40 | low, high = 0, minLength 41 | 42 | while low <= high: 43 | mid = (low+high)/2 44 | if (prefix(strs, mid)): 45 | low = mid + 1 46 | else: 47 | high = mid - 1 48 | 49 | return strs[0][:(low+high)/2] -------------------------------------------------------------------------------- /Python3-Learn/python3-quicksort-dwiputrias.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: DWI PUTRI A S 2 | # Python3 Concept: Sorting -- > Quick Sort 3 | # GITHUB: https://github.com/dwiputrias 4 | 5 | #function that consider last element as pivot, place the pivot at its exact position, and place smaller elements to left of pivot and greater elements to right of pivot. 6 | def partition (a, start, end): 7 | i = (start - 1) 8 | pivot = a[end] # pivot element 9 | 10 | for j in range(start, end): 11 | # If current element is smaller than or equal to the pivot 12 | if (a[j] <= pivot): 13 | i = i + 1 14 | a[i], a[j] = a[j], a[i] 15 | 16 | a[i+1], a[end] = a[end], a[i+1] 17 | 18 | return (i + 1) 19 | 20 | # function to implement quick sort 21 | def quick(a, start, end): # a[] = array to be sorted, start = Starting index, end = Ending index 22 | if (start < end): 23 | p = partition(a, start, end) # p is partitioning index 24 | quick(a, start, p - 1) 25 | quick(a, p + 1, end) 26 | 27 | 28 | def printArr(a): # function to print the array 29 | for i in range(len(a)): 30 | print (a[i], end = " ") 31 | 32 | 33 | a = [68, 88, 32, 43, 1, 55, 77] 34 | print("Before sorting array elements are - ") 35 | printArr(a) 36 | quick(a, 0, len(a)-1) 37 | print("\nAfter sorting array elements are - ") 38 | printArr(a) 39 | -------------------------------------------------------------------------------- /Python3-Learn/Rock_paper_scissor_mayankgoyal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : Rock Paper Scissor Game 3 | Author : [Mayank Goyal) [https://github.com/mayankgoyal-13] 4 | """ 5 | 6 | import random 7 | 8 | def validate(hand): 9 | if hand < 0 or hand > 2: 10 | return False 11 | return True 12 | 13 | def print_hand(hand, name='Guest'): 14 | hands = ['Rock', 'Paper', 'Scissors'] 15 | print(name + ' picked: ' + hands[hand]) 16 | 17 | def judge(player, computer): 18 | # comparison of player and computer 19 | if player == computer: 20 | return 'Draw' 21 | elif player == 0 and computer == 1: 22 | return 'Lose' 23 | elif player == 1 and computer == 2: 24 | return 'Lose' 25 | elif player == 2 and computer == 0: 26 | return 'Lose' 27 | else: 28 | return 'Win' 29 | 30 | print('Starting the Rock Paper Scissors game!') 31 | player_name = input('Please enter your name: ') 32 | print('Pick a hand: (0: Rock, 1: Paper, 2: Scissors)') 33 | player_hand = int(input('Please enter a number (0-2): ')) 34 | 35 | if validate(player_hand): 36 | # the computer chooses a random value and each value is assigned to a hand 37 | computer_hand = random.randint(0, 2) 38 | print_hand(player_hand, player_name) 39 | print_hand(computer_hand, 'Computer') 40 | result = judge(player_hand, computer_hand) # judge function is called 41 | print('Result: ' + result) 42 | else: 43 | print('You entered an invalid option') 44 | -------------------------------------------------------------------------------- /Python3-Learn/Itertools.py: -------------------------------------------------------------------------------- 1 | #AUTHOR: Ankita Mandal 2 | #Python3 Concept: Python Lambda 3 | #GITHUB: https://github.com/GoGi2712 4 | 5 | from itertools import * 6 | 7 | # Easy joining of two lists into a list of tuples 8 | for i in izip([1, 2, 3], ['a', 'b', 'c']): 9 | print i 10 | # ('a', 1) 11 | # ('b', 2) 12 | # ('c', 3) 13 | 14 | # The count() function returns an interator that 15 | # produces consecutive integers, forever. This 16 | # one is great for adding indices next to your list 17 | # elements for readability and convenience 18 | for i in izip(count(1), ['Bob', 'Emily', 'Joe']): 19 | print i 20 | # (1, 'Bob') 21 | # (2, 'Emily') 22 | # (3, 'Joe') 23 | 24 | # The dropwhile() function returns an iterator that returns 25 | # all the elements of the input which come after a certain 26 | # condition becomes false for the first time. 27 | def check_for_drop(x): 28 | print 'Checking: ', x 29 | return (x > 5) 30 | 31 | for i in dropwhile(should_drop, [2, 4, 6, 8, 10, 12]): 32 | print 'Result: ', i 33 | 34 | # Checking: 2 35 | # Checking: 4 36 | # Result: 6 37 | # Result: 8 38 | # Result: 10 39 | # Result: 12 40 | 41 | 42 | # The groupby() function is great for retrieving bunches 43 | # of iterator elements which are the same or have similar 44 | # properties 45 | 46 | a = sorted([1, 2, 1, 3, 2, 1, 2, 3, 4, 5]) 47 | for key, value in groupby(a): 48 | print(key, value), end=' ') 49 | 50 | # (1, [1, 1, 1]) 51 | # (2, [2, 2, 2]) 52 | # (3, [3, 3]) 53 | # (4, [4]) 54 | # (5, [5]) -------------------------------------------------------------------------------- /Python3-Learn/password_generator_Princekumaraj.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Prince Kumar Raj 2 | // Python3 Concept: using libraries like tkinter, random , pyperclip 3 | // GITHUB: https://github.com/Princekumaraj 4 | 5 | from tkinter import * 6 | import random, string 7 | import pyperclip 8 | 9 | root= Tk() 10 | root.geometry("400x400") 11 | root.resizable(0,0) 12 | root.title("Prototype - Password Generator") 13 | Label(root, text= 'PASSWORD GENERATOR', font ='arial 16 bold').pack() 14 | Label(root, text ='Prototype', font ='arial 16 bold').pack(side= BOTTOM) 15 | 16 | 17 | pass_label = Label(root, text = 'PASSWORD LENGTH', font ='arial 11 bold').pack() 18 | pass_len = IntVar() 19 | length = Spinbox(root, from_ = 8, to_ = 32, textvariable= pass_len, width =15).pack() 20 | 21 | pass_str = StringVar() 22 | def Generator(): 23 | password = '' 24 | 25 | for x in range(0,4): 26 | password = random.choice(string.ascii_uppercase) + random.choice(string.ascii_lowercase) + random.choice(string.digits) + random.choice 27 | for y in range(pass_len.get()- 4): 28 | password = password + random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits + string.punctuation) 29 | pass_str.set(password) 30 | 31 | 32 | Button(root, text = "GENERATE PASSWORD", command = Generator).pack(pady= 5) 33 | Entry(root , textvariable= pass_str).pack() 34 | 35 | def Copy_password(): 36 | pyperclip.copy(pass_str.get()) 37 | 38 | Button(root, text = 'COPY TO CLIPBOARD', command = Copy_password).pack(pady=5) 39 | 40 | -------------------------------------------------------------------------------- /Python3-Learn/snake.py: -------------------------------------------------------------------------------- 1 | //Author : Arayan Gupta 2 | //Python Concept : Snake game 3 | //Github : https://github.com/Arayan1906 4 | from turtle import * 5 | import turtle 6 | from random import randrange 7 | from freegames import square, vector 8 | 9 | turtle.bgcolor("black") 10 | food = vector(0, 0) 11 | snake = [vector(10, 0)] 12 | aim = vector(0, -10) 13 | 14 | def change(x, y): 15 | "Change snake direction." 16 | aim.x = x 17 | aim.y = y 18 | 19 | def inside(head): 20 | "Return True if head inside boundaries." 21 | return -250 < head.x < 230 and -250 < head.y < 230 22 | 23 | def move(): 24 | "Move snake forward one segment." 25 | head = snake[-1].copy() 26 | head.move(aim) 27 | 28 | if not inside(head) or head in snake: 29 | square(head.x, head.y, 9, 'red') 30 | update() 31 | return 32 | 33 | snake.append(head) 34 | 35 | if head == food: 36 | print('Snake:', len(snake)) 37 | food.x = randrange(-15, 15) * 10 38 | food.y = randrange(-15, 15) * 10 39 | else: 40 | snake.pop(0) 41 | 42 | clear() 43 | 44 | for body in snake: 45 | square(body.x, body.y, 9, 'green') 46 | 47 | square(food.x, food.y, 9, 'red') 48 | update() 49 | ontimer(move, 100) 50 | 51 | 52 | hideturtle() 53 | tracer(False) 54 | listen() 55 | onkey(lambda: change(10, 0), 'Right') 56 | onkey(lambda: change(-10, 0), 'Left') 57 | onkey(lambda: change(0, 10), 'Up') 58 | onkey(lambda: change(0, -10), 'Down') 59 | move() 60 | done() 61 | -------------------------------------------------------------------------------- /Python3-Learn/ATM_krosskid12.py: -------------------------------------------------------------------------------- 1 | #AUTHOR: Farrah Akram 2 | #Python3 Concept: Simple ATM in Python 3 | #GITHUB: https://github.com/krosskid12 4 | while True: 5 | balance=10000; 6 | print(" <<-- Welcome to Github ATM -->> ") 7 | print(""" 8 | 1) Balance Check 9 | 2) Withdraw Balance 10 | 3) Deposit 11 | 4) Quit 12 | """) 13 | 14 | try: 15 | Option=int(input("Enter Option :")) 16 | 17 | except Exception as e: 18 | print("Error:",e) 19 | print("Enter 1,2,3 or 4 only") 20 | continue 21 | 22 | if Option==1: 23 | print("Balance $ ",balance) 24 | 25 | if Option==2: 26 | print("Balance $ ",balance) 27 | Withdraw=float(input("Enter Withdraw ammount $ :")) 28 | 29 | if Withdraw>0: 30 | forwardbalance=(balance-Withdraw) 31 | print("Forward balance is $ ",forwardbalance) 32 | 33 | elif Withdraw>balance: 34 | print("No Balance in account !!!") 35 | 36 | else: 37 | print("None withdraw made ") 38 | 39 | if Option==3: 40 | print("Balance $ ",balance) 41 | Deposit=float(input("Enter deposit ammount $ :")) 42 | 43 | if Deposit>0: 44 | forwardbalance=(balance+Deposit) 45 | print("forwardbalance $",forwardbalance) 46 | 47 | else: 48 | print("No deposit made !!!") 49 | 50 | if Option==4: 51 | exit() 52 | -------------------------------------------------------------------------------- /Python3-Learn/Queue_Ananya2003Gupta.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Ananya 2 | // Python3 Concept: Queue 3 | // GITHUB: https://github.com/Ananya2003Gupta 4 | 5 | lim=100 6 | s=[] 7 | def enqueue(s): 8 | global lim 9 | n=int(input("Enter the value:")) 10 | l=len(s) 11 | if l==lim: 12 | print("Overflow") 13 | else: 14 | s.append(n) 15 | print("Number added in queue") 16 | 17 | def dequeue(s): 18 | if len(s)==0: 19 | print("Underflow") 20 | else: 21 | a=s.pop(0) 22 | print("Deleted {} from queue".format(a)) 23 | 24 | def queuelim(): 25 | global lim 26 | lim=int(input("Enter the queue limit")) 27 | print("Limit set as",lim) 28 | 29 | def view(s): 30 | for i in range(len(s)): 31 | print(s[i]) 32 | 33 | def frontandrear(s): 34 | if len(s)==0: 35 | print("Queue is empty") 36 | else: 37 | print("Front element is",s[0]) 38 | print("Rear element is",s[len(s)-1]) 39 | 40 | def main(): 41 | c=1 42 | while c!=0: 43 | print("""Menu 44 | 1.Add elements in queue 45 | 2.Delete elements from queue 46 | 3.Set queue limit(By default queue limit is 100) 47 | 4.View queue 48 | 5.View Front and Rear elements of queue 49 | 6.Exit""") 50 | a=int(input("Enter your choice:")) 51 | if a==1: 52 | enqueue(s) 53 | elif a==2: 54 | dequeue(s) 55 | elif a==3: 56 | queuelim() 57 | elif a==4: 58 | view(s) 59 | elif a==5: 60 | frontandrear(s) 61 | elif a==6: 62 | c=0 63 | else: 64 | print("Invalid Input") 65 | main() 66 | -------------------------------------------------------------------------------- /Python3-Learn/python3-InverseBurrowWheeler_DeepthiSudharsan.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Deepthi Sudharsan 2 | # Python3 Concept: Burrow Wheeler and Inverse Burrow Wheeler 3 | # GITHUB: https://github.com/DeepthiSudharsan 4 | 5 | def BWT(input): 6 | assert "$" not in input 7 | input = input + "$" 8 | rottable = [input[i:] + input[:i] for i in range(len(input))] # Table of rotations of the sequence 9 | print("Rotation table ",rottable) 10 | sorttable = sorted(rottable) # sortted rotation table 11 | print("Sorted table ",sorttable) 12 | lcol = [row[-1:] for row in sorttable] 13 | bwt = ''.join(lcol) 14 | print(" Burrow Wheeler Transform ",bwt) 15 | print("===============================================================================================================") 16 | IBWT(bwt) 17 | 18 | def IBWT(bwt): 19 | invtable = [""] * len(bwt) # creating empty table 20 | for i in range(len(bwt)): 21 | invtable = [bwt[i] + invtable[i] for i in range(len(bwt))] 22 | print("Unsorted table : ",invtable) 23 | invtable = sorted(invtable) 24 | print("Sorted table : ",invtable) 25 | print() 26 | ibwt = [row for row in invtable if row.endswith("$")][0] # Finding the correct row i.e., row ending with $ 27 | ibwt = ibwt.rstrip("$") # Getting rid of the start and end marker $ 28 | print(" Inverse Burrow Wheeler Transform ",ibwt) 29 | 30 | print("Example Sequence 1 : TTGGAAGA") 31 | print(BWT('TTGGAAGA')) 32 | print("Example Sequence 2 : TGGACAAG") 33 | print(BWT('TGGACAAG')) 34 | print("Example Sequence 3 : TTCTTTTT") 35 | print(BWT('TTCTTTTT')) 36 | print("Example Sequence 4 : AGAACCTG") 37 | print(BWT('AGAACCTG')) 38 | -------------------------------------------------------------------------------- /Python3-Learn/mergeSort_rbb-99.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Rutuja Bhure 2 | # Python3 Concept: merge sort in python 3 | # GITHUB: https://github.com/rbb-99 4 | 5 | ''' 6 | Task : Given an array, sort it in ascending order using merge sort algorithm. 7 | 8 | # Time Complexity : O(n*log n) 9 | # Space Complexity : O(n) 10 | ''' 11 | 12 | def mergeSort(array): 13 | if len(array) > 1: 14 | 15 | # r is the point where the array is divided into two subarrays 16 | r = len(array)//2 17 | L = array[:r] 18 | M = array[r:] 19 | 20 | # Sort the two halves 21 | mergeSort(L) 22 | mergeSort(M) 23 | 24 | i = j = k = 0 25 | 26 | # Until we reach either end of either L or M, pick larger among 27 | # elements L and M and place them in the correct position at A[p..r] 28 | while i < len(L) and j < len(M): 29 | if L[i] < M[j]: 30 | array[k] = L[i] 31 | i += 1 32 | else: 33 | array[k] = M[j] 34 | j += 1 35 | k += 1 36 | 37 | # When we run out of elements in either L or M, 38 | # pick up the remaining elements and put in A[p..r] 39 | while i < len(L): 40 | array[k] = L[i] 41 | i += 1 42 | k += 1 43 | 44 | while j < len(M): 45 | array[k] = M[j] 46 | j += 1 47 | k += 1 48 | 49 | 50 | # Print the array 51 | def printList(array): 52 | for i in range(len(array)): 53 | print(array[i], end=" ") 54 | print() 55 | 56 | 57 | # Driver program 58 | if __name__ == '__main__': 59 | array = [6, 5, 12, 10, 9, 1] 60 | 61 | mergeSort(array) 62 | 63 | print("Sorted array is: ") 64 | printList(array) 65 | 66 | -------------------------------------------------------------------------------- /Python3-Learn/Majority_Element_Fatema110.py: -------------------------------------------------------------------------------- 1 | """ 2 | AUTHOR: Fatema Vajihee 3 | Python3 Concept: Majority Element in Python 4 | GITHUB: https://github.com/Fatema110 5 | 6 | A majority element in an array A[] of size n is an element that appears more than n/2 times (and hence there is at most one such element). 7 | 8 | Examples : 9 | 10 | Input : {3, 3, 4, 2, 4, 4, 2, 4, 4} 11 | Output : 4 12 | Explanation: The frequency of 4 is 5 which is greater 13 | than the half of the size of the array size. 14 | 15 | """ 16 | 17 | def majorityElement(self, arr, n): 18 | arr.sort() 19 | count = 1 20 | max_ele = -1 21 | temp = arr[0] 22 | flag = 0 23 | 24 | for i in range(1,n): 25 | 26 | if(temp == arr[i]): 27 | count += 1 28 | else: 29 | count = 1 30 | temp = arr[i] 31 | 32 | if(max_ele < count): 33 | 34 | max_ele = count 35 | ele = arr[i] 36 | 37 | if(max_ele > (n//2)): 38 | flag = 1 39 | break 40 | 41 | if(flag == 1): 42 | return ele 43 | elif(len(arr) == 1): 44 | return arr[0] 45 | else: 46 | return -1 47 | 48 | 49 | import math 50 | 51 | from sys import stdin 52 | 53 | 54 | def main(): 55 | 56 | T=int(input()) 57 | while(T>0): 58 | 59 | N=int(input()) 60 | 61 | A=[int(x) for x in input().strip().split()] 62 | 63 | 64 | obj = Solution() 65 | print(obj.majorityElement(A,N)) 66 | 67 | T-=1 68 | 69 | 70 | if __name__ == "__main__": 71 | main() 72 | -------------------------------------------------------------------------------- /Python3-Learn/python3-Stacks-priyanshu-28.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Priyanshu Pathak 2 | # Python3 Concept: Data-Structure -- > Stack 3 | # GITHUB: https://github.com/priyanshu-28 4 | 5 | #Add your python3 concept below 6 | #Stack 7 | #A stack is a linear data structure 8 | 9 | #Access limited to a last-in first-out order. 10 | 11 | #Adding and removing items is restricted to one end known as the top of the stack. 12 | 13 | #An empty stack contains no items. 14 | 15 | #Operations: 16 | #Stack() --> Creates a new empty stack. 17 | #isEmpty() --> Returns a boolean value indicating if the stack is empty. 18 | #length() --> Returns the number of items in the stack. 19 | #pop() --> Removes and returns the top item of the stack 20 | #peek() --> Returns a reference to the item on top of a non-empty stack without removing it. 21 | #push(item) --> Adds the given item to the top of the stack. 22 | 23 | # Implementation of the Stack ADT using a Python list. 24 | class Stack : 25 | 26 | # Creates an empty stack. 27 | def __init__( self ): 28 | self._theItems = list() 29 | 30 | # Returns True if the stack is empty or False otherwise. 31 | def isEmpty( self ): 32 | return len( self ) == 0 33 | 34 | # Returns the number of items in the stack. 35 | def __len__ ( self ): 36 | return len( self._theItems ) 37 | 38 | # Returns the top item on the stack without removing it. 39 | def peek( self ): 40 | assert not self.isEmpty(), "Cannot peek at an empty stack" 41 | return self._theItems[-1] 42 | 43 | # Removes and returns the top item on the stack. 44 | def pop( self ): 45 | assert not self.isEmpty(), "Cannot pop from an empty stack" 46 | return self._theItems.pop() 47 | 48 | # Push an item onto the top of the stack. 49 | def push( self, item ): 50 | self._theItems.append( item ) 51 | -------------------------------------------------------------------------------- /Python3-Learn/BasicArtificialNeuralNetwork_Mgeethabhargava.py: -------------------------------------------------------------------------------- 1 | # AUTHOR: Mandava Geetha Bhargava 2 | # Python3 Concept: Basic Artificial Neural Network using python 3 | # GITHUB: https://github.com/Mgeethabhargava 4 | 5 | #Neural Network code 6 | 7 | 8 | # Use scikit-learn to grid search the batch size and epochs 9 | import numpy 10 | from sklearn.model_selection import GridSearchCV 11 | from keras.models import Sequential 12 | from keras.layers import Dense 13 | from keras.wrappers.scikit_learn import KerasClassifier 14 | # Function to create model, required for KerasClassifier 15 | def create_model(optimizer='adam'): 16 | # create model 17 | model = Sequential() 18 | model.add(Dense(12, input_dim=8, activation='relu')) 19 | model.add(Dense(1, activation='sigmoid')) 20 | # Compile model 21 | model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy']) 22 | return model 23 | # fix random seed for reproducibility 24 | seed = 7 25 | numpy.random.seed(seed) 26 | # load dataset 27 | dataset = numpy.loadtxt("pima-indians-diabetes.csv", delimiter=",") 28 | # split into input (X) and output (Y) variables 29 | X = dataset[:,0:8] 30 | Y = dataset[:,8] 31 | # create model 32 | model = KerasClassifier(build_fn=create_model, epochs=100, batch_size=10, verbose=0) 33 | # define the grid search parameters 34 | optimizer = ['SGD', 'RMSprop', 'Adagrad', 'Adadelta', 'Adam', 'Adamax', 'Nadam'] 35 | param_grid = dict(optimizer=optimizer) 36 | grid = GridSearchCV(estimator=model, param_grid=param_grid, n_jobs=-1, cv=3) 37 | grid_result = grid.fit(X, Y) 38 | # summarize results 39 | print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_)) 40 | means = grid_result.cv_results_['mean_test_score'] 41 | stds = grid_result.cv_results_['std_test_score'] 42 | params = grid_result.cv_results_['params'] 43 | for mean, stdev, param in zip(means, stds, params): 44 | print("%f (%f) with: %r" % (mean, stdev, param)) 45 | -------------------------------------------------------------------------------- /Python3-Learn/Merge sort.py: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | int main(){ 6 | int n; 7 | cin>>n; 8 | while(n--){ 9 | # Python program for implementation of MergeSort 10 | 11 | # Merges two subarrays of arr[]. 12 | # First subarray is arr[l..m] 13 | # Second subarray is arr[m+1..r] 14 | 15 | 16 | def merge(arr, l, m, r): 17 | n1 = m - l + 1 18 | n2 = r - m 19 | 20 | # create temp arrays 21 | L = [0] * (n1) 22 | R = [0] * (n2) 23 | 24 | # Copy data to temp arrays L[] and R[] 25 | for i in range(0, n1): 26 | L[i] = arr[l + i] 27 | 28 | for j in range(0, n2): 29 | R[j] = arr[m + 1 + j] 30 | 31 | # Merge the temp arrays back into arr[l..r] 32 | i = 0 # Initial index of first subarray 33 | j = 0 # Initial index of second subarray 34 | k = l # Initial index of merged subarray 35 | 36 | while i < n1 and j < n2: 37 | if L[i] <= R[j]: 38 | arr[k] = L[i] 39 | i += 1 40 | else: 41 | arr[k] = R[j] 42 | j += 1 43 | k += 1 44 | 45 | # Copy the remaining elements of L[], if there 46 | # are any 47 | while i < n1: 48 | arr[k] = L[i] 49 | i += 1 50 | k += 1 51 | 52 | # Copy the remaining elements of R[], if there 53 | # are any 54 | while j < n2: 55 | arr[k] = R[j] 56 | j += 1 57 | k += 1 58 | 59 | # l is for left index and r is right index of the 60 | # sub-array of arr to be sorted 61 | 62 | 63 | def mergeSort(arr, l, r): 64 | if l < r: 65 | 66 | # Same as (l+r)//2, but avoids overflow for 67 | # large l and h 68 | m = l+(r-l)//2 69 | 70 | # Sort first and second halves 71 | mergeSort(arr, l, m) 72 | mergeSort(arr, m+1, r) 73 | merge(arr, l, m, r) 74 | 75 | 76 | # Driver code to test above 77 | arr = [12, 11, 13, 5, 6, 7] 78 | n = len(arr) 79 | print("Given array is") 80 | for i in range(n): 81 | print("%d" % arr[i]), 82 | 83 | mergeSort(arr, 0, n-1) 84 | print("\n\nSorted array is") 85 | for i in range(n): 86 | print("%d" % arr[i]), 87 | 88 | # This code is contributed by Mohit Kumra 89 | -------------------------------------------------------------------------------- /Python3-Learn/ArrayCode_Pankaj05011998.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Pankaj 2 | // Python3 Concept: Array in python 3 | // GITHUB: https://github.com/Pankaj05011998 4 | 5 | //Add your python3 concept below 6 | # 1) Insertion, deletion and random access of array 7 | # 2) Assumes int for element type 8 | # 9 | # Author: Pankaj 10 | # 11 | 12 | 13 | class MyArray: 14 | """A simple wrapper around List. 15 | You cannot have -1 in the array. 16 | """ 17 | 18 | def __init__(self, capacity: int): 19 | self._data = [] 20 | self._capacity = capacity 21 | 22 | def __getitem__(self, position: int) -> object: 23 | return self._data[position] 24 | 25 | def __setitem__(self, index: int, value: object): 26 | self._data[index] = value 27 | 28 | def __len__(self) -> int: 29 | return len(self._data) 30 | 31 | def __iter__(self): 32 | for item in self._data: 33 | yield item 34 | 35 | def find(self, index: int) -> object: 36 | try: 37 | return self._data[index] 38 | except IndexError: 39 | return None 40 | 41 | def delete(self, index: int) -> bool: 42 | try: 43 | self._data.pop(index) 44 | return True 45 | except IndexError: 46 | return False 47 | 48 | def insert(self, index: int, value: int) -> bool: 49 | if len(self) >= self._capacity: 50 | return False 51 | else: 52 | return self._data.insert(index, value) 53 | 54 | def print_all(self): 55 | for item in self: 56 | print(item) 57 | 58 | 59 | def test_myarray(): 60 | array = MyArray(5) 61 | array.insert(0, 3) 62 | array.insert(0, 4) 63 | array.insert(1, 5) 64 | array.insert(3, 9) 65 | array.insert(3, 10) 66 | assert array.insert(0, 100) is False 67 | assert len(array) == 5 68 | assert array.find(1) == 5 69 | assert array.delete(4) is True 70 | array.print_all() 71 | 72 | 73 | if __name__ == "__main__": 74 | test_myarray() 75 | -------------------------------------------------------------------------------- /Python3-Learn/Linkedlist_ShreyaDayma-cse.py: -------------------------------------------------------------------------------- 1 | //Author: Shreya Dayma 2 | //Python3 concept: Linked list insertion, deletion and length of nodes. 3 | //Github: https://github.com/ShreyaDayma-cse 4 | 5 | class Node: 6 | def __init__(self,data=None,next=None): 7 | self.data = data 8 | self.next = next 9 | 10 | class LinkedList: 11 | def __init__(self): 12 | self.head = None 13 | 14 | def insert_at_beginning(self,data): 15 | n = Node(data,self.head) 16 | self.head = n 17 | 18 | def insert_at_end(self,data): 19 | if self.head is None: 20 | self.head = Node(data,self.head) 21 | return 22 | else: 23 | itr = self.head 24 | while itr.next: 25 | itr = itr.next 26 | itr.next = Node(data,None) 27 | 28 | def print(self): 29 | if self.head is None: 30 | print("Linked list is empty") 31 | else: 32 | itr = self.head 33 | l=' ' 34 | while itr is not None: 35 | l+= str(itr.data) + '-->' 36 | itr = itr.next 37 | print(l) 38 | 39 | def get_length(self): 40 | c=0 41 | itr = self.head 42 | while itr: 43 | c+=1 44 | itr=itr.next 45 | return c 46 | 47 | def remove_at(self,index): 48 | if index<0 or index>=self.get_length(): 49 | print("Invalid Index") 50 | elif index==0: 51 | self.head = self.head.next 52 | return 53 | else: 54 | c=0 55 | itr=self.head 56 | while itr: 57 | if c==index-1: 58 | itr.next=itr.next.next 59 | break 60 | itr=itr.next 61 | c+=1 62 | 63 | if __name__ == '__main__': 64 | ll=LinkedList() 65 | ll.insert_at_beginning(4) 66 | ll.insert_at_beginning(7) 67 | ll.insert_at_end(8) 68 | ll.insert_at_end(2) 69 | print(ll.get_length()) 70 | ll.print() 71 | ll.remove_at(3) 72 | ll.print() 73 | -------------------------------------------------------------------------------- /Python3-Learn/Oops_shruticode81.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Shruti Anand 2 | // Python3 Concept: oops 3 | // GITHUB: https://github.com/shruticode81 4 | 5 | //Add your python3 concept below 6 | 7 | class Atm: 8 | pin=0 9 | __balance=0 10 | __counter=1001 11 | 12 | def __init__(self): 13 | self.accno=Atm.__counter 14 | self.pin=input("Kindly set ur pin:") 15 | print("Congrat pin set successfully!!") 16 | print("your account no is",self.accno) 17 | Atm.__counter=Atm.__counter+1 18 | 19 | @staticmethod 20 | def get_accno(): 21 | return Atm.__accno 22 | def get_balance(self): 23 | print(self.__balance) 24 | 25 | def set_balance(self,value): 26 | if type(value)==int: 27 | self.__balance=value 28 | print("ho gaya") 29 | else: 30 | print("double",value) 31 | 32 | def changePin(self): 33 | temp=input("Purana pin kiya tha!!") 34 | if self.pin==temp: 35 | self.pin=input("Naya pin bata:") 36 | print("Ho gaya ") 37 | else: 38 | print("invalid pin") 39 | 40 | def deposit(self): 41 | temp=input("Enter ur pin:") 42 | if self.pin==temp: 43 | amount=int(input("Kitna deposit karna h")) 44 | self.__balance=self.__balance+amount 45 | print("Deposited") 46 | else: 47 | print("Jyada paise h kiya?") 48 | 49 | def checkBalance(self): 50 | temp=input("Enter ur pin:") 51 | if self.pin==temp: 52 | print("Your balance is",self.__balance) 53 | else: 54 | print("Dusree ka balance kyu jaana h!!") 55 | 56 | def withdraw(self): 57 | temp=input("Enter ur pin:") 58 | if self.pin==temp: 59 | amount=int(input("Kitna chahiye ??")) 60 | if amount limit): # If requested amount is more than daily limit value then Exception is raised 29 | raise LimitExceeded 30 | if(a > bankbalance): # If requested amount is more than account's balance then Exception is raised 31 | raise InsufficientAmount 32 | except LimitExceeded as e: # LimitExceed exception is caught here 33 | print("Requested Amount is more than the limit,Kindly review your request!\n") 34 | except InsufficientAmount as e: # Insufficient exception is caught here 35 | print( 36 | "Requested Amount exceeded your account balance,Kindly check your balance!\n") 37 | except Exception as e: # Anyother Exceptions will be handeled here 38 | print( 39 | "Check the amount that you have entered.....Enter with out spaces.....and an integer value\n") 40 | else: # else is executed when there is no exception raised in try block 41 | bankbalance -= a 42 | print("Remaining balance is {}".format(bankbalance)) 43 | print("Your transaction is being processed.Please wait ..................\n") 44 | finally: # finally will be executed irrespectives of any exceptions 45 | print("Thank you for visiting :)"+"....."+"To exit press ctrl+c\n") 46 | 47 | 48 | if __name__ == "__main__": # Main function 49 | Atm() # ATM method is called here 50 | -------------------------------------------------------------------------------- /Python3-Learn/Set-Operations_Aman22sharma.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Syed Mohammad Muneer 2 | // Python3 Concept: Set-Operations 3 | // GITHUB: https://github.com/muneersyed156 4 | 5 | a=set() #a will be assigned to Object set() 6 | print(a) #prints empty set i.e Φ 7 | print(type(a)) #returns the datatype as set 8 | 9 | b={} #Don't get confused here ,it is a dict 10 | print(type(b)) #returns the datatype as dict 11 | print(b) #prints an empty dict 12 | 13 | m={1,(2,3,5),"Happy Hacking.... :D"} 14 | print(m) #set can have heterogeneous data that are immutable 15 | 16 | try: 17 | m={1,[2,3,5],"Happy Hacking.... :D"} #Exception will be raised as it has mutable datatype i.e [2,3,5] 18 | print(m) 19 | except Exception as e: 20 | print("There could be some mutable data in m") 21 | 22 | 23 | #Convertion of a datatype to Set 24 | z=["Hai","Welcome to",2020,"Hacktober-fest"] 25 | k=("Dark-Matter",1,4.0,45,3,3) 26 | print(set(z)) #Converting a list to set 27 | print(set(k)) #Converting a tuple to set 28 | 29 | #adding elements in to a set 30 | 31 | m={1,2,3,4} 32 | m.add(7) #adding an element into a set 33 | m.update([12, 3, 14]) #adding multiple elements to a set using update method 34 | 35 | #deleting an element from a set 36 | 37 | m.discard(7) #discard method is used to delete an element from a set 38 | print(m) 39 | m.remove(12) #remove method is also used to delete an element from a set 40 | print(m) 41 | m.discard(17) #If the element to be deleted is not present in the set then discard method will return None 42 | try: 43 | m.remove(17) #If the element to be deleted is not present in the set then remove methods raises an Exception 44 | except Exception as e: 45 | print("Deleting an element which is not present in set using remove method") 46 | 47 | m.pop() #Randomly delets an element from the set 48 | m.clear() #Deletes every element from the set and finally makes the set empty 49 | 50 | 51 | #Set Operations 52 | a={13,12,3,2,5,7,19,10} 53 | b={17,13,2,4,8,9,11,23} 54 | 55 | print(a-b) #prints all the elements that are present only in a 56 | print(b.difference(a)) #Instead of using - we can use difference operator 57 | 58 | print(a|b) #prints union of both a,b 59 | print(b.union(a)) #union method can be used instead of using | operator 60 | 61 | print(a&b) #prints common elements in both set a,b 62 | print(a.intersection(b)) #Instead of using & operation we can use intersection method 63 | 64 | print(a^b) #prints elements of a,b which are not in both sets called as Symmetric difference 65 | print(a.symmetric_difference(b)) #Instead of using ^ operator for we can use symmetric difference method here 66 | 67 | #frozen sets 68 | 69 | a=frozenset(a) 70 | print(a) 71 | try: 72 | a.add(800) 73 | except Exception as e: 74 | print("Frozen set means ...... Manipulations on set cannot be done!") 75 | 76 | 77 | -------------------------------------------------------------------------------- /Python3-Learn/face_and_body_detection_swairik.py: -------------------------------------------------------------------------------- 1 | # AUTHOR : Swairik Dey 2 | # Python3 Concept : Face and Body Detection using mediapipe 3 | # GITHUB : https://github.com/swairik 4 | 5 | import mediapipe as mp 6 | import cv2 7 | import sys 8 | 9 | mp_drawing = mp.solutions.drawing_utils 10 | mp_holistic = mp.solutions.holistic 11 | 12 | cascPath = sys.argv[1] if len(sys.argv) > 1 else '.' 13 | 14 | cap = cv2.VideoCapture(0, cv2.CAP_DSHOW) 15 | 16 | with mp_holistic.Holistic(min_detection_confidence = 0.5, min_tracking_confidence = 0.5) as holistic: 17 | 18 | while cap.isOpened(): 19 | ret, frame = cap.read() 20 | # frame = cv2.flip(frame, 1) # flip at the end for showing 21 | 22 | # Recolor Feed 23 | image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) 24 | 25 | # Make Detections 26 | results = holistic.process(image) 27 | # print(results.face_landmarks) 28 | 29 | # face_landmarks, pose_landmarks, left_hand_landmarks, right_hand_landmarks 30 | 31 | # Recolor image back to BGR for rendering 32 | image = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) 33 | 34 | # Draw face landmarks using mp_holistic.FACE_CONNECTIONS 35 | mp_drawing.draw_landmarks(image, results.face_landmarks, mp_holistic.FACE_CONNECTIONS, 36 | mp_drawing.DrawingSpec(color = (0,0,0), thickness = 1, circle_radius = 1), 37 | mp_drawing.DrawingSpec(color = (80,256,121), thickness = 1, circle_radius = 1) 38 | ) 39 | 40 | # Draw right hand 41 | mp_drawing.draw_landmarks(image, results.right_hand_landmarks, mp_holistic.HAND_CONNECTIONS, 42 | mp_drawing.DrawingSpec(color = (80,22,10), thickness = 2, circle_radius = 4), 43 | mp_drawing.DrawingSpec(color = (80,44,121), thickness = 2, circle_radius = 2) 44 | ) 45 | 46 | # Draw left hand 47 | mp_drawing.draw_landmarks(image, results.left_hand_landmarks, mp_holistic.HAND_CONNECTIONS, 48 | mp_drawing.DrawingSpec(color = (121,22,76), thickness = 2, circle_radius = 4), 49 | mp_drawing.DrawingSpec(color = (121,44,250), thickness = 2, circle_radius = 2) 50 | ) 51 | 52 | # Draw Pose Detections 53 | mp_drawing.draw_landmarks(image, results.pose_landmarks, mp_holistic.POSE_CONNECTIONS, 54 | mp_drawing.DrawingSpec(color = (245,117,66), thickness = 2, circle_radius = 4), 55 | mp_drawing.DrawingSpec(color = (245,66,230), thickness = 2, circle_radius = 2) 56 | ) 57 | 58 | 59 | 60 | image = cv2.flip(image, 1) 61 | cv2.imshow('Raw Webcam Feed', image) 62 | 63 | if cv2.waitKey(10) & 0xff == ord('q'): 64 | break 65 | 66 | cap.release() 67 | cv2.destroyAllWindows() -------------------------------------------------------------------------------- /Python3-Learn/String-Manipulations_muneersyed156.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Syed Mohammad Muneer 2 | // Python3 Concept: String Manipulations 3 | // GITHUB: https://github.com/muneersyed156 4 | 5 | 6 | #consider a string as follows 7 | s = "Harry and Hermione along with Ron went to Hogwarts to learn magic and also win battle against Lord Voldemort" 8 | 9 | #basic slicing format is s[startindex:stopindex:stepvalue(optional)] where stop index is not inclusive 10 | # space is also considered as a charcater 11 | print(s[0:7]) # prints from character at index 0 to charcater at index 6 12 | print(s[0:10:2]) # prints from charcater at index 0 to charcater at index 9 with a step value of 2 13 | print(s[-1]) # prints last charcater of the string s 14 | print(s[::-1]) # prints the string in a reverse order 15 | print(s[:]) # prints the whole string 16 | 17 | k="Welcome" 18 | print(k*3) #prints a string 3 times continuously 19 | 20 | #String methods and functions 21 | 22 | a="Hope Andrea Mikaelson" 23 | a=a.split(" ") #The name is splitted a part based on the delimitor used i.e " " 24 | print(a) #prints list of words seperated by spaces 25 | 26 | print(a[0].upper()) #converts each character in the string to uppercase 27 | print(a[0].lower()) #converts each character in the string to lowercase 28 | print(a[0].capitalize()) #converts first character in the string to uppercase 29 | print(a[0].startswith("an")) #if string starts with "an" substring then returns true else false 30 | print(a[1].endswith("klaus")) #if string ends with "klaus" substring then returns true else false 31 | 32 | a=' '.join(a) #Join function combines the words into a sentence with mentioned delimiter between the words 33 | print(a) 34 | 35 | print(a.find('a')) #returns the position of mentioned charcater from left if existed else -1 will be returned 36 | 37 | try: 38 | print(a.index('e')) #if character is found then it's position is retunred 39 | print(a.index('c')) #if charcater is not found then index function raises an exception 40 | except Exception as e: 41 | print("Element is not found") 42 | 43 | 44 | m='Dark,Matter,is,found,everywhere' 45 | 46 | m=m.replace(","," ") #replace funtion is used to replace a charcater with other character in whole string 47 | print(m) 48 | 49 | k='hello1' 50 | 51 | print(k.isalpha()) #returns true if string has only alphabets else false 52 | print(k.isalnum()) #returns true if string has either alphabets,numbers or both else false 53 | print(k.isdigit()) #returns true if all charcaters in string are digits 54 | 55 | #string library 56 | 57 | import string 58 | 59 | print(string.ascii_letters) #prints alphabets both lower,uppercase 60 | print(string.ascii_lowercase) #prints lowercase alphabets 61 | print(string.ascii_uppercase) #prints uppercase alphabets 62 | print(string.digits) #prints digits from [0-9] 63 | 64 | print("\n") 65 | #Custom printing using format method 66 | 67 | s=str(input("Please Enter your name: ")) 68 | print("Dear {}, \nWelcome to Hacktober fest".format(s)) 69 | -------------------------------------------------------------------------------- /Python3-Learn/list-methods_awsheeshh.py: -------------------------------------------------------------------------------- 1 | ''' 2 | AUTHOR: Ashish 3 | Python3 Concept: List Manipulation and Methods in Python 4 | GITHUB: https://github.com/awsheeshh 5 | ''' 6 | 7 | # Let's take a list which we will use as an example. 8 | 9 | my_list_1 = [2, 4, 5, 1] #This is a single data-type list. 10 | my_list_2 = [2, "hello", 10, 13, 17, 13] #This is a mixed data-type list with both strings and integer in it. 11 | my_list_3 = [3, [2, 1, 7], 9, 3] #This is a multi dimensional list. 12 | 13 | #List Methods 14 | 15 | #append() method 16 | #appends the given element to the last index of the list. 17 | ''' 18 | input: my_list_1.append(10) 19 | print(my_list_1) 20 | output: [2, 4, 5, 1, 10] 21 | ''' 22 | 23 | #insert() method 24 | #Inserts the given element at given position of list. 25 | ''' 26 | input: my_list_1.insert(0, 8) {0 is the index where you want to put element that is 8} 27 | print(my_list_1) 28 | output: [8, 2, 4, 5, 1] 29 | ''' 30 | 31 | #Accessing List Elements 32 | #1. For Single Dimensional List 33 | ''' 34 | input: print(my_list_1[0]) {0 is the index of the element you want to retrieve} 35 | output: 2 36 | ''' 37 | #2. For Multi Dimensional List 38 | ''' 39 | my_list_3 = [3, [2, 1, 7], 9, 3] (list inside list) 40 | Suppose, we want to retrieve the 2nd element from the list which is inside my_list_3 41 | 42 | input: print(my_list_3[1][1]) {The second list is at index 1 of my_list_3 and we want to retreive 2nd element from it so we use [1] again} 43 | output: 1 44 | ''' 45 | 46 | #Removing Elements From List 47 | #1. remove() method 48 | ''' 49 | It removes the element specified from the list given that the element is present in the list. 50 | input: my_list_1.remove(2) -> will remove the first occurence of 2 51 | print(my_list_1) 52 | output: [4, 5, 1] 53 | ''' 54 | #2. pop() method 55 | ''' 56 | It removes the last element of list by default but to remove an element at specific position you have to pass it's index value in function call. 57 | input1: my_list_1.pop() -> will remove last element 58 | print(my_list_1) 59 | output1: [2, 4, 5] 60 | 61 | input2: my_list_1.pop(0) -> will remove element at index 2. 62 | print(my_list_1) 63 | output2: [4, 5, 1] 64 | ''' 65 | 66 | #List Slicing 67 | ''' 68 | input: print(my_list_1[1:]) -> will slice the list from index 1. 69 | output: [4, 5, 1] 70 | 71 | input: print(my_list_2[2:5]) -> will slice the list from index 2 upto index 4. 72 | output: [10, 13, 17] 73 | 74 | input: print(my_list_2[:-3]) -> will slice till 3rd element from the last 75 | output: [2, "hello", 10] 76 | 77 | >> list[::-1] reverses thee list but you can use list.reverse() method too. 78 | ''' 79 | 80 | #sort() method 81 | #Sorts the list in ascending or descending order. 82 | ''' 83 | input: print(my_list_1.sort()) -> sorts in ascending order by default 84 | output: [1, 2, 4, 5] 85 | 86 | input: print(my_list_1.sort(reverse=True)) -> sorts in descending order 87 | output: [5, 4, 2, 1] 88 | ''' 89 | 90 | #Thanks for reading. 91 | #Read python docs for more in depth understanding. 92 | 93 | -------------------------------------------------------------------------------- /Python3-Learn/crud_csv_ninefyi.py: -------------------------------------------------------------------------------- 1 | #AUTHOR: Piti (Fyi) Champeethong 2 | #Python3 Concept: CRUD for CSV file 3 | #GITHUB: https://github.com/ninefyi 4 | 5 | import csv 6 | 7 | def create_mobile(): 8 | name = str(input("Enter mobile contact:")) 9 | mobile = str(input("Enter mobile number:")) 10 | headers = ['name', 'mobile'] 11 | with open("mobile.csv", "a+", encoding='UTF8', newline='') as f: 12 | writer = csv.DictWriter(f,fieldnames=headers) 13 | writer.writerow({'name':name, 'mobile':mobile}) 14 | 15 | def read_mobile(): 16 | headers = ['name', 'mobile'] 17 | with open("mobile.csv", "r+", encoding='UTF8') as f: 18 | reader = csv.DictReader(f,fieldnames=headers) 19 | print("Row\tName\t\tMobile") 20 | print("-" * 30) 21 | row_index = 1 22 | for line in reader: 23 | print(row_index, "\t", line['name'],"\t\t",line["mobile"]) 24 | row_index = row_index + 1 25 | 26 | def update_mobile(): 27 | row_number = int(input("Enter row number for updating:")) 28 | headers = ['name', 'mobile'] 29 | update_list = [] 30 | with open("mobile.csv", "r+", encoding='UTF8') as f: 31 | reader = csv.DictReader(f,fieldnames=headers) 32 | row_index = 1 33 | for line in reader: 34 | if(row_index == row_number): 35 | name = str(input("Enter new mobile contact ({}):".format(line['name']))) 36 | mobile = str(input("Enter new mobile number ({}):".format(line["mobile"]))) 37 | line['name'] = name 38 | line['mobile'] = mobile 39 | update_list.append(line) 40 | row_index = row_index + 1 41 | update_csv(update_list) 42 | 43 | def delete_mobile(): 44 | row_number = int(input("Enter row number for deleting:")) 45 | headers = ['name', 'mobile'] 46 | update_list = [] 47 | with open("mobile.csv", "r+", encoding='UTF8') as f: 48 | reader = csv.DictReader(f,fieldnames=headers) 49 | row_index = 1 50 | for line in reader: 51 | if(row_index != row_number): 52 | update_list.append(line) 53 | row_index = row_index + 1 54 | update_csv(update_list) 55 | 56 | def update_csv(new_list): 57 | headers = ['name', 'mobile'] 58 | with open("mobile.csv", "w+", encoding='UTF8', newline='') as f: 59 | writer = csv.DictWriter(f,fieldnames=headers) 60 | writer.writerows(new_list) 61 | 62 | def display_menu(): 63 | print("-" * 30) 64 | print("1. Create a new mobile number on CSV") 65 | print("2. Read all mobile numbers from CSV") 66 | print("3. Update a mobile numbers from CSV") 67 | print("4. Delete a mobile numbers from CSV") 68 | print("0. Exit") 69 | menu = int(input("Enter you menu number [0,1,2,3,4]:")) 70 | print("-" * 30) 71 | return menu 72 | 73 | menu = display_menu() 74 | 75 | while menu != 0: 76 | if menu == 1: 77 | create_mobile() 78 | elif menu == 2: 79 | read_mobile() 80 | elif menu == 3: 81 | update_mobile() 82 | elif menu == 4: 83 | delete_mobile() 84 | elif menu == 0: 85 | exit 86 | menu = display_menu() -------------------------------------------------------------------------------- /Python3-Learn/TIC_TAC_TOE game.py: -------------------------------------------------------------------------------- 1 | 2 | # AUTHOR: Hitesh Vishnoi 3 | # Python3 Concept: Tic Tac Toe Game !! 4 | # GITHUB: https://github.com/hiteshv01 5 | 6 | 7 | import numpy as np 8 | import random 9 | from time import sleep 10 | 11 | # Creates an empty board 12 | def create_board(): 13 | return(np.array([[0, 0, 0], 14 | [0, 0, 0], 15 | [0, 0, 0]])) 16 | 17 | # Check for empty places on board 18 | def possibilities(board): 19 | l = [] 20 | 21 | for i in range(len(board)): 22 | for j in range(len(board)): 23 | 24 | if board[i][j] == 0: 25 | l.append((i, j)) 26 | return(l) 27 | 28 | # Select a random place for the player 29 | def random_place(board, player): 30 | selection = possibilities(board) 31 | current_loc = random.choice(selection) 32 | board[current_loc] = player 33 | return(board) 34 | 35 | # Checks whether the player has three 36 | # of their marks in a horizontal row 37 | def row_win(board, player): 38 | for x in range(len(board)): 39 | win = True 40 | 41 | for y in range(len(board)): 42 | if board[x, y] != player: 43 | win = False 44 | continue 45 | 46 | if win == True: 47 | return(win) 48 | return(win) 49 | 50 | # Checks whether the player has three 51 | # of their marks in a vertical row 52 | def col_win(board, player): 53 | for x in range(len(board)): 54 | win = True 55 | 56 | for y in range(len(board)): 57 | if board[y][x] != player: 58 | win = False 59 | continue 60 | 61 | if win == True: 62 | return(win) 63 | return(win) 64 | 65 | # Checks whether the player has three 66 | # of their marks in a diagonal row 67 | def diag_win(board, player): 68 | win = True 69 | y = 0 70 | for x in range(len(board)): 71 | if board[x, x] != player: 72 | win = False 73 | if win: 74 | return win 75 | win = True 76 | if win: 77 | for x in range(len(board)): 78 | y = len(board) - 1 - x 79 | if board[x, y] != player: 80 | win = False 81 | return win 82 | 83 | # Evaluates whether there is 84 | # a winner or a tie 85 | def evaluate(board): 86 | winner = 0 87 | 88 | for player in [1, 2]: 89 | if (row_win(board, player) or 90 | col_win(board,player) or 91 | diag_win(board,player)): 92 | 93 | winner = player 94 | 95 | if np.all(board != 0) and winner == 0: 96 | winner = -1 97 | return winner 98 | 99 | # Main function to start the game 100 | def play_game(): 101 | board, winner, counter = create_board(), 0, 1 102 | print(board) 103 | sleep(2) 104 | 105 | while winner == 0: 106 | for player in [1, 2]: 107 | board = random_place(board, player) 108 | print("Board after " + str(counter) + " move") 109 | print(board) 110 | sleep(2) 111 | counter += 1 112 | winner = evaluate(board) 113 | if winner != 0: 114 | break 115 | return(winner) 116 | 117 | # Driver Code 118 | print("Winner is: " + str(play_game())) 119 | -------------------------------------------------------------------------------- /Python3-Learn/telegramScraper_rakeshchauhan/addmember.py: -------------------------------------------------------------------------------- 1 | from telethon.sync import TelegramClient 2 | from telethon.tl.functions.messages import GetDialogsRequest 3 | from telethon.tl.types import InputPeerEmpty, InputPeerChannel, InputPeerUser 4 | from telethon.errors.rpcerrorlist import PeerFloodError, UserPrivacyRestrictedError 5 | from telethon.tl.functions.channels import InviteToChannelRequest 6 | import sys 7 | import csv 8 | import traceback 9 | import time 10 | 11 | #Update the values from telegram.org/app 12 | api_id = 123456 13 | api_hash = '' 14 | phone = '' 15 | client = TelegramClient(phone, api_id, api_hash) 16 | 17 | client.connect() 18 | if not client.is_user_authorized(): 19 | client.send_code_request(phone) 20 | client.sign_in(phone, input('Enter the code: ')) 21 | 22 | dialogs = client.get_dialogs() 23 | for user in dialogs: 24 | if user.title is not None: 25 | print(user.title) 26 | 27 | for dialog in client.iter_dialogs(): 28 | print('{:>14}: {}'.format(dialog.id, dialog.title)) 29 | if dialog.title == "Telegram" : 30 | print( client.get_messages(dialog.title, 10)) 31 | 32 | 33 | 34 | 35 | 36 | users = [] 37 | with open('members20.csv', encoding='UTF-8') as f: 38 | rows = csv.reader(f,delimiter=",",lineterminator="\n") 39 | next(rows, None) 40 | for row in rows: 41 | user = {} 42 | user['username'] = row[0] 43 | user['id'] = int(row[1]) 44 | user['access_hash'] = int(row[2]) 45 | user['name'] = row[3] 46 | users.append(user) 47 | 48 | chats = [] 49 | last_date = None 50 | chunk_size = 200 51 | groups=[] 52 | 53 | result = client(GetDialogsRequest( 54 | offset_date=last_date, 55 | offset_id=0, 56 | offset_peer=InputPeerEmpty(), 57 | limit=chunk_size, 58 | hash = 0 59 | )) 60 | chats.extend(result.chats) 61 | 62 | for chat in chats: 63 | try: 64 | if chat.megagroup== True: 65 | groups.append(chat) 66 | except: 67 | continue 68 | 69 | print('Choose a group to add members:') 70 | i=0 71 | for group in groups: 72 | print(str(i) + '- ' + group.title) 73 | i+=1 74 | 75 | g_index = input("Enter a Number: ") 76 | target_group=groups[int(g_index)] 77 | 78 | target_group_entity = InputPeerChannel(target_group.id,target_group.access_hash) 79 | 80 | mode = int(input("Enter 1 to add by username or 2 to add by ID: ")) 81 | 82 | n = 0 83 | 84 | for user in users: 85 | n += 1 86 | if n == 500: 87 | sleep(900) 88 | try: 89 | print ("Adding {}".format(user['id'])) 90 | if mode == 1: 91 | if user['username'] == "": 92 | continue 93 | user_to_add = client.get_input_entity(user['username']) 94 | elif mode == 2: 95 | user_to_add = InputPeerUser(user['id'], user['access_hash']) 96 | else: 97 | sys.exit("Invalid Mode Selected. Please Try Again.") 98 | client(InviteToChannelRequest(target_group_entity,[user_to_add])) 99 | print("Waiting for 60-180 Seconds...") 100 | time.sleep(100) 101 | except PeerFloodError: 102 | print("Getting Flood Error from telegram. Script is stopping now. Please try again after some time.") 103 | except UserPrivacyRestrictedError: 104 | print("The user's privacy settings do not allow you to do this. Skipping.") 105 | except: 106 | traceback.print_exc() 107 | print("Unexpected Error") 108 | continue 109 | 110 | 111 | 112 | 113 | 114 | -------------------------------------------------------------------------------- /Python3-Learn/AdventureWithRio.py: -------------------------------------------------------------------------------- 1 | #AUTHOR: Rio Cantre 2 | #Python3 Concept: Adventure Game 3 | #GITHUB: https://github.com/RioCantre 4 | 5 | 6 | import time 7 | import random 8 | 9 | weather = ["sunny", "rainy", "stormy", "windy", "snowy", "dark"] 10 | ambience = random.choice(weather) 11 | tools = ["flashlight", "stick", "bat", "gun", "phone", "knife"] 12 | weapon = random.choice(tools) 13 | emotions = ["scared", "tired", "nervours", "crying", "sweating"] 14 | condition = random.choice(emotions) 15 | 16 | 17 | def print_pause(message_to_print): 18 | print(message_to_print) 19 | time.sleep(0.2) 20 | 21 | 22 | def intro(): 23 | print_pause("You woke up from your nap.") 24 | print_pause("It's a " + ambience + " afternoon.") 25 | print_pause("You heard a strange noise coming from the backyard.") 26 | print_pause("The noise is getting more bolder and louder.") 27 | print_pause("You are so curious.\n") 28 | 29 | 30 | def first_move(): 31 | print_pause("You grab a " + weapon + " and head towards the back door.") 32 | print_pause("You sneak to the backdoor slowly and smoothly.") 33 | print_pause("As you get closer the noise seems so familiar.") 34 | choice = input("Would you run away? yes or no?") 35 | if choice == "no": 36 | print_pause("It's the same wild Boar from yesterday.") 37 | print_pause("It stopped eating the sack of potatoes on the floor.") 38 | print_pause("It looked around and finally saw you.") 39 | print_pause("Both of you are staring.") 40 | attack = input("Initiate attack? yes or no?") 41 | if attack == "yes": 42 | print_pause("You lift up your hand with your " + 43 | weapon + " and smash it on the wall.") 44 | print_pause("The boar run away as quickly as it can.") 45 | if attack == "no": 46 | print_pause("The boar growl and roar. Trying to scare you.") 47 | print_pause("As you lift your hand, it run away quickly.") 48 | conclusion() 49 | elif choice == "yes": 50 | print_pause("You run fast heading back and close the door.") 51 | conclusion() 52 | else: 53 | print_pause("You're a warrior.\n") 54 | conclusion() 55 | 56 | 57 | def second_move(): 58 | print_pause("You grab your keys and lock the back door.") 59 | print_pause("You called someone and told them to come and get you.") 60 | print_pause("You were " + condition + " and waiting for help to come.") 61 | print_pause("The noise suddenly stop.") 62 | print_pause("You calm down and went out of bed.") 63 | next_step = input("Would you like to continue or no?") 64 | if next_step == "continue": 65 | print_pause("You went slowy heading to the backdoor.") 66 | print_pause("Your dog suddenly appeared behind you.") 67 | print_pause("That surprises you and felt relief.") 68 | conclusion() 69 | elif next_step == "no": 70 | print_pause("You stayed in bed and went back to sleep.") 71 | conclusion() 72 | else: 73 | print_pause("continue or no?\n") 74 | conclusion() 75 | 76 | 77 | def reaction(): 78 | print_pause("Enter 1 to go out and investigate.") 79 | print_pause("Enter 2 to lock the door and call for help.") 80 | print_pause("What will you do?") 81 | moves = input("(Please enter 1 or 2.)\n") 82 | if moves == "1": 83 | first_move() 84 | elif moves == "2": 85 | second_move() 86 | else: 87 | conclusion() 88 | 89 | 90 | def conclusion(): 91 | play_again = input("Would you like to restart? yes or no?\n") 92 | if play_again == "yes": 93 | print_pause("Okay, mighty warrior.") 94 | reaction() 95 | elif play_again == "no": 96 | print_pause("You're a brave warrior.") 97 | else: 98 | print_pause("Please enter yes or no.") 99 | conclusion() 100 | 101 | 102 | def play_game(): 103 | intro() 104 | reaction() 105 | 106 | 107 | play_game() 108 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Hacktoberfest2021 Repo for Beginners 2 | ![HF2020 Events 1600x400 Centered](https://user-images.githubusercontent.com/40789486/135643400-72926541-6437-4ed6-b81a-77cfadbebafb.png) 3 | 4 | 5 | 6 | 9 | 12 | 13 | 14 | 37 | 43 | 44 |
7 | - Follow the Contribution guidelines** 8 | 10 |
Repo Maintainers
11 |
15 | 16 | ## How You Can Contribute to this repo Adding to follow for Python Concepts is below under `Format` 17 | 1. Add your Python3 Concepts in the respective `Python3-Learn` directory 18 | ### Name of File: python3-concept-name_yourusername.py 19 | ```markdown 20 | example: hello_world_Aman22sharma.py 21 | example: Variables_yourusername.py 22 | example: Data-types_Aman22sharma.py 23 | ``` 24 | ### Name of File: python3-concept-name_yourusername.py 25 | # Format 26 | 27 | ### * Python3-Learn 28 | ### Name of File: python3-concept-name_yourusername.py 29 | ```markdown 30 | // AUTHOR: Your Name 31 | // Python3 Concept: (ex: variable,datatypes etc) 32 | // GITHUB: your github profile link 33 | 34 | //Add your python3 concept below 35 | ``` 36 | 38 |

39 |
Aman Sharma
Product Engineer
@Hylobiz, Banglore (India)
40 |

41 |
Shruti Shastri
Software Engineer
@32nd, Delhi (India)
42 |
45 | 46 | - You can not add the same concepts again so, make sure whatever concept you are going to add check it once and add new concepts 47 | 48 | Make a Pull Request for your changes and wait to be merged. 49 | 50 | # How to Begin 51 | #### 0. Star this repository 52 | 53 | ![Copy of Colorful Neon Marble Gaming YouTube Channel Art (1)](https://user-images.githubusercontent.com/40789486/135642232-bfb074a4-fd32-4fa9-84d7-507f72fbaa2a.gif) 54 | 55 | - :star::star::star: Star this repository have fun! :star::star::star: 56 | #### 1. Fork this repository 57 | 58 | ![Copy of Colorful Neon Marble Gaming YouTube Channel Art](https://user-images.githubusercontent.com/40789486/135641797-e71ee5a7-7a4c-4130-8376-2ea2e8ea68e5.gif) 59 | 60 | #### 2. Clone this repo to your local environment 61 | 62 | 63 | ![Copy of Colorful Neon Marble Gaming YouTube Channel Art (2)](https://user-images.githubusercontent.com/40789486/135642597-fde41ce7-13d3-4021-8350-7fee3f99ad31.gif) 64 | 65 | ```markdown 66 | git clone https://github.com/your-username/Hacktoberfest2021-beginner.git 67 | cd Hacktoberfest2021_beginner 68 | ``` 69 | 70 | #### 3. Set your streams (For sync your clone with the original repo) 71 | ```markdown 72 | git remote add upstream https://github.com/Aman22sharma/Hacktoberfest2021_beginner.git 73 | git pull upstream master 74 | ``` 75 | #### 4. Make your addition to the Python3 concepts in `Python3-Learn` directories 76 | #### 5. Create a branch 77 | ```markdown 78 | git checkout -b your-branch-name 79 | ``` 80 | #### 6. Pull from the upstream again (This is to ensure we still have the latest code) 81 | ```markdown 82 | git pull upstream master 83 | ``` 84 | #### 7. Commit and Push your changes 85 | ```markdown 86 | git add . 87 | git commit -m "commit message" 88 | git push origin your-branch-name 89 | ``` 90 | 91 | - Create a new Pull Request from your forked repository, click the `New Pull Request` button located at the top of your repository 92 | - Wait for you PR to be reviewed and merge approval 93 | 94 | 106 | 107 | 108 | # HAPPY Hacktoberfest! 109 | ![1_Zgzm5Dw86UPNlSLeyUAoyw](https://user-images.githubusercontent.com/40789486/94897225-cfac6580-04ac-11eb-9e58-79d821976848.gif) 110 | 111 | -------------------------------------------------------------------------------- /Python3-Learn/Matrix-Calculator-Andy-Ra.py: -------------------------------------------------------------------------------- 1 | ## AUTHOR: Andy-Ra 2 | ## GITHUB: https://github.com/Andy-Ra/ 3 | ## Python3 Concept: Matrix calculator in python 4 | 5 | import re 6 | 7 | 8 | repeat = 'Y' 9 | while (repeat == 'Y' or repeat == 'y'): 10 | print ("++++++ WELCOME TO MATRIX CALCULATOR ++++++") 11 | 12 | repeat_cm = 'Y' 13 | while (repeat_cm == 'Y' or repeat_cm == 'y'): 14 | print ("") 15 | ##To Insert a order matrix 16 | print ("") 17 | print ("Please input the same order matrix : ") 18 | fc = int(input("First order matrix row : ")) 19 | fr = int(input("First order matrix collumn : ")) 20 | sc = int(input("Second order matrix row : ")) 21 | sr = int(input("Second order matrix collumn : ")) 22 | fm = fc * fr 23 | sm = sc * sr 24 | 25 | print ("Please choose one of the commands :") 26 | print ("1. matrix addition") 27 | print ("2. matrix subtraction (coming soon)") 28 | choose = input("Number :") 29 | 30 | if (choose == "1"): ##or choose == "2" 31 | if (fc == sc) & (fr == sr): 32 | print ("") 33 | print ("+++++++++++++++++++++++++++++++++++++++") 34 | print ("Enter {} Value of First Matrix :" .format(fm)) 35 | f_row = [] 36 | for a_value in range (0, fc): 37 | f_contents = [] 38 | for b_value in range (0, fr): 39 | f_number = int(input("Input index of [{}] [{}] from first matrix : ".format(a_value, b_value))) 40 | f_contents.append(f_number) 41 | f_row.append(f_contents) 42 | 43 | f_contents ='\n'.join (str(f) for f in f_row) 44 | print ("") 45 | print ("+++++++++++++++++++++++++++++++++++++") 46 | print ("Value of First Matrix : \n{}" .format(f_contents)) 47 | 48 | print ("") 49 | print ("+++++++++++++++++++++++++++++++++++++++") 50 | print ("Enter {} Value of Second Matrix :" .format(sm)) 51 | s_row = [] 52 | for c_value in range (0, sc): 53 | s_contents = [] 54 | for d_value in range (0, sr): 55 | s_number = int(input("Input index of [{}] [{}] from Second matrix : ".format(c_value, d_value))) 56 | s_contents.append(s_number) 57 | s_row.append(s_contents) 58 | 59 | s_contents ='\n'.join (str(s) for s in s_row) 60 | print ("") 61 | print ("+++++++++++++++++++++++++++++++++++++") 62 | print ("Value of Second Matrix : \n{}" .format(s_contents)) 63 | 64 | 65 | ##if user chose matrix addition 66 | if (choose == "1"): 67 | m_row =[] 68 | r_row = [] 69 | for l in range (0, len (f_row)): 70 | r_content = [] 71 | for m in range (0,len (f_row [0])): 72 | result = int((f_row[l][m] + s_row[l][m])) 73 | r_content.append(result) 74 | 75 | r_row.append(r_content) 76 | r_content ='\n'.join (str(h) for h in r_row) 77 | print ("") 78 | print ("+++++++++++++++++++++++++++++++++++++") 79 | print ("") 80 | print ("sum of Matrix : \n{} \n+ \n{} \n= \n{}" .format(f_contents, s_contents, r_content)) 81 | 82 | ##to show sum method 83 | print ("Method :") 84 | for l in range (0, len (f_row)): 85 | m_content=[] 86 | for m in range (0,len (f_row [0])): 87 | process = ('[{} + {}]' .format(f_row[l][m],s_row[l][m])) 88 | m_content.append(process) 89 | 90 | m_row.append (m_content) 91 | m_content = '\n' .join (str(proc) for proc in m_row) 92 | print (m_content) 93 | 94 | repeat_cm = 'N' 95 | 96 | ##if user chose matrix subtaction 97 | elif (choose == "2"): 98 | print ("coming soon") 99 | repeat_cm = 'N' 100 | 101 | else : 102 | print ("please insert the same order matrix") 103 | 104 | ##to repeat if the user choose another 105 | elif not (re.match("[0-9]", choose)): 106 | repeat_cm = 'Y' 107 | 108 | 109 | repeat_yn = 'Y' 110 | while (repeat_yn == 'Y' or repeat_yn == 'y'): 111 | repeat_yn = input("Try Again? [Y/N] ") 112 | 113 | ## if user choose "N" option, then the program will be stopped 114 | if repeat_yn == 'N' or repeat_yn == 'n': 115 | print ("") 116 | print ("++++++ THANK YOU ++++++") 117 | print ("+++++++++++++++++++++++++") 118 | repeat = 'N' 119 | 120 | ##if user choose "Y" option, then the program will be looping from the beginning 121 | elif repeat_yn == 'Y' or repeat_yn == 'y': 122 | repeat_yn = 'N' 123 | repeat = 'Y' 124 | 125 | ## If users didn't choose Y/N, this program is looping to ask "Try again" again 126 | else : 127 | repeat_yn = 'Y' -------------------------------------------------------------------------------- /Python3-Learn/Breast Cancer Detection System.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: Vanshika 2 | // Python3 Concept: Breast Cancer Detection System 3 | // GITHUB: https://github.com/Vanshika-11 4 | 5 | //Add your python3 concept below 6 | 7 | # In[1]: 8 | 9 | 10 | import pandas as pd 11 | import numpy as np 12 | 13 | from sklearn.datasets import load_breast_cancer 14 | from sklearn.preprocessing import StandardScaler 15 | 16 | 17 | # In[2]: 18 | 19 | 20 | data=load_breast_cancer() 21 | 22 | 23 | # In[3]: 24 | 25 | 26 | data 27 | 28 | 29 | # In[4]: 30 | 31 | 32 | data.keys() 33 | 34 | 35 | # In[5]: 36 | 37 | 38 | data['DESCR'] 39 | 40 | 41 | # In[6]: 42 | 43 | 44 | print(data['DESCR']) 45 | 46 | #569 tumors each having 30 attributes 47 | 48 | 49 | # In[7]: 50 | 51 | 52 | print(data['frame']) 53 | 54 | 55 | # In[8]: 56 | 57 | 58 | print(data['target_names']) 59 | 60 | 61 | # In[9]: 62 | 63 | 64 | print(data['target']) 65 | 66 | # 0=malignant (cancerous) 67 | # 1=benign (non - cancerous) 68 | 69 | 70 | # In[10]: 71 | 72 | 73 | print(data['data']) 74 | 75 | 76 | # In[11]: 77 | 78 | 79 | print(data['data'][0]) #values of first tumor 80 | 81 | 82 | # In[12]: 83 | 84 | 85 | data['data'].shape 86 | 87 | 88 | # 569 tumors each having 30 features. 89 | # Each tumor has a target , either 0 or 1. Means if any tumor has target=0,it is malignant and if any tumor has target=1,it is benign 90 | 91 | 92 | # In[13]: 93 | 94 | 95 | print(data['feature_names']) 96 | print(len(data['feature_names'])) 97 | 98 | 99 | # In[14]: 100 | 101 | 102 | j = 0 103 | for i in data['feature_names']: 104 | print(i,":",data['data'][568][j]) 105 | j+=1 106 | 107 | #values and features of 568th tumor 108 | 109 | 110 | # In[15]: 111 | 112 | 113 | feature=data['data'] 114 | feature 115 | 116 | #attributes of each tumor 117 | 118 | 119 | # In[16]: 120 | 121 | 122 | label=data['target'] 123 | label 124 | 125 | # target or label = malignant or benign 126 | 127 | 128 | # In[17]: 129 | 130 | 131 | feature.shape 132 | 133 | 134 | # In[18]: 135 | 136 | 137 | label.shape 138 | 139 | 140 | # In[19]: 141 | 142 | 143 | print(data['DESCR']) 144 | 145 | # here if we observe that min and max values are very much varied, some have small range and some have a very wide range 146 | 147 | # As for area attribute, range is very high , but if we look for concave points , range is very small 148 | 149 | # So we need to rearrange all the values in a particular range, so that every row is having only a particular range 150 | 151 | 152 | # In[20]: 153 | 154 | 155 | # Standardising the data 156 | 157 | scale = StandardScaler() 158 | 159 | feature = scale.fit_transform(feature) 160 | print(feature) 161 | 162 | 163 | # In[21]: 164 | 165 | 166 | # Comparing before and after standardisation 167 | # For first tumor 168 | 169 | j = 0 170 | for i in data['feature_names']: 171 | print(i,":",data['data'][568][j]) 172 | j+=1 173 | 174 | 175 | print('------------------------AFTER-----------------------------------------') 176 | 177 | j = 0 178 | for i in data['feature_names']: 179 | print(i,":",feature[0][j]) 180 | j+=1 181 | 182 | 183 | 184 | 185 | # In[22]: 186 | 187 | 188 | # We will pass these features to the neural network and will get '0' or '1' as output 189 | 190 | 191 | # In[23]: 192 | 193 | 194 | print(feature[568]) 195 | print(data['target_names'][label[568]],label[568]) 196 | 197 | 198 | # In[24]: 199 | 200 | 201 | df= pd.DataFrame(feature,columns=data['feature_names']) 202 | 203 | 204 | # In[25]: 205 | 206 | 207 | df 208 | 209 | 210 | # In[26]: 211 | 212 | 213 | 214 | df_features= pd.DataFrame(feature , columns = data['feature_names']) 215 | df_label = pd.DataFrame(label , columns = ['label']) 216 | df = pd.concat([df_features, df_label], axis=1) 217 | 218 | df 219 | 220 | 221 | # In[27]: 222 | 223 | 224 | 225 | #500 Training 226 | X_train = feature[:500] 227 | y_train = label[:500] 228 | 229 | #35 Validation 230 | X_val = feature[500:535] 231 | y_val = label[500:535] 232 | 233 | #34 Testing 234 | X_test = feature[535:] 235 | y_test = label[535:] 236 | 237 | 238 | # In[28]: 239 | 240 | 241 | # neural network 242 | 243 | from keras.models import Sequential 244 | from keras.layers import Dense 245 | 246 | 247 | # In[49]: 248 | 249 | 250 | model=Sequential() 251 | 252 | model.add(Dense(15, activation='relu',input_dim=30)) 253 | model.add(Dense(8, activation='relu')) 254 | model.add(Dense(1, activation='sigmoid')) 255 | 256 | model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy']) 257 | 258 | 259 | # In[53]: 260 | 261 | 262 | model.fit(X_train,y_train,batch_size=1,epochs=5,validation_data=(X_val,y_val)) 263 | 264 | 265 | # In[54]: 266 | 267 | 268 | model.evaluate(X_test,y_test) 269 | 270 | 271 | # In[55]: 272 | 273 | 274 | #Predictions 275 | sample=X_test[0] 276 | 277 | 278 | # In[56]: 279 | 280 | 281 | sample 282 | 283 | 284 | # In[58]: 285 | 286 | 287 | sample.shape 288 | 289 | 290 | # In[62]: 291 | 292 | 293 | import numpy as np 294 | 295 | sample=np.reshape(sample, (1,30)) 296 | sample.shape 297 | 298 | 299 | # In[68]: 300 | 301 | 302 | model.predict(sample)[0][0] 303 | 304 | 305 | # In[69]: 306 | 307 | 308 | if model.predict(sample)[0][0]>0.5: 309 | print("Benign") 310 | else: 311 | print("Malignant") 312 | 313 | 314 | # In[76]: 315 | 316 | 317 | print("-------------Predicted vs actual value---------------") 318 | for i in range(100): 319 | sample=X_test[i] 320 | sample=np.reshape(sample, (1,30)) 321 | 322 | if model.predict(sample)[0][0]>0.5: 323 | print("-Benign") 324 | else: 325 | print("-Malignant") 326 | 327 | if y_test[i]==0: 328 | print("*Malignant") 329 | else: 330 | print("*Benign") 331 | 332 | print("----------------------------") 333 | 334 | 335 | # In[ ]: 336 | 337 | 338 | #df=df.sample(frac=1) to shuffle the dataset 339 | 340 | -------------------------------------------------------------------------------- /Python3-Learn/sha384_Guruprasanna02.py: -------------------------------------------------------------------------------- 1 | #// AUTHOR: Guruprasanna 2 | #// Python3 Concept: sha384(hashing) 3 | #// GITHUB: https://github.com/Guruprasanna02 4 | 5 | #// Add your python3 concept below 6 | 7 | #SHA384 hashing implementation manaually. 8 | 9 | 10 | 11 | def rightrotate_64(i, j): 12 | i &= 0xFFFFFFFFFFFFFFFF 13 | return ((i >> j) | (i << (64 - j))) & 0xFFFFFFFFFFFFFFFF 14 | 15 | def leftrotate_64(i, j): 16 | i &= 0xFFFFFFFFFFFFFFFF 17 | return ((i << j) | (i >> (64 - j))) & 0xFFFFFFFFFFFFFFFF 18 | 19 | def leftshift(i, j): 20 | return i << j 21 | 22 | def rightshift(i, j): 23 | return i >> j 24 | 25 | class SHA384(): 26 | def __init__(self): 27 | self.digest_size = 48 28 | self.block_size = 96 29 | 30 | h0 = 0xcbbb9d5dc1059ed8 31 | h1 = 0x629a292a367cd507 32 | h2 = 0x9159015a3070dd17 33 | h3 = 0x152fecd8f70e5939 34 | h4 = 0x67332667ffc00b31 35 | h5 = 0x8eb44a8768581511 36 | h6 = 0xdb0c2e0d64f98fa7 37 | h7 = 0x47b5481dbefa4fa4 38 | 39 | self.k = [ 40 | 0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc, 0x3956c25bf348b538, 41 | 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118, 0xd807aa98a3030242, 0x12835b0145706fbe, 42 | 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2, 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 43 | 0xc19bf174cf692694, 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65, 44 | 0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5, 0x983e5152ee66dfab, 45 | 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4, 0xc6e00bf33da88fc2, 0xd5a79147930aa725, 46 | 0x06ca6351e003826f, 0x142929670a0e6e70, 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 47 | 0x53380d139d95b3df, 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b, 48 | 0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30, 0xd192e819d6ef5218, 49 | 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8, 0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 50 | 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8, 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 51 | 0x682e6ff3d6b2b8a3, 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec, 52 | 0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b, 0xca273eceea26619c, 53 | 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, 0x06f067aa72176fba, 0x0a637dc5a2c898a6, 54 | 0x113f9804bef90dae, 0x1b710b35131c471b, 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 55 | 0x431d67c49c100d4c, 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817 56 | ] 57 | 58 | self.hash_pieces = [h0, h1, h2, h3, h4, h5, h6, h7] 59 | 60 | def update(self, arg): 61 | h0, h1, h2, h3, h4, h5, h6, h7 = self.hash_pieces 62 | data = bytearray(arg) 63 | orig_len_in_bits = (8 * len(data)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF 64 | data.append(0x80) 65 | while len(data) % 128 != 112: 66 | data.append(0) 67 | data += orig_len_in_bits.to_bytes(16, byteorder='big') 68 | for a in range(0, len(data), 128): 69 | group = data[a : a + 128] 70 | w = [0 for i in range(80)] 71 | for i in range(16): 72 | w[i] = int.from_bytes(group[8*i : 8*i + 8], byteorder='big') 73 | for j in range(16, 80): 74 | s0 = (rightrotate_64(w[j-15], 1) ^ rightrotate_64(w[j-15], 8) ^ rightshift(w[j-15], 7)) & 0xFFFFFFFFFFFFFFFF 75 | s1 = (rightrotate_64(w[j-2], 19) ^ rightrotate_64(w[j-2], 61) ^ rightshift(w[j-2], 6)) & 0xFFFFFFFFFFFFFFFF 76 | w[j] = (w[j-16] + s0 + w[j-7] + s1) & 0xFFFFFFFFFFFFFFFF 77 | a, b, c, d, e, f, g, h = h0, h1, h2, h3, h4, h5, h6, h7 78 | for m in range(80): 79 | S1 = (rightrotate_64(e, 14) ^ rightrotate_64(e, 18) ^ rightrotate_64(e, 41)) & 0xFFFFFFFFFFFFFFFF 80 | ch = ((e & f) ^ ((~e) & g)) & 0xFFFFFFFFFFFFFFFF 81 | temp1 = (h + S1 + ch + self.k[m] + w[m]) & 0xFFFFFFFFFFFFFFFF 82 | S0 = (rightrotate_64(a, 28) ^ rightrotate_64(a, 34) ^ rightrotate_64(a, 39)) & 0xFFFFFFFFFFFFFFFF 83 | maj = ((a & b) ^ (a & c) ^ (b & c)) & 0xFFFFFFFFFFFFFFFF 84 | temp2 = (S0 + maj) & 0xFFFFFFFFFFFFFFFF 85 | a1 = (temp1 + temp2) & 0xFFFFFFFFFFFFFFFF 86 | e1 = (d + temp1) & 0xFFFFFFFFFFFFFFFF 87 | a, b, c, d, e, f, g, h = a1, a, b, c, e1, e, f, g 88 | 89 | h0 = (h0 + a) & 0xFFFFFFFFFFFFFFFF 90 | h1 = (h1 + b) & 0xFFFFFFFFFFFFFFFF 91 | h2 = (h2 + c) & 0xFFFFFFFFFFFFFFFF 92 | h3 = (h3 + d) & 0xFFFFFFFFFFFFFFFF 93 | h4 = (h4 + e) & 0xFFFFFFFFFFFFFFFF 94 | h5 = (h5 + f) & 0xFFFFFFFFFFFFFFFF 95 | h6 = (h6 + g) & 0xFFFFFFFFFFFFFFFF 96 | h7 = (h7 + h) & 0xFFFFFFFFFFFFFFFF 97 | self.hash_pieces = [h0, h1, h2, h3, h4, h5, h6, h7] 98 | 99 | def digest(self): 100 | mod_hashPieces = self.hash_pieces[:-2] 101 | return sum(leftshift(x, 64*i) for i, x in enumerate(mod_hashPieces[::-1])) 102 | 103 | def hexdigest(self): 104 | digest = self.digest() 105 | raw = digest.to_bytes(self.digest_size, byteorder='big') 106 | format_str = '{:0' + str(2 * self.digest_size) + 'x}' 107 | return format_str.format(int.from_bytes(raw, byteorder='big')) 108 | 109 | def main(): 110 | string = input("Input : ") 111 | h = SHA384() 112 | data = bytes(string, encoding='utf8') 113 | h.update(data) 114 | print(f"The hexadecimal equivalent of SHA384 is:\n {h.hexdigest()}") 115 | 116 | main() 117 | -------------------------------------------------------------------------------- /Python3-Learn/Math-module_praneethacl.py: -------------------------------------------------------------------------------- 1 | // AUTHOR: PPraneetha Chebolu 2 | //Python3 Concept: Math Modules 3 | // GITHUB: https://github.com/praneethacl 4 | 5 | # This module provides access to the mathematical functions defined by the C standard. 6 | # These functions cannot be used with complex numbers 7 | 8 | # To use mathematical functions under this module, you have to import the module using import math. 9 | import math 10 | 11 | 12 | #Constants 13 | 14 | print(math.pi) # prints the mathematical constant π = 3.141592…, to available precision. 15 | 16 | print(math.e) # prints the mathematical constant e = 2.718281…, to available precision. 17 | 18 | print(math.tau) # prints the mathematical constant τ = 6.283185…, to available precision. 19 | 20 | print(math.inf) # prints a floating-point positive infinity. 21 | 22 | print(math.nan) # prints a floating-point “not a number” (NaN) value. 23 | 24 | 25 | 26 | #Number-theoretic functions 27 | 28 | # math.ceil(x): returns the smallest integer greater than or equal to x. 29 | print(math.ceil(5.4)) # prints 6 30 | 31 | # math.copysign(x, y): returns a float with the magnitude (absolute value) of x with the sign of y 32 | print(math.copysign(1.0, -1)) # prints -1.0 33 | 34 | # math.fabs(x): return the absolute value of x. 35 | print(math.fabs(-12.3)) # prints 12.3 36 | 37 | # math.factorial(x): return x factorial as an integer. 38 | print(math.factorial(5)) # prints 120 39 | 40 | # math.floor(x): return the largest integer less than or equal to x. 41 | print(math.ceil(5.4)) # prints 5 42 | 43 | # math.fmod(x, y): returns x % y, but is generally used for floats instead of integers. 44 | print(math.fmod(-15.7, 4.9)) # prints -0.9982 but -15.7 % 4.9 gives 3.9002 45 | 46 | # math.frexp(x): return the mantissa and exponent of x as the pair (m, e), such that x == m * 2**e. 47 | print(math.frexp(3)) # prints(0.75, 2) 48 | 49 | # math.fsum(iterable): return an accurate floating point sum of values in the iterable. 50 | print(math.fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])) # prints 1.0 51 | 52 | # math.gcd(a, b): return the greatest common divisor of the integers a and b. 53 | print(math.gcd(147, 21)) # prints 21 54 | 55 | # math.isfinite(x): return True if x is neither an infinity nor a NaN, and False otherwise. 56 | print(math.isfinite(1)) # print True 57 | 58 | # math.isinf(x): return True if x is a positive or negative infinity, and False otherwise. 59 | print(math.isinf(-math.inf)) # prints True 60 | 61 | # math.isnan(x): return True if x is a NaN (not a number), and False otherwise. 62 | print(math.isnan(math.nan)) # prints True 63 | 64 | # math.ldexp(x, i): return x * (2**i). This is essentially the inverse of function frexp(). 65 | print(math.ldexp(2, 2)) # prints 8.0 66 | 67 | # math.modf(x): return the fractional and integer parts of x. 68 | print(math.modf(-11.44)) # prints (-0.4399999999999995, -11.0) 69 | 70 | # math.trunc(x): returns the truncated integer value of x 71 | print(math.trunc(134.33)) # prints 134 72 | 73 | 74 | 75 | #Power and logarithmic functions 76 | 77 | # math.log(x): return the natural logarithm of x (to base e). 78 | print(math.log(2)) # prints 0.6931471805599453 79 | 80 | # math.log(x, base): return the logarithm of x to the given base. 81 | print(math.log(4, 2)) # prints 2.0 82 | 83 | # math.log1p(x): return the natural logarithm of 1+x (base e). 84 | print(math.log1p(1)) # prints 0.6931471805599453 85 | 86 | # math.log2(x): return the base-2 logarithm of x. 87 | print(math.log2(2)) # prints 1.0 88 | 89 | # math.log10(x): return the base-10 logarithm of x. 90 | print(math.log10(2)) # prints 0.3010299956639812 91 | 92 | # math.pow(x, y): return x raised to the power y. 93 | print(math.pow(2, 3)) # prints 8.0 94 | 95 | # math.sqrt(x): return the square root of x. 96 | print(math.sqrt(9)) # prints 3.0 97 | 98 | 99 | 100 | #Trigonometric functions 101 | 102 | # math.acos(x): return the arc cosine of x, in radians. 103 | print(math.acos(0.1)) # prints 1.4706289056333368 104 | 105 | # math.asin(x): return the arc sine of x, in radians. 106 | print(math.asin(0.1)) # prints 0.1001674211615598 107 | 108 | # math.atan(x): return the arc tangent of x, in radians. 109 | print(math.atan(0.1)) # prints 0.09966865249116204 110 | 111 | # math.atan2(y, x): returns atan(y / x) 112 | print(math.atan2(1, 10)) # prints 0.09966865249116202 113 | 114 | # math.cos(x): return the cosine of x. 115 | print(math.cos(0.1)) # prints 0.9950041652780258 116 | 117 | # math.sin(x): returns the sine of x. 118 | print(math.sin(0.1)) # prints 0.09983341664682815 119 | 120 | # math.tan(x): returns the tangent of x. 121 | print(math.tan(0.1)) # prints 0.10033467208545055 122 | 123 | # math.hypot(x, y): returns the Euclidean norm, sqrt(x*x + y*y) 124 | print(math.hypot(3,4)) # prints 5.0 125 | 126 | # math.degrees(x): converts angle x from radians to degrees 127 | print(math.degrees(1.57079)) # prints 89.99963750135457 128 | 129 | # math.radians(x): converts angle x from degrees to radians 130 | print(math.radians(90)) # prints 1.5707963267948966 131 | 132 | 133 | 134 | # Hyperbolic functions 135 | 136 | # math.acosh(x): return the inverse hyperbolic cosine of x. 137 | print(math.acosh(90)) # prints 5.192925985263684 138 | 139 | # math.asinh(x): return the inverse hyperbolic sine of x. 140 | print(math.asinh(90)) # prints 5.192987713658941 141 | 142 | # math.atanh(x): return the inverse hyperbolic tangent of x. 143 | print(math.atanh(0.5)) # prints 0.5493061443340549 144 | 145 | # math.cosh(x): return the hyperbolic cosine of x. 146 | print(math.cosh(0.5)) # prints 1.1276259652063807 147 | 148 | # math.sinh(x): return the hyperbolic sine of x. 149 | print(math.sinh(0.5)) # prints 0.5210953054937474 150 | 151 | # math.tanh(x): return the hyperbolic tangent of x. 152 | print(math.tanh(0.5)) # prints 0.46211715726000974 153 | 154 | 155 | -------------------------------------------------------------------------------- /Python3-Learn/basic-concepts-drishyadamodaran.py: -------------------------------------------------------------------------------- 1 | # Python3-Learn 2 | ## Name of File: basic-concepts_drishyadamodaran.py 3 | // AUTHOR: Drishya 4 | // Python3 Concept: Basic python concepts 5 | // GITHUB: https://github.com/drishyadamodaran 6 | 7 | 8 | # Data types 9 | #Let’s move to data types. The data structures in Python are dictionaries, tuples and lists. Sets can be found in the sets library that is available in all versions of Python from 2.5 onwards. Lists are similar to one-dimensional arrays, although you can also have lists of other lists. Dictionaries are essentially associative arrays or hash tables. Tuples are one-dimensional arrays. Now, Python arrays can be of any type, and the types are always zero. Negative numbers start from the end to the beginning, and -1 is the last item. Variables can also point to functions. Here is an example of the usage: You can use the colon to access array ranges. If you leave the start index empty, the interpreter assumes the first item, so the end index assumes the last item. Negative indexes count from the last item, so -1 is seen as the last item. Here is an example: 10 | #Adding the third parameter will see the Python step in the N item increments instead of one in the last line. For instance, in the above sample code, the first item is returned and then the third, so items zero and two in zero-indexing. 11 | 12 | #Strings 13 | #Let’s move on to strings. Python strings can either use single or double quotation marks, and you can use quotation marks of one kind in a string using another kind, so the following is valid: 14 | 15 | #**“This is a ‘valid’ string.”** 16 | 17 | #Multi-strings are enclosed in single or triple double-quotes. Python can support Unicode right from the start, using the following syntax: 18 | 19 | #**u”This is Unicode.”** 20 | 21 | #To fill strings with values, you can use the modulo (%) operator and then a tuple. Each % gets replaced with a tuple item from left to right, and you can use dictionary substitutions as well. 22 | 23 | 24 | print "Name: %s\ 25 | Number: %s\ 26 | String: %s" % (myclass.name, 3, 3 * "-") 27 | Name: Poromenos 28 | Number: 3 29 | String: --- 30 | 31 | strString = """This is a multiline string.""" 32 | >>> print "This %(verb)s a %(noun)s." % {"noun": "test", "verb": "is"} 33 | #This is a test. 34 | 35 | # Flow control statements 36 | #Python’s flow control statements are ‘while’, ‘for’ and ‘if’. For a switch, you need to use ‘if’. For enumerating through list members, use ‘for’. For obtaining a number list, use range (number). Here is the statement syntax: 37 | 38 | rangelist = range(10) 39 | print rangelist 40 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for number in rangelist: 41 | if number in (3, 4, 7, 9): 42 | break 43 | else: 44 | continue 45 | else: 46 | pass 47 | if rangelist[1] == 2: 48 | print "The second item (lists are 0-based) is 2" 49 | elif rangelist[1] == 3: 50 | print "The second item (lists are 0-based) is 3" 51 | else: 52 | print "Dunno" 53 | while rangelist[1] == 1: 54 | pass 55 | 56 | ### Functions 57 | #The ‘def’ keyword is used to declare functions. Optional arguments can be set in the function declaration after mandatory arguments by assigning them default values. In the case of named arguments, the argument name is assigned a value. Functions can return a tuple, and you can effectively return several values using tuple unpacking. Parameters are passed through reference, but tuples, ints, strings, and other immutable types are unchangeable because only the item’s memory location is passed. Binding another object to the variable removed the older one and replaced immutable types. Here is an example: 58 | 59 | funcvar = lambda x: x + 1 60 | print funcvar(1) 61 | 2 62 | def passing_example(a_list, an_int=2, a_string="A default string"): 63 | a_list.append("A new item") 64 | an_int = 4 65 | return a_list, an_int, a_string 66 | 67 | my_list = [1, 2, 3] my_int = 10 68 | print passing_example(my_list, my_int) 69 | ([1, 2, 3, 'A new item'], 4, "A default string") 70 | my_list 71 | [1, 2, 3, 'A new item'] my_int 72 | 10 73 | 74 | ### Classes 75 | #Python supports a very limited multiple class inheritance. Private methods and variables can be declared with the addition of two or more underscores and at most one trailing one. You can also bind names to class instances, like so. 76 | 77 | class MyClass(object): 78 | common = 10 79 | def __init__(self): 80 | self.myvariable = 3 81 | def myfunction(self, arg1, arg2): 82 | return self.myvariable 83 | >>> classinstance = MyClass() 84 | >>> classinstance.myfunction(1, 2) 85 | 3 86 | >>> classinstance2 = MyClass() 87 | >>> classinstance.common 88 | 10 89 | >>> classinstance2.common 90 | 10 91 | >>> MyClass.common = 30 92 | >>> classinstance.common 93 | 30 94 | >>> classinstance2.common 95 | 30 96 | >>> classinstance.common = 10 97 | >>> classinstance.common 98 | 10 99 | >>> classinstance2.common 100 | 30 101 | >>> MyClass.common = 50 102 | >>> classinstance.common 103 | 10 104 | >>> classinstance2.common 105 | 50 106 | def __init__(self, arg1): 107 | self.myvariable = 3 108 | print arg1 109 | >>> classinstance = OtherClass("hello") 110 | hello 111 | >>> classinstance.myfunction(1, 2) 112 | 3 113 | >>> classinstance.test = 10 114 | >>> classinstance.test 115 | 10 116 | 117 | # Exceptions 118 | #In Python, Exceptions are handled via try-except blocks [exceptionname]. Here is an example syntax: 119 | 120 | def some_function(): 121 | try: 122 | 10 / 0 123 | except ZeroDivisionError: 124 | print "Oops, invalid." 125 | else: 126 | pass 127 | finally: 128 | print "We're done with that." 129 | >>> some_function() 130 | Oops, invalid. 131 | #We're done with that. 132 | ### Importing 133 | 134 | #In Python, external libraries can be used using the keyword import[library]. For individual functions, you can use from [funcname] or [libname] import. Take a look at the following sample syntax: 135 | 136 | import random 137 | from time import clock 138 | randomint = random.randint(1, 100) 139 | >>> print randomint 140 | 64 141 | 142 | # File I/O 143 | #The Python programing language comes with a lot of libraries, to begin with. For instance, here is a look at how we convert data structures to strings with the use of the pickle library using file I/O: 144 | 145 | import pickle 146 | mylist = ["This", "is", 4, 13327] # Open the file C: 147 | #binary.dat for writing. The letter r before the filename string is used to prevent backslash escaping. 148 | myfile = open(r"C:\\binary.dat", "w") 149 | pickle.dump(mylist, myfile) 150 | myfile.close() 151 | myfile = open(r"C:\\text.txt", "w") 152 | myfile.write("This is a sample string") 153 | myfile.close() 154 | myfile = open(r"C:\\text.txt") 155 | >>> print myfile.read() 156 | #'This is a sample string' 157 | myfile.close() 158 | #Open the file for reading. 159 | myfile = open(r"C:\\binary.dat") 160 | loadedlist = pickle.load(myfile) 161 | myfile.close() 162 | >>> print loadedlist 163 | ['This', 'is', 4, 13327] 164 | 165 | #Conditions and variables 166 | #Conditions in Python can be changed. For instance, take a look at this condition: 167 | 168 | 1 < a < 3 169 | 170 | #This condition checks that a is greater than one and also less than three. You can also use ‘del’ to delete items or variables in arrays. A great way to manipulate and create lists is through list comprehensions, which have an expression and then a ‘for’ clause, followed by a zero or more ‘for’ or ‘if’ clauses. Here is an example: 171 | 172 | >>> lst1 = [1, 2, 3] >>> lst2 = [3, 4, 5] 173 | >>> print [x * y for x in lst1 for y in lst2] [3, 4, 5, 6, 8, 10, 9, 12, 15] 174 | >>> print [x for x in lst1 if 4 > x > 1] [2, 3] 175 | #Check if a condition is true for any items. 176 | #"any" returns true if any item in the list is true. 177 | >>> any([i % 3 for i in [3, 3, 4, 4, 3]]) 178 | True 179 | #This is because 4 % 3 = 1, and 1 is true, so any() returns True. 180 | #Check for how many items a condition is true. 181 | >>> sum(1 for i in [3, 3, 4, 4, 3] if i == 4) 182 | 2 183 | >>> del lst1[0] >>> print lst1 184 | [2, 3] >>> del lst1 185 | 186 | #Global variables are called so because they are declared outside functions and are readable without special declarations. However, if you want to write them, you need to declare them at the start of the function with the ‘global’ keyword. Otherwise, Python will bind the object to a new local variable. Take a look at the sample syntax below: 187 | 188 | number = 5 189 | def myfunc(): 190 | #This will print 5. 191 | print number 192 | def anotherfunc(): 193 | #This raises an exception because the variable has not been bound before printing. Python knows that it an object will be bound to it later and creates a new, local object instead of accessing the global one. 194 | print number 195 | number = 3 196 | def yetanotherfunc(): 197 | global number 198 | #This will correctly change the global. 199 | number = 3 200 | -------------------------------------------------------------------------------- /Python3-Learn/python3-Basics-Concept_Vaishnavi-101.py: -------------------------------------------------------------------------------- 1 | #Author:Vaishnavi Sharma 2 | #python3 concepts - firstprogram,escape sequences,variable,data type,casting 3 | #list,set,tuple,dictionary,conditional statement,Loop,Function,lambda Function, 4 | #classes and object. 5 | #Github Profile Link : https://github.com/Vaishnavi-101 6 | 7 | #python Begginers Guide: 8 | #first python Program 9 | # print("Hello") 10 | # print('Hello World!') 11 | 12 | # facts about " " and '' 13 | 14 | #print("Hi i am 'Vaishnavi' ") 15 | # print('Hi i am "Devil" ') 16 | 17 | # Esape Sequences \ , \\ , \n , \t , \r 18 | 19 | # print("\'Python\' Begginer Course") 20 | # print("I\'m learning it from youtube\nand it is going cool!") 21 | # print("Enjoying\tlearning") 22 | 23 | #importance of indentation in python , python use it to refer a block of code 24 | #same whitespaces should be given for same block otherwise syntax error occoured 25 | if(6 > 3): 26 | print("Yes") 27 | print("yes 6 is greater") 28 | 29 | #MultiLine Comment - python ignore string literals if it is not assign to string 30 | """ 31 | this is multiLine 32 | Comment 33 | 34 | """ 35 | #Variable - Python has no Command for declariang a variable 36 | # x =5 37 | # y = "DEVIL" 38 | # print(x) 39 | # print(y) 40 | 41 | # x=6 42 | # x="Mannu" 43 | # print(x) 44 | 45 | #Casting - if you want to specify a data type 46 | # a = str(7) 47 | # b = float(5) 48 | # print(a) 49 | # print(b) 50 | 51 | #type() - get the data type 52 | # a = 7 53 | # print(type(a)) 54 | 55 | #variable Functionality - Many to one or One to many 56 | # x,y,z = 5,"hi",10.0 57 | # print(x) 58 | # print(y) 59 | # print(z) 60 | 61 | # x= y =0 62 | # print(x) 63 | # print(y) 64 | 65 | # + combine both text and variable 66 | # a = "Python" 67 | # print(a +" is cool") 68 | 69 | # b="Hello" 70 | # c ="Everyone" 71 | # print(b + c) 72 | 73 | #Data Types - Built in Data Types 74 | #Numeric Type also called Numbers 75 | # x = 10 #int 76 | # print(x) 77 | # y = 20.5 #float 78 | # print(y) 79 | # z = 5j #complex 80 | # print(z) 81 | 82 | #Text Type 83 | # x ="Hello" #str 84 | # print(x) 85 | 86 | #sequence Type - list,Tuple,Range 87 | # z = ["Apple","Banana"] 88 | # print(z) 89 | # b = ("mango","orange") 90 | # print(b) 91 | # v = range(5) 92 | # print(v) 93 | 94 | #strings and string Methods 95 | #a ="Hello" 96 | # print(a) 97 | # print(a[2]) 98 | # print(a[2:]) #slicing it gives index 2 to end 99 | # print(a[:2]) #slicing it give index 0 to 2 100 | # print(a[1:4]) #including start but excluding end 101 | # print(a[::2]) #jump at one position 102 | 103 | # print(len(a)) len -for length 104 | # txt = "Hi i am learning Python" 105 | # if "am" in txt: Find word present in given string or not 106 | # print("Yes") 107 | 108 | #UpperCase And LowerCase 109 | # a="WORLD" 110 | # print(a.lower()) 111 | # b="hello" 112 | # print(b.upper()) 113 | 114 | #strip - remove whiteSpaces 115 | # a =" Hello World " 116 | # print(a.strip()) 117 | 118 | #replace() - string with another string 119 | # a="Devil" 120 | # print(a.replace("D","E")) 121 | 122 | #split - split string in to two substring 123 | # a ="Hello,World" 124 | # print(a.split(",")) 125 | 126 | #format - combine number with string 127 | # a=22 128 | # b="Devil age is {}" 129 | # print(b.format(a)) 130 | 131 | #List - is simiilar to string (functionality) 132 | # it is one of built in data type in Python 133 | # MyList =[1,7,5,3] #list also allow duplicates 134 | # MyList1=["Devil","Evil","angstrom"] 135 | # MyList2=["shinchan",5] 136 | #print(MyList) 137 | # print(MyList1) 138 | # print(MyList2) 139 | #List are Mutable means change the value 140 | # MyList[1] =5 141 | # print(MyList) 142 | 143 | # print(MyList) 144 | #Insert - used to insert at specified Position 145 | # MyList.insert(3,4) 146 | # print(MyList) 147 | 148 | #append - add item in list to last 149 | # MyList.append(5) 150 | # print(MyList) 151 | 152 | #extend - add list to another list 153 | # MyList.extend(MyList1) 154 | # print(MyList) 155 | 156 | #remove or pop- it remove given item and also specified 157 | # MyList1.remove("Devil") 158 | # print(MyList1) 159 | # MyList1.pop() #remove last item 160 | # print(MyList1) 161 | # MyList1.pop(1) 162 | # print(MyList1) 163 | 164 | #sort - sort in ascending order 165 | # MyList.sort() 166 | # print(MyList) 167 | 168 | #sort(reverse=True) - sort in descending order 169 | # MyList.sort(reverse=True) 170 | # print(MyList) 171 | 172 | #copy - listname.copy() cant copied by l1=l2 173 | # hi=MyList.copy() 174 | # print(hi) 175 | 176 | #join - list can be join in many method like append,extend,+ 177 | # NewList=MyList+MyList1 178 | # print(NewList) 179 | """ 180 | There are four collection built in data types in the Python programming language: 181 | List ,Tuple , Set , dictionary 182 | List is a collection which is ordered and changeable. Allows duplicate members. 183 | Tuple is a collection which is ordered and unchangeable. Allows duplicate members. 184 | 185 | """ 186 | #Tuple - very simillar to list but it is immutable but ordered 187 | # MyTuple =("Hello","WOrld") 188 | # print(MyTuple) 189 | # MyTuple[1]="Name" // Tuple not support item assignment 190 | # print(MyTuple) 191 | 192 | #sets - unordered and unindexed , dont allow duplicates values 193 | # MySets ={1,2,"banana",2} 194 | # print(MySets) 195 | # MySets.add(5) #to add an item 196 | # print(MySets) 197 | 198 | #update() - add one set item to another set 199 | # MySets1={5,7} 200 | # MySets.update(MySets1) 201 | # print(MySets) 202 | 203 | #remove() or discard() - both use to remove element from sets 204 | #with one difference is that if element not present then remove show error 205 | #and discard() not shown any error 206 | #pop(),clear(),del 207 | 208 | # MySets.remove(2) 209 | # print(MySets) 210 | 211 | #join() - union() or update() both of them exclude duplicates 212 | #MySets2={4,6} 213 | # MySets3=MySets1.union(MySets2) 214 | # print(MySets3) 215 | 216 | #duplicates - intersection_update 217 | # set={5,3} 218 | # set.intersection_update(MySets1) 219 | # print(set) 220 | 221 | #intersection() - return which present in both 222 | #symmetric_difference - it conatins which is not present in both sets 223 | 224 | # Dictionary - is a collection which is ordered and changeable. No duplicate members. 225 | #dictionaries are python version of hash table based on mapping of key value pair. 226 | #thisdic={"vaishu":1,"payal":420} 227 | # print(thisdic) 228 | # x=thisdic["payal"] // accessing value by its key 229 | # print(x) 230 | #get() - accessing 231 | # x=thisdic.get("payal") 232 | # print(x) 233 | 234 | #keys() - return all keys of dictionaries 235 | # x=thisdic.keys() 236 | # print(x) 237 | 238 | #values() - return all values of dictionaries 239 | #update() - updates a key value pair 240 | # thisdic.update({"vaishu":420}) 241 | # print(thisdic) 242 | 243 | #delte a value - pop(key),popitem(),del,clear() 244 | #copy() - one dictionary to another 245 | 246 | #conditional statement 247 | #if 248 | # a=5 249 | # b=4 250 | # if a>b : 251 | # print("a is graeter than b") 252 | 253 | #elif- 254 | # a =41 255 | # b=22 256 | # if ab : 259 | # print("a is greater than b") 260 | 261 | #else - keyword caught anything which is not done by previous conditions 262 | # a=12 263 | # b=25 264 | # if a==b: 265 | # print("a is equal to b") 266 | # elif a>b: 267 | # print("a is greater") 268 | # else : 269 | # print("a is smaller than b") 270 | 271 | #And , or - logical operator 272 | # a = 5 273 | # b = 7 274 | # c = 10 275 | # if a