Python Random Notes
Using max heap
The post is taken from here.
We use heapq class to implement Heaps in Python. By default Min Heap is implemented by this class.
To implement MaxHeap not limiting to only numbers but any type of object(String, Tuple, Object etc) we should
Create a Wrapper class for the item in the list.
Override the \_lt\_ dunder method to give inverse result.
Following is the implementation of the method mentioned here.
"""
Python3 program to implement MaxHeap Operation
with built-in module heapq
for String, Numbers, Objects
"""
from functools import total_ordering
import heapq
# why total_ordering: https://www.geeksforgeeks.org/python-functools-total_ordering/
@total_ordering
class Wrapper:
def __init__(self, val):
self.val = val
def __lt__(self, other):
return self.val > other.val
def __eq__(self, other):
return self.val == other.val
# Working on existing list of int
heap = [10, 20, 400, 30]
wrapper_heap = list(map(lambda item: Wrapper(item), heap))
heapq.heapify(wrapper_heap)
max_item = heapq.heappop(wrapper_heap)
# push item
heapq.heappush( wrapper_heap, Wrapper(400) )
# This will give the max value
print(f"Top of numbers are: {max_item.val}")
# Working on existing list of str
heap = ["this", "code", "is", "wonderful"]
wrapper_heap = list(map(lambda item: Wrapper(item), heap))
heapq.heapify(wrapper_heap)
print("The string heap elements in order: ")
while wrapper_heap:
top_item = heapq.heappop(wrapper_heap)
print(top_item.val, end=" ")
# This code is contributed by Supratim Samantray (super_sam)
Convert to ASCII and back
The function ord()
gets the int value of the char. And in case you want to convert back after playing with the number, function chr()
does the trick.
>>> ord('a')
97
>>> chr(97)
'a'
initializing 2D array
arr = [[0 for i in range(cols)] for j in range(rows)]
using deque
Deque (Doubly Ended Queue) in Python is implemented using the module “collections“. Deque is preferred over a list in the cases where we need quicker append and pop operations from both the ends of the container, as deque provides an O(1)
time complexity for append and pop operations as compared to a list that provides O(n)
time complexity.
Methods:
append()
: This function is used to insert the value in its argument to the right end of the deque.appendleft()
: This function is used to insert the value in its argument to the left end of the deque.pop()
: This function is used to delete an argument from the right end of the deque.popleft()
: This function is used to delete an argument from the left end of the deque.Deque[0]
: We can access the front element of the deque using indexing with de[0].Deque[-1]
: We can access the back element of the deque using indexing with de[-1].
Example Code:
# importing "collections" for deque operations
import collections
# initializing deque
de = collections.deque([1, 2, 3])
print("deque: ", de)
# using append() to insert element at right end
# inserts 4 at the end of deque
de.append(4)
# printing modified deque
print("\nThe deque after appending at right is : ")
print(de)
# using appendleft() to insert element at left end
# inserts 6 at the beginning of deque
de.appendleft(6)
# printing modified deque
print("\nThe deque after appending at left is : ")
print(de)
Generate random number
Python has a built-in module called random
that can be used to make random numbers, random.randrange(start, stop, step)
: step
, an integer specifying the incrementation. Default 1.
Import the random module, and display a random number between 1 and 9:
import random
print(random.randrange(1, 10))
strings
in Python are immutable
You cannot modify individual characters directly, otherwise, you will get the error:TypeError: 'str' object does not support item assignment
. One way is to convert it to a list:
s = "hello"
s_list = list(s) # Convert string to list
s_list[0] = "H"
Function arguments
In Python, function arguments are passed by object reference. This behavior can be thought of as "pass by assignment", which lies between the traditional notions of pass-by-reference and pass-by-value.
Here’s how it works:
- Mutable objects (like lists, dictionaries, sets) can be changed in place inside a function.
- Immutable objects (like integers, strings, tuples) cannot be changed inside a function — only reassigned.
The post is published under CC 4.0 License.