Skip to main content

Topological sort

Nov 19, 2022CodeCatch
Loading...

More Python Posts

clamp number

Nov 19, 2022CodeCatch

0 likes • 0 views

def clamp_number(num, a, b):
return max(min(num, max(a, b)), min(a, b))
clamp_number(2, 3, 5) # 3
clamp_number(1, -1, -5) # -1

AnyTree Randomizer

Apr 15, 2021NoahEaton

0 likes • 0 views

import anytree as at
import random as rm
# Generate a tree with node_count many nodes. Each has a number key that shows when it was made and a randomly selected color, red or white.
def random_tree(node_count):
# Generates the list of nodes
nodes = []
for i in range(node_count):
test = rm.randint(1,2)
if test == 1:
nodes.append(at.Node(str(i),color="white"))
else:
nodes.append(at.Node(str(i),color="red"))
#Creates the various main branches
for i in range(node_count):
for j in range(i, len(nodes)):
test = rm.randint(1,len(nodes))
if test == 1 and nodes[j].parent == None and (not nodes[i] == nodes[j]):
nodes[j].parent = nodes[i]
#Collects all the main branches into a single tree with the first node being the root
for i in range(1, node_count):
if nodes[i].parent == None and (not nodes[i] == nodes[0]):
nodes[i].parent = nodes[0]
return nodes[0]

return byte size

Nov 19, 2022CodeCatch

0 likes • 1 view

def byte_size(s):
return len(s.encode('utf-8'))
byte_size('😀') # 4
byte_size('Hello World') # 11

convert bytes to a string

Jun 1, 2023CodeCatch

0 likes • 1 view

bytes_data = b'Hello, World!'
string_data = bytes_data.decode('utf-8')
print("String:", string_data)

Bogo Sort

Nov 19, 2022CodeCatch

0 likes • 0 views

# Python program for implementation of Bogo Sort
import random
# Sorts array a[0..n-1] using Bogo sort
def bogoSort(a):
n = len(a)
while (is_sorted(a)== False):
shuffle(a)
# To check if array is sorted or not
def is_sorted(a):
n = len(a)
for i in range(0, n-1):
if (a[i] > a[i+1] ):
return False
return True
# To generate permuatation of the array
def shuffle(a):
n = len(a)
for i in range (0,n):
r = random.randint(0,n-1)
a[i], a[r] = a[r], a[i]
# Driver code to test above
a = [3, 2, 4, 1, 0, 5]
bogoSort(a)
print("Sorted array :")
for i in range(len(a)):
print ("%d" %a[i]),

Remove i'th character

Nov 19, 2022CodeCatch

0 likes • 0 views

# Python code to demonstrate
# method to remove i'th character
# Naive Method
# Initializing String
test_str = "CodeCatch"
# Printing original string
print ("The original string is : " + test_str)
# Removing char at pos 3
# using loop
new_str = ""
for i in range(len(test_str)):
if i != 2:
new_str = new_str + test_str[i]
# Printing string after removal
print ("The string after removal of i'th character : " + new_str)