Skip to main content

Compute all the Permutation of a String

0 likes • May 31, 2023 • 0 views
Python
Loading...

More Python Posts

Create a Pascal’s Triangle

0 likes • May 31, 2023 • 0 views
Python
def generate_pascals_triangle(num_rows):
triangle = []
for row in range(num_rows):
# Initialize the row with 1
current_row = [1]
# Calculate the values for the current row
if row > 0:
previous_row = triangle[row - 1]
for i in range(len(previous_row) - 1):
current_row.append(previous_row[i] + previous_row[i + 1])
# Append 1 at the end of the row
current_row.append(1)
# Add the current row to the triangle
triangle.append(current_row)
return triangle
def display_pascals_triangle(triangle):
for row in triangle:
for number in row:
print(number, end=" ")
print()
# Prompt the user for the number of rows
num_rows = int(input("Enter the number of rows for Pascal's Triangle: "))
# Generate Pascal's Triangle
pascals_triangle = generate_pascals_triangle(num_rows)
# Display Pascal's Triangle
display_pascals_triangle(pascals_triangle)

UNT CSCE 2100 Assignment 6

0 likes • Nov 18, 2022 • 0 views
Python
"""
Assignment 6
The goal is to make a graph of
who bit who and who was bitten.
There should be 10 nodes and 15 edges.
3 arrows of biting each other and
3 arrows of someone biting themselves.
Networkx can not do self biting
arrows, but it is in the code.
"""
from graphviz import Digraph as DDotGraph
from graphviz import Graph as UDotGraph
import networkx as nx
from networkx.algorithms.dag import transitive_closure
import graphviz as gv
import matplotlib.pyplot as plt
import numpy as np
from numpy.linalg import matrix_power
"""
class DGraph:
def __init__(self):
self.d = dict()
def clear(self):
self.d = dict()
def add_node(self,n):
if not self.d.get(n):
self.d[n] = set()
def add_edge(self,e):
f,t=e
self.add_node(f)
self.add_node(t)
vs=self.d.get(f)
if not vs:
self.d[f] = {t}
else:
vs.add(t)
def add_edges_from(self,es):
for e in es:
self.add_edge(e)
def edges(self):
for f in self.d:
for t in self.d[f]:
yield (f,t)
def number_of_nodes(self):
return len(self.d)
def __repr__(self):
return self.d.__repr__()
def show(self):
dot = gv.Digraph()
for e in self.edges():
#print(e)
f, t = e
dot.edge(str(f), str(t), label='')
#print(dot.source)
show(dot)
# displays graph with graphviz
def show(dot, show=True, file_name='graph.gv'):
dot.render(file_name, view=show)
def showGraph(g,label="",directed=True):
if directed:
dot = gv.Digraph()
else:
dot = gv.Graph()
for e in g.edges():
print(e)
f, t = e
dot.edge(str(f), str(t), label=label)
print(dot.source)
show(dot)
def bit():
G = DGraph()
G.add_edge(("Blade","Samara"))
G.add_edge(("Shadow","Wolfe"))
G.add_edge(("Raven", "Austin"))
G.add_edge(("Blade", "Alice"))
G.add_edge(("Alice","Brandon"))
G.add_edge(("Blade", "Wolfe"))
G.add_edge(("Samara", "Robin"))
G.add_edge(("Samara", "Raven"))
G.add_edge(("Samara", "Hamed"))
G.add_edge(("Wolfe", "Blade"))
G.add_edge(("Hamed", "Samara"))
G.add_edge(("Wolfe", "Shadow"))
G.add_edge(("Brandon", "Brandon"))
G.add_edge(("Hamed", "Hamed"))
G.add_edge(("Austin", "Austin"))
showGraph(G, label="bit")
bit()
def bitten():
G=DGraph()
G.add_edge(("Samara","Blade"))
G.add_edge(("Wolfe","Shadow"))
G.add_edge(("Austin", "Raven"))
G.add_edge(("Alice","Blade"))
G.add_edge(("Brandon", "Alice"))
G.add_edge(("Wolfe", "Blade" ))
G.add_edge(("Robin", "Samara"))
G.add_edge(("Raven", "Samara"))
G.add_edge(("Hamed", "Samara"))
G.add_edge(("Blade", "Wolfe"))
G.add_edge(("Samara", "Hamed"))
G.add_edge(("Shadow", "Wolfe"))
G.add_edge(("Brandon", "Brandon"))
G.add_edge(("Hamed", "Hamed"))
G.add_edge(("Austin", "Austin"))
showGraph(G, label="bitten by")
#bitten()
family = ["Blade", "Samara", "Shadow", "Wolfe", "Raven", "Alice"]
"""
#Do transitive closure call out and the
#matrix power operation should be the same
D = nx.DiGraph()
#D.add_nodes_from("SamaraBladeWolfeShadowAliceRavenBrandonRobinHamedAustin")
D.add_edge("Blade","Samara")
D.add_edge("Shadow","Wolfe")
D.add_edge("Raven", "Austin")
D.add_edge("Blade", "Alice")
D.add_edge("Alice","Brandon")
D.add_edge("Blade", "Wolfe")
D.add_edge("Samara", "Robin")
D.add_edge("Samara", "Raven")
D.add_edge("Samara", "Hamed")
D.add_edge("Wolfe", "Blade")
D.add_edge("Hamed", "Samara")
D.add_edge("Wolfe", "Shadow")
D.add_edge("Brandon", "Brandon")
D.add_edge("Hamed", "Hamed")
D.add_edge("Austin", "Austin")
T = transitive_closure(D)
for e in D.edges(): print(e)
for n in D.nodes(): print(n)
def show(H):
nx.draw(H, with_labels=True, font_weight='bold')
plt.show()
#Use nx.to_numpy_matrix instead of nx.adjacency_matrix
# M = nx.adjacency_matrix(D)
# MT = nx.adjacency_matrix(T)
M = nx.to_numpy_matrix(D)
MT = nx.to_numpy_matrix(T)
M2 = M@M
def mPower(M, k): #M is numpy matrix
assert k >= 1
P = M
for _ in range(k):
P = P @ M
return P
def tc(M):
#compute transitive closure
pass
D1 = nx.DiGraph(M)
D2 = nx.DiGraph(M2)
print('Matrix for Original\n', M)
N = nx.to_numpy_array(D,dtype=int)
print('np_array for Original\n', N)
print('\nMatrix for Transitive Closure\n', MT)
N2 = nx.to_numpy_array(T,dtype=int)
print('np_array for Transitive Closure\n', N2)
show(D) #can use D, T, and numpy matrix power operation
show(T)
show(T)

screencap.py

0 likes • Jan 23, 2021 • 0 views
Python
"""
Take screenshots at x interval - make a movie of doings on a computer.
"""
import time
from datetime import datetime
import ffmpeg
import pyautogui
while True:
epoch_time = int(time.time())
today = datetime.now().strftime("%Y_%m_%d")
filename = str(epoch_time) + ".png"
print("taking screenshot: {0}".format(filename))
myScreenshot = pyautogui.screenshot()
myScreenshot.save(today + "/" + filename)
time.sleep(5)
#
# and then tie it together with: https://github.com/kkroening/ffmpeg-python/blob/master/examples/README.md#assemble-video-from-sequence-of-frames
#
"""
import ffmpeg
(
ffmpeg
.input('./2021_01_22/*.png', pattern_type='glob', framerate=25)
.filter('deflicker', mode='pm', size=10)
.filter('scale', size='hd1080', force_original_aspect_ratio='increase')
.output('movie.mp4', crf=20, preset='slower', movflags='faststart', pix_fmt='yuv420p')
.run()
)
"""

AnyTree Randomizer

0 likes • Apr 15, 2021 • 0 views
Python
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]

curry function

0 likes • Nov 19, 2022 • 1 view
Python
from functools import partial
def curry(fn, *args):
return partial(fn, *args)
add = lambda x, y: x + y
add10 = curry(add, 10)
add10(20) # 30

Bubble sort

0 likes • Nov 19, 2022 • 0 views
Python
# Python program for implementation of Bubble Sort
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n-1):
# range(n) also work but outer loop will repeat one time more than needed.
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
# Driver code to test above
arr = [64, 34, 25, 12, 22, 11, 90]
bubbleSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("%d" %arr[i]),