7 Helpful Python Snippets

 ANAGRAMS

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

from collections import Counter
def anagram(first, second):
    return Counter(first) == Counter(second)
anagram( "abcd3", "3acdb") # True

This method can be used to check if two strings are anagrams.


ALL UNIQUE

The following method checks whether the given list has duplicate elements. It uses the property of set which removes duplicate elements from the list.


def all_unique(lst):
    return len(lst) == len( set(lst))
x = [1,1,2,2,3,2,3,4,5,6]
y = [1,2,3,4,5]
all_unique(x) # False
all_unique(y) # True



CAPITALIZE FIRST LETTERS

s = "live to code"
print(s.title()) # Live to code

This snippet simply uses the method title() to capitalize the first letters of every word in a string.


BYTE SIZE
The following method returns the length of a string in bytes.

def byte_size(string):
    return(len(string.encode('utf-8')))
byte_size('Hii') # 3
byte_size('Tech with fahad') # 15


PRINT A STRING N TIMES
n = 3
s="Hello"
print(s * n) # Hello Hello Hello

This snippet can be used to print a string n times without having to use loops to do it.


CHUNK

The following method chunks a list into smaller lists of a specified size.
def chunk(list, size):
    return [list[i:i+size] for i in range(0, len(list), size)]


MEMORY

import sys
var = {"name":"john"}
print(sys.getsizeof(var)) # 232

This snippet can be used to check the memory usage of an object.

Comments

Popular posts from this blog

LeetCode 350: Intersection of Two Arrays II

LeetCode 35: Search Insert Position

LeetCode 217: Contains Duplicate