Last active
April 14, 2021 11:25
-
-
Save tvilo/5ebe0ed515011c532f0cd2bc5b037114 to your computer and use it in GitHub Desktop.
python snippets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## enumerate() inbuilt function lets you access index and value at the same time within a or loop | |
| arr = [2,4,6,3,8,10] | |
| for index,value in enumerate(arr): | |
| print(f"At Index {index} The Value Is -> {value}") | |
| '''Output | |
| At Index 0 The Value Is -> 2 | |
| At Index 1 The Value Is -> 4 | |
| At Index 2 The Value Is -> 6 | |
| At Index 3 The Value Is -> 3 | |
| At Index 4 The Value Is -> 8 | |
| At Index 5 The Value Is -> 10 | |
| ''' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## Let’s say you have two lists and you want to merge them into one single list by adding their elements. It can be useful in some scenarios like | |
| maths = [59, 64, 75, 86] | |
| physics = [78, 98, 56, 56] | |
| # Brute Force Method | |
| list1 = [ | |
| maths[0]+physics[0], | |
| maths[1]+physics[1], | |
| maths[2]+physics[2], | |
| maths[3]+physics[3] | |
| ] | |
| # List Comprehension | |
| list1 = [x + y for x,y in zip(maths,physics)] | |
| # Using Maps | |
| import operator | |
| all_devices = list(map(operator.add, maths, physics)) | |
| # Using Numpy Library | |
| import numpy as np | |
| list1 = np.add(maths,physics) | |
| '''Output | |
| [137 162 131 142] | |
| ''' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## This code snippet shows how simply you can write a calculator without using any if-else conditions. | |
| import operator | |
| action = { | |
| "+" : operator.add, | |
| "-" : operator.sub, | |
| "/" : operator.truediv, | |
| "*" : operator.mul, | |
| "**" : pow | |
| } | |
| print(action['*'](5, 5)) # 25 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## It becomes important sometimes to know the execution time of the shell or code block to get a better algorithm with minimum time spent. | |
| # METHOD 1 | |
| import datetime | |
| start = datetime.datetime.now() | |
| """ | |
| CODE | |
| """ | |
| print(datetime.datetime.now()-start) | |
| # METHOD 2 | |
| import time | |
| start_time = time.time() | |
| main() | |
| print(f"Total Time To Execute The Code is {(time.time() - start_time)}" ) | |
| # METHOD 3 | |
| import timeit | |
| code = ''' | |
| ## Code snippet whose execution time is to be measured | |
| [2,6,3,6,7,1,5,72,1].sort() | |
| ''' | |
| print(timeit.timeit(stmy = code,number = 1000)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## You can call multiple functions on one line in python. | |
| def add(a,b): | |
| return a+b | |
| def sub(a,b): | |
| return a-b | |
| a,b = 9,6 | |
| print((sub if a > b else add)(a, b)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## An anagram is a word that is formed by rearranging the letters of a different word, using all the original letters exactly once. | |
| def check_anagram(first_word, second_word): | |
| return sorted(first_word) == sorted(second_word) | |
| print(check_anagram("silent", "listen")) # True | |
| print(check_anagram("ginger", "danger")) # False |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Brute force Method | |
| import os.path | |
| from os import path | |
| def check_for_file(): | |
| print("File exists: ",path.exists("data.txt")) | |
| if __name__=="__main__": | |
| check_for_file() | |
| ''' | |
| File exists: False | |
| ''' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## Check whether a string contains a substring. | |
| addresses = [ | |
| "12/45 Elm street", | |
| '34/56 Clark street', | |
| '56,77 maple street', | |
| '17/45 Elm street' | |
| ] | |
| street = 'Elm street' | |
| for i in addresses: | |
| if street in i: | |
| print(i) | |
| '''output | |
| 12/45 Elm street | |
| 17/45 Elm street | |
| ''' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## The following method can be used to convert two lists into a dictionary. | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## The following method can be used to convert two lists into a dictionary. | |
| list1 = ['karl','lary','keera'] | |
| list2 = [28934,28935,28936] | |
| # Method 1: zip() | |
| dictt0 = dict(zip(list1,list2)) | |
| # Method 2: dictionary comprehension | |
| dictt1 = {key:value for key,value in zip(list1,list2)} | |
| # Method 3: Using a For Loop (Not Recommended) | |
| tuples = zip(list1, list2) | |
| dictt2 = {} | |
| for key, value in tuples: | |
| if key in dictt2: | |
| pass | |
| else: | |
| dictt2[key] = value | |
| print(dictt0, dictt1, dictt2, sep = "\n") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## Like Java and C++, python also offers a way to handle exceptions using try, except, and finally block. | |
| # Example 1 | |
| try: | |
| a = int(input("Enter a:")) | |
| b = int(input("Enter b:")) | |
| c = a/b | |
| print(c) | |
| except: | |
| print("Can't divide with zero") | |
| # Example 2 | |
| try: | |
| #this will throw an exception if the file doesn't exist. | |
| fileptr = open("file.txt","r") | |
| except IOError: | |
| print("File not found") | |
| else: | |
| print("The file opened successfully") | |
| fileptr.close() | |
| # Example 3 | |
| try: | |
| fptr = open("data.txt",'r') | |
| try: | |
| fptr.write("Hello World!") | |
| finally: | |
| fptr.close() | |
| print("File Closed") | |
| except: | |
| print("Error") | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## The most important part of a code is the input, logic, and output. All three parts require some sort of formatting while writing the code for better and easy-to-read outputs. | |
| name = "Abhay" | |
| age = 21 | |
| ## METHOD 1: Concatenation | |
| print("My name is "+name+", and I am "+str(age)+ " years old.") | |
| ## METHOD 2: F-strings (Python 3+) | |
| print(f"My name is {name}, and I am {age} years old") | |
| ## METHOD 3: Join | |
| print(''.join(["My name is ", name, ", and I am ", str(age), " years old"])) | |
| ## METHOD 4: modulus operator | |
| print("My name is %s, and I am %d years old." % (name, age)) | |
| ## METHOD 5: format(Python 2 and 3) | |
| print("My name is {}, and I am {} years old".format(name, age)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## This will come in handy when you are dealing with databases and JSON files and need to merge multiple data from different files or tables into a common file. | |
| basic_information = {"name":['karl','Lary'],"mobile":["0134567894","0123456789"]} | |
| academic_information = {"grade":["A","B"]} | |
| details = dict() ## Combines Dict | |
| ## Dictionary Comprehension Method | |
| details = {key: value for data in (basic_information, academic_information) for key,value in data.items()} | |
| print(details) | |
| ## Dictionary unpacking | |
| details = {**basic_information ,**academic_information} | |
| print(details) | |
| ## Copy and Update Method | |
| details = basic_information.copy() | |
| details.update(academic_information) | |
| print(details) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## When you have a list of dictionaries, you might want to organize them in sorted order with the help of a key. | |
| dict1 = [ | |
| {"Name":"Karl", | |
| "Age":25}, | |
| {"Name":"Lary", | |
| "Age":39}, | |
| {"Name":"Nina", | |
| "Age":35} | |
| ] | |
| ## Using sort() | |
| dict1.sort(key=lambda item: item.get("Age")) | |
| # List sorting using itemgetter | |
| from operator import itemgetter | |
| f = itemgetter('Name') | |
| dict1.sort(key=f) | |
| # Iterable sorted function | |
| dict1 = sorted(dict1, key=lambda item: item.get("Age")) | |
| '''Output | |
| [{'Age': 25, 'Name': 'Karl'}, | |
| {'Age': 35, 'Name': 'Nina'}, | |
| {'Age': 39, 'Name': 'Lary'}] | |
| ''' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## This can be useful when you have a list containing the names of students and you want to sort all the names. | |
| # Method 1: sort() | |
| list1.sort() | |
| # Method 2: sorted() | |
| sorted_list = sorted(list1) | |
| # Method 3: Brute Force Method | |
| size = len(list1) | |
| for i in range(size): | |
| for j in range(size): | |
| if list1[i] < list1[j]: | |
| temp = list1[i] | |
| list1[i] = list1[j] | |
| list1[j] = temp | |
| print(list1) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## Taking Two Integers as input at once | |
| a,b = map(int,input().split()) | |
| print("a:",a) | |
| print("b:",b) | |
| ## Taking a List as input | |
| arr = list(map(int,input().split())) | |
| print("Input List:",arr) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## In this snippet, we take the help of inbuilt function itertools to find the square of every integer in a given range. | |
| # METHOD 1 | |
| from itertools import repeat | |
| n = 5 | |
| squares = list(map(pow, range(1, n+1), repeat(2))) | |
| print(squares) | |
| # METHOD 2 | |
| n = 6 | |
| squares = [i**2 for i in range(1,n+1)] | |
| print(squares) | |
| """Output | |
| [1, 4, 9, 16, 25] | |
| """ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment