CODE EXAMPLES


Here, you'll find a collection of code samples for various applications and libraries. These snippets are designed to be a quick and easy way to add specific functionality to your code.


Skip to a subsection :

  1. Some libraries : itertools, sympy, google search, translate
  2. Random
  3. Creating data structures
  4. Slicing and indexing
  5. Time
  6. Coding for common questions
  7. Converting objects
  8. Working with files and directories
  9. Loops
  10. Matplotlib
  11. Decorators
  12. Images
  13. Other


Some libraries

Itertools

import itertools
flowers = ['orchid','tulip','rose','lily']
letters = ['A','B','C']
numbers = [1,2,3]
def FuncAdd(a,b):
    return a+b

# Creates all the combinations of 3 members
for combination in itertools.combinations(flowers,3):
    print(combination) 
# prints :
# ('orchid', 'tulip', 'rose')
# ('orchid', 'tulip', 'lily')
# ...

# Creates all the combinations of 3 members and allows elements to be repeated
for combination in itertools.combinations_with_replacement(flowers,3):
    print(combination)
# prints :
# ('orchid', 'orchid', 'lily')
# ('orchid', 'tulip', 'tulip') ...
    

# Creates all the permutations
for permutation in itertools.permutations(flowers):
    print(permutation)
# prints :
# ('orchid', 'tulip', 'rose', 'lily')
# ('orchid', 'tulip', 'lily', 'rose')
# ...

# Creates the cartesian product
for prod in itertools.product(letters,numbers):
    print(prod) # prints ('A', 1) ('A', 2)  ('A', 3)  ('B', 1) ...

# Repeats an object 3 times
for i in itertools.repeat('abc',3):
    print(i) 
# prints : 
# abc
# abc
# ...

# Accumaltes results of a function
for i in itertools.accumulate(numbers,FuncAdd):
 print(i)
# prints :
# 1
# 3
# 6

# Cumputes a function 
numbers=[(1,2),(3,4),(5,6)]
for result in itertools.starmap(FuncAdd,numbers):
    print(result) 
# prints :
# 3
# 7
# 11

calculating the derivative of a symbolic expression with sympy

import sympy as sp
x = sp.symbols('x')
f = sp.cos(x)**2
f_prime = sp.diff(f, x)
print(f_prime)
# prints : -2*sin(x)*cos(x)

Google Search library

from googlesearch import search
results = search("python", num_results=10,lang="en",advanced=True)
for result in results:
	print(result)

Translate library

from translate import Translator
translator= Translator(from_lang="en",to_lang="de",provider=”mymemory)
translation = translator.translate("What time is it ?")
print(translation)

pdg debugger

some pdg commands : c continue, s step, n next, q quit, l list...

import dbg
c = 3
print(globals())
breakpoint()
def function(a,b):
    s = 0
    for i in range(4):
        s+= a * b + c * i
    print(locals())
    print(s)
function(2,3)

Random

random library :

import random
colors = ['Red', 'Orange', 'Yellow','Blue']
random.sample(colors,3) # takes 3 elements of colors sequence
random.choice(colors) # Choose a random element from colors sequence
weights = [0.7, 0.1,0.1,0.1]  
random.choices(colors, weights, k=2) #  Choose 2 random elements with the probabilities of weights list
random.shuffle(colors) # Shuffle the list of elements
random.randint(7,11) # Returns a random selected integer between 7 and 11
random.randrange(7,11) # Returns a random element from the range, upper bound exclusive
random.uniform(7,11)  # Returns a random floating-point number between 7 and 11, inclusive
random.random() # returns a random floating-point number between 0 and 1.
random.float()

Creating data structures

Creating random data structures :

# creating a pandas dataframe time series :
dates = pd.date_range("1 1 2023", periods=365, freq="D")
values=np.random.rand(365,1)
df=pd.DataFrame(data=values,index=dates,columns=['values'])

# creating a pandas dataframe with headers
data = np.random.rand(5, 2)
df = pd.DataFrame(data, columns=['Column1', 'Column2'])

# creating a products pandas dataframe with categories and values
data = []  
for i in range(n):
    data.append({'Product':'product'+str(i),'Category':random.choice(['A','B','C','D']), 'Value':random.randint(0,1000)})
    df = pd.DataFrame(data)

# creating numpy arrays of dimension 1,2 and 3 :
arr1D=np.random.randint(0, 10, size = (4,))
arr2D=np.random.randint(0, 10, size = (2,4))
arr3D=np.random.randint(0, 10, size = (2,2,3))

Creating random customer, product and sales dataframes with faker :

from faker import Faker
import pandas as pd
import random
fake = Faker()
 
def customers(n):
    """creating a pandas customer dataframe"""
    customer_data = []
    for i in range(n):
        customer_data.append({
            'Customer Number': fake.unique.random_int(min=10000, max=99999),
            'Customer Name': fake.unique.company()
        })
    customers_df = pd.DataFrame(customer_data)
    return customers_df

def products(n):
    """creating a pandas products dataframe"""
    product_data = []
    for i in range(n):
        product_data.append({
            'Product Number': fake.unique.numerify(text='%######'),
            'Product Name': '_'.join(fake.words(nb=2))
        })
    products_df = pd.DataFrame(product_data)
    return products_df
    
def sales(n,customer_data,product_data):
"""creating a pandas sales dataframe using results of the above functions """
    sales_data = []
    for i in range(n):
        sales_data.append({
            'Customer Number':random.choice(customer_data['Customer Number'].tolist()),
            'Product Number':random.choice(product_data['Product Number'].tolist()),
            'Sales':fake.pyfloat(right_digits=2, positive=True,min_value=500,max_value=500000)
        })
    sales_df = pd.DataFrame(sales_data)
    return sales_df
        
# calling the above functions to create dataframes
customer_data = customers(20)
product_data = products(30)
sales_data = sales(5,customer_data,product_data)
num_rows = len(sales_data)  # Number of rows in the existing dataframe
random_dates = [fake.date_between(start_date='-1y', end_date='today') for _ in range(num_rows)]
sales_data['Random Date'] = random_dates
    

create periodic signals

from matplotlib import pyplot as plt
import numpy as np
x = np.linspace(-10,10,500)
ysine = np.cos(x)
ysquare = np.where(ysine>0,1,-1)
ysawtooth = x%2-1
ytriangle = x%2-1
ytriangle = np.where(ytriangle>0,ytriangle,-ytriangle)
fig,ax=plt.subplots(4,1,sharex=True)
ax[0].plot(x,ysquare)
ax[1].plot(x,ysawtooth)
ax[2].plot(x,ytriangle)
ax[3].plot(x,ysine)
plt.show()

Create specific arrays :

 # Each element is a tuple (i, j) , i and j represent the row and column index :
arr = np.empty((4,4),dtype=tuple)
for i in range(arr.shape[0]):
    for j in range(arr.shape[1]):
        arr[i, j] = (i, j)

# Each element is a tuple (i, j) , i and j represent the row and column index ( other option ):
m = np.random.randint(1,4,9).reshape(3,3)
new_arr = np.zeros_like(m,dtype=object)
for index,value in np.ndenumerate(m):
	new_arr[index[0]][index[1]]=(index[0],index[1])


# Creating a design matrix by adding ones to an existing array:
arr = np.array([[2, 1], [3, 4]])
design_arr = np.hstack((np.ones((arr.shape[0], 1)), arr))
print (design_arr) # prints  array([[1., 2., 1.],[1., 3., 4.]])

Create an array of points with meshgrid :

# 2D points
x = np.linspace(1,5,5)
y = np.linspace(1,5,5)
X,Y = np.meshgrid(x, y)
grid = np.stack((X.flatten(), Y.flatten()), axis=1)
print(grid.shape) # prints (25, 2)

# 3D points
x = np.linspace(1,5,5)
y = np.linspace(1,5,5)
z = np.linspace(1,5,5)
X,Y,Z=np.meshgrid(x, y,z)
grid = np.stack((X.flatten(), Y.flatten(), Z.flatten()), axis=1)
print(grid.shape) # prints (125,3)


Slicing and indexing

# boolean indexing with numpy
a = np.array([-1,2,-2,3,4])
b = a>1
print(a[b]) # prints array([2, 3, 4])

# get every nth element 
a = np.arange(0,11,1) 
print(a) # prints [ 0  1  2  3  4  5  6  7  8  9 10 ]
print(a[::2]) # prints [ 0  2  4  6  8 10]

# get elements at odd and even indices :
even = a[::2]
odd = a[1::2]

# get the first n elements
a[:3]

# get the first n columns and first n lines of a 2D numpy array :
a[:n,:n]

# get the n last element(s)
a[-n]

# get all elements except the last one
a[:-1]

# remove the first n elements
a[:n] = []

# reverse elements
a[::-1]

# cloning a list
mylist = [1,3,7]
new_list = mylist[:]

# circular indexing
mylist=['a','b','c']
for i in range(5):
    print(mylist[i % len(mylist)])



Time

time library :

import time
time.time()
time.ctime(time.time()) # convert a timestamp into a human-readable string 
time.sleep(2) # # Pause the execution for 2 seconds

# Measuring Execution Time
start_time = time.time()
for i in range(1, 100000):
    pass
end_time = time.time()
execution_time = end_time - start_time

datetime library :

import datetime
# now
now = datetime.now()
print(now) # prints 2023-04-29 14:17:44.726348
print(now.day, now.month, now.year,
       now.hour,now.minute, 
       now.microsecond) # prints 29 4 2023 14 17 726348

#  datetime object -> string
from datetime import datetime as dt
t = dt.now()
t_str = t.strftime(""%a"") # Tue
t_str = t.strftime(""%A"") # Tuesday
t_str = t.strftime(""%w"") # 2
t_str = t.strftime(""%m"") # 11
t_str = t.strftime(""%b"") # Nov
t_str = t.strftime(""%B"") # November
t_str = t.strftime(""%y"") # 23
t_str = t.strftime(""%Y"") # 2023
t_str = t.strftime(""%d-%B-%Y"") # 28-November-2023
t_str = t.strftime(""%Y-%m-%d %H:%M:%S"") # 2023-11-28 13:38:09

# string -> date object :
date_string = "2022-01-01 12:30:00"
date_object = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
# creating a date object using datetime constructor
my_datetime = datetime.datetime(2023, 4, 29, 12, 30, 0)
# adding days, hours, to a given datetime object
one_day_later = my_datetime + datetime.timedelta(days=2)
two_hours_earlier = my_datetime - datetime.timedelta(hours=5)

calendar :

import calendar
# Generate a text-based calendar for a given month
year = 2023
month = 7
print(calendar.month(year,month))

# Generate a text-based calendar for a given year
year = 2023
print(calendar.calendar(year))

Adding the current date and time in a file name string :

from datetime import datetime
now = datetime.now() 
time = now.strftime("%Y-%m-%d_%H-%M-%S")
filename = f"C:\\myFolder\\myFile{time}.txt"

# using a variable folder name :   
now = datetime.now() 
time = now.strftime("%Y-%m-%d_%H-%M-%S")
FOLDER = r'C:\Users\myFolder\\' # note the trailing \\
file = FOLDER + f"myFile{time}.png"

# using a a function :
FOLDER = r'C:\Users\Me....myfolder\\'
def filename(folder:str = FOLDER)-> str:
    now = datetime.now() 
    time = now.strftime("%Y-%m-%d_%H-%M-%S")
    file = FOLDER+f"myfile{time}.png"
    return file

# or
import datetime
now = datetime.datetime.now()
...

Coding for common questions

Where is Python installed ?

import sys
print(sys.executable)

pip : version, upgrade

# in command line   :
cd C:\Users\Me\AppData\Local\Programs\Python\Python311\Scripts # path depends on your configuration
pip --version # return pip version
pip install --upgrade pip # upgrade pip

Is this library imported ?

import sys
'numpy' in sys.modules


Converting objects

Converting strings, lists, sets, arrays :

# Strings to ...
s = 'hello'
a = list(s) # to list ['h', 'e', 'l', 'l', 'o']
b = set(s) # to set, removes duplicates {'h', 'l', 'e', 'o'}
c = tuple(s) # to tuple ('h', 'e', 'l', 'l', 'o')
s2 = 'h-e-l-l-o'
d = np.array(s2.split('-')) # to numpy array

# Lists to ...
mylist = [10,100,1000]
a = set(mylist) # to set, removes duplicates
b = tuple(mylist) # to tuple 
c = str(mylist) # to string
d = np.array(mylist) # to numpy array

# Sets to ...
myset={3,4,5}
a = list(myset) # to list
b = tuple(myset) # to tuple
c = str(myset) # to string
d = np.array(myset) # to numpy array

# dictionaries to  ...
my_dict = {'file1' : 1.1, 'file2' : 2, 'file3' :0.5}
my_list_keys = list(my_dict.keys()) # keys to list
my_list_values = list(my_dict.values()) # values to list

# numpy array to list:
arr = np.ndarray([1,2,3])
arr = arr.tolist()

# dataframe to numpy array ( doesn't include the headers) :
arr = df.values

Converting meshgrid to [x,y] arrays :

This script takes 3 points, the coordinates of which are stored in arrays 'x' and 'y'. It then uses 'meshgrid' to create a grid of 3x3 points, and the generated coordinates by 'meshgrid' are arranged in the form of a sequence of arrays [x, y, z] for each point.

import numpy as np
x = np.array([1,2,3])
y = np.array([4,5,6])
X, Y = np.meshgrid(x,y)
sequence = np.vstack((X.flatten(),Y.flatten())).T

Converting angles :

import numpy as np
# from radians to degrees 
angle = 3.1416
np.rad2deg(angle) 
# from degrees to radians
angle = 180
np.radians(angle)

Converting images to arrays and arrays to images :

From PIL import Image
import numpy as np
# from iamge to array
i = Image.open(f)
a = np.asarray(i)

# from array to image
arr = arr.astype(np.uint8)
i = Image.fromarray(arr)

Converting datatime objects to strings

from datetime import datetime
dt = datetime.now()
date_str1 = dt.strftime('%Y-%m-%d')
print(date_str1) # prints '2023-06-26'
date_str2 = dt.strftime('%d-%b-%Y')
print(date_str2) # prints '26-Jun-2023'
date_str3 = dt.strftime('%B %d, %Y')
print(date_str3) # prints 'June 26, 2023'
date_str4 = dt.strftime('%d %B %Y')
print(date_str3) # prints '26 June 2023'

Working with files and directories

Files :

myFile=r'C:/users/file.txt'
f = open(myFile,'r') # r = read
f = open(myFile,'w') # w = write , creates file if doesn't exist
f = open(myFile,'a') # a = append 
f.close 
f.read() # reads file and returns a string 
f.readline() # reads a single line from the file, returns a string
f.readlines() # reads file and returns a list of strings, 1 string per line
f.readlines() [n] # read the n+1th line
f.readlines()[:10] # Extract the first 10 lines 

# create a file and write 3 lines
with open('C:/Users/example.txt', 'w') as file:
    file.write('line1\n')
    file.write('line2\n')
    file.write('line3\n')

Files and directories with os library :

myFolder=r'C:/users/'
# list of all files and directories in the specified folder :
os.listdir(myFolder) 
# returns True if the specified path exists :
os.path.exists(myFolder)
# returns a tuple containing the head and tail parts of the specified path :
os.path.split(myFolder)
# creates a new directory with the specified name
os.makedirs(fo+'\\newFolder')
# creates a new directory and any necessary parent directories :
os.makedirs(myFolder++'\\newFolder1\\newFolder2')
# renames a file or directory from old to new :
os.rename('old', 'new') 
 # returns the current working directory as a string :
os.getcwd()
# changes the current working directory to the specified path
os.cwd('newpath')
# returns the name of the operating system
os.name

Rename files of a directory :

import os 

    def rename(folder:str, extension:str, name:str='myfile'):
        files = [os.path.join(folder, file) for file in os.listdir(folder) if file.endswith(extension) ]
        for index,file in enumerate(files):
            new_name = os.path.join(folder,name+str(index).zfill(4) + extension)
            os.rename(file,new_name)
    
    folder = r'C:\Users\....\\'
    extension ='.png'
    name ='myfile'
    rename(folder = folder , extension = extension, name = name)

Creating zip archives

# This script zips PNG files from a specific folder, and creates a zip archive in the provided destination directory.

import os
import zipfile

# Folder containing files to be added to the zip
folder_path = r'C:\Users\...\folder1'
# Name of the zip file
zip_file_name = "my_files.zip"
# Destination directory for creating the zip file
zip_path = r'C:\Users\..\folder2'

with zipfile.ZipFile(os.path.join(zip_path, zip_file_name), "w") as zip_file:
    for file_name in os.listdir(folder_path):
        if file_name.endswith(".png"):
            # Combine the folder path and file name to create the full file path
            file_path = os.path.join(folder_path, file_name)
            # arcname specifies the name under which the file will be added to the zip archive
            zip_file.write(file_path, arcname=file_name) 

Loops

# loop over multiple iterables simultaneously :
days = ['Mon','Tue','Wed']
fruits = ['Apple', 'Orange', 'Banana']
colors = ['Blue', 'Yellow', 'Green']
for day, fruit,color in zip(days, fruits, colors):
    print(day, fruit, color)
# prints :
# Mon Apple Blue
# Tue Orange Yellow
# Wed Banana Green

# loop over multiple iterables of different lengths    
from itertools import zip_longest
days = ['Mon', 'Tue', 'Wed']
fruits = ['Apple', 'Orange']
for day, fruit in zip_longest(days, fruits, fillvalue='N/A'):
    print(day, fruit)
# prints :
# Mon Apple
# Tue Orange
# Wed N/A

# loop with enumerate :
fruits = ['Apple', 'Orange', 'Banana']
for index, fruit in enumerate(fruits):
    print(index,fruit)
# prints :
# 0 Apple
# 1 Orange
# 2 Banana

# loop in reverse :
days = ['Mon', 'Tue', 'Wed']
for day in reversed(days):
    print(day)
    
# recursive function :
def fibonacci(p):
    if p in (0,1):
        return 1
    else:
        return fibonacci(p-1) + fibonacci(p-2)    

Decorators

# exemple 1 : fibonacci with timer

def timer(func):
import time
def wrapper(n):
    start_time = time.time()
    result = func(n)
    end_time = time.time()
    print(f"Elapsed time: {end_time - start_time} seconds")
    return result
return wrapper

@timer
def fibonacci(p):
if p in (0,1):       
    return 1
else:     
    return fibonacci(p-1) + fibonacci(p-2)
        
print(fibonacci(15))


# example 2 : plot values generated by a function

import numpy as np
from matplotlib import pyplot as plt

def plot(func):
    fig,ax = plt.subplots()
    def wrapper(n):
        fig.suptitle(str(n)+' values',color='blue')
        x,y = func(n)
        plt.plot(x,y,color='red')
        plt.show()
    return wrapper

@plot
def values(n):
    x = np.linspace(-1,1,n)
    y = np.cos(x)
    return x,y

values(10)

Images

Pillow :

# write some text in the center of a new image
from PIL import Image, ImageDraw, ImageFont
FOLDER = r'C:\myfolder'
year = 2023
c = calendar.calendar(year)  
image_width = 900
image_height = 1200
image = Image.new("RGB", (image_width, image_height))
text = "Hello World!"  
text_color = (255, 255, 255)  # RGB color value for the text (white in this example)
font_size = 40  
font = ImageFont.truetype("arial.ttf", font_size)  # Specify the font and its size
draw = ImageDraw.Draw(image)
text_width, text_height = draw.textsize(text, font=font)
text_position = ((image_width - text_width) // 2, (image_height - text_height) // 2)
draw.text(text_position, text, font=font, fill=text_color)
filename = r'C:\Users\Me\'image.png'
image.save(filename)    


Other

Unpack and assign :

myList = [1, 2, 3, 4, 5]

# assigns some values and ignore the rest :
a,b,*_ = myList 

# assigns some values and collects remaining elements, packs into a list :
a, b, *c = myList 
print(c) # prints [3, 4, 5]

# 1 list of 2-tuples (x,y) -> 1 tuple of x and 1 tuple of y  
coordinates=[(1,2),(3,4),(5,6)]
x,y = zip(*coordinates)
print(x) # prints (1, 3, 5)
print(y) # prints (2, 4, 6)

# 1 tuple of x and 1 tuple of y -> 1 list of 2-tuples (x,y)
x = (1, 3, 5)
y = (2, 4, 6)
coordinates = list(zip(x, y))
print(coordinates)  # prints [(1, 2), (3, 4), (5, 6)]

Swap 2 elements of a string :

def swapstr(strng, index1, index2):
    list_strng = list(strng)
    element1, element2 = list_strng[index1], list_strng[index2]
    list_strng[index1], list_strng[index2] = element2, element1
    new_strng = ''.join(list_strng)
    return new_strng 

Move a string element :

def move_str_element(strng, index_from, index_to):
    list_strng=list(strng)
    element = list_strng[index_from]
    if index_from - index_to > 0 :
        shift_remove, shift_insert = 1,0
    else : 
        shift_remove, shift_insert = 0, 1
    list_strng.insert(index_to + shift_insert  , element)
    list_strng.pop(index_from + shift_remove)
    new_strng = ''.join(list_strng)
    return new_strng