• Apr 15, 2021 •NoahEaton
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]
• Sep 6, 2020 •C S
0 likes • 2 views
def Fibonacci(n): if n<0: print("Incorrect input") # First Fibonacci number is 0 elif n==1: return 0 # Second Fibonacci number is 1 elif n==2: return 1 else: return Fibonacci(n-1)+Fibonacci(n-2) # Driver Program print(Fibonacci(9))
• Oct 15, 2022 •CodeCatch
1 like • 2 views
my_list = ["blue", "red", "green"] #1- Using sort or srted directly or with specifc keys my_list.sort() #sorts alphabetically or in an ascending order for numeric data my_list = sorted(my_list, key=len) #sorts the list based on the length of the strings from shortest to longest. # You can use reverse=True to flip the order #2- Using locale and functools import locale from functools import cmp_to_key my_list = sorted(my_list, key=cmp_to_key(locale.strcoll))
• Jun 1, 2023 •CodeCatch
0 likes • 1 view
filename = "data.txt" data = "Hello, World!" with open(filename, "a") as file: file.write(data)
• Nov 19, 2022 •CodeCatch
def print_x_pattern(size): i,j = 0,size - 1 while j >= 0 and i < size: initial_spaces = ' '*min(i,j) middle_spaces = ' '*(abs(i - j) - 1) final_spaces = ' '*(size - 1 - max(i,j)) if j == i: print(initial_spaces + '*' + final_spaces) else: print(initial_spaces + '*' + middle_spaces + '*' + final_spaces) i += 1 j -= 1 print_x_pattern(7)
from time import sleep def delay(fn, ms, *args): sleep(ms / 1000) return fn(*args) delay(lambda x: print(x), 1000, 'later') # prints 'later' after one second