Skip to main content

Propositional logic with itertools

0 likes • Nov 18, 2022 • 0 views
Python
Loading...

More Python Posts

Sort a List of Strings

0 likes • Oct 15, 2022 • 2 views
Python
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))

collect dictionary

0 likes • Nov 19, 2022 • 0 views
Python
from collections import defaultdict
def collect_dictionary(obj):
inv_obj = defaultdict(list)
for key, value in obj.items():
inv_obj[value].append(key)
return dict(inv_obj)
ages = {
'Peter': 10,
'Isabel': 10,
'Anna': 9,
}
collect_dictionary(ages) # { 10: ['Peter', 'Isabel'], 9: ['Anna'] }

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)

primes numbers finder

0 likes • Mar 12, 2021 • 0 views
Python
prime_lists=[] # a list to store the prime numbers
def prime(n): # define prime numbers
if n <= 1:
return False
# divide n by 2... up to n-1
for i in range(2, n):
if n % i == 0: # the remainder should'nt be a 0
return False
else:
prime_lists.append(n)
return True
for n in range(30,1000): # calling function and passing starting point =30 coz we need primes >30
prime(n)
check=0 # a var to limit the output to 10 only
for n in prime_lists:
for x in prime_lists:
val= n *x
if (val > 1000 ):
check=check +1
if (check <10) :
print("the num is:", val , "=",n , "* ", x )
break

Color Gradient

0 likes • Mar 10, 2021 • 0 views
Python
color2 = (60, 74, 172)
color1 = (19, 28, 87)
percent = 1.0
for i in range(101):
resultRed = round(color1[0] + percent * (color2[0] - color1[0]))
resultGreen = round(color1[1] + percent * (color2[1] - color1[1]))
resultBlue = round(color1[2] + percent * (color2[2] - color1[2]))
print((resultRed, resultGreen, resultBlue))
percent -= 0.01

Calculator

0 likes • Nov 19, 2022 • 0 views
Python
""" Calculator
----------------------------------------
"""
def addition ():
print("Addition")
n = float(input("Enter the number: "))
t = 0 //Total number enter
ans = 0
while n != 0:
ans = ans + n
t+=1
n = float(input("Enter another number (0 to calculate): "))
return [ans,t]
def subtraction ():
print("Subtraction");
n = float(input("Enter the number: "))
t = 0 //Total number enter
sum = 0
while n != 0:
ans = ans - n
t+=1
n = float(input("Enter another number (0 to calculate): "))
return [ans,t]
def multiplication ():
print("Multiplication")
n = float(input("Enter the number: "))
t = 0 //Total number enter
ans = 1
while n != 0:
ans = ans * n
t+=1
n = float(input("Enter another number (0 to calculate): "))
return [ans,t]
def average():
an = []
an = addition()
t = an[1]
a = an[0]
ans = a / t
return [ans,t]
// main...
while True:
list = []
print(" My first python program!")
print(" Simple Calculator in python by Malik Umer Farooq")
print(" Enter 'a' for addition")
print(" Enter 's' for substraction")
print(" Enter 'm' for multiplication")
print(" Enter 'v' for average")
print(" Enter 'q' for quit")
c = input(" ")
if c != 'q':
if c == 'a':
list = addition()
print("Ans = ", list[0], " total inputs ",list[1])
elif c == 's':
list = subtraction()
print("Ans = ", list[0], " total inputs ",list[1])
elif c == 'm':
list = multiplication()
print("Ans = ", list[0], " total inputs ",list[1])
elif c == 'v':
list = average()
print("Ans = ", list[0], " total inputs ",list[1])
else:
print ("Sorry, invilid character")
else:
break