## Bitonic sort

0 likes • Nov 19, 2022
Python

## More Python Posts

```def when(predicate, when_true):  return lambda x: when_true(x) if predicate(x) else x
double_even_numbers = when(lambda x: x % 2 == 0, lambda x : x * 2)print(double_even_numbers(2)) # 4print(double_even_numbers(1)) # 1```
```def key_of_min(d):  return min(d, key = d.get)
key_of_min({'a':4, 'b':0, 'c':13}) # b```
```# Function to multiply two matricesdef multiply_matrices(matrix1, matrix2):    # Check if the matrices can be multiplied    if len(matrix1[0]) != len(matrix2):        print("Error: The number of columns in the first matrix must be equal to the number of rows in the second matrix.")        return None
# Create the result matrix filled with zeros    result = [[0 for _ in range(len(matrix2[0]))] for _ in range(len(matrix1))]
# Perform matrix multiplication    for i in range(len(matrix1)):        for j in range(len(matrix2[0])):            for k in range(len(matrix2)):                result[i][j] += matrix1[i][k] * matrix2[k][j]
return result
# Example matricesmatrix1 = [[1, 2, 3],           [4, 5, 6],           [7, 8, 9]]
matrix2 = [[10, 11],           [12, 13],           [14, 15]]
# Multiply the matricesresult_matrix = multiply_matrices(matrix1, matrix2)
# Display the resultif result_matrix is not None:    print("Result:")    for row in result_matrix:        print(row)```
```"""Assignment 6
The goal is to make a graph ofwho bit who and who was bitten.There should be 10 nodes and 15 edges.3 arrows of biting each other and3 arrows of someone biting themselves.Networkx can not do self bitingarrows, but it is in the code."""
from graphviz import Digraph as DDotGraphfrom graphviz import Graph as UDotGraphimport networkx as nxfrom networkx.algorithms.dag import transitive_closureimport graphviz as gvimport matplotlib.pyplot as pltimport numpy as npfrom 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 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 graphvizdef 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)

bit()
#bitten()
T = transitive_closure(D)
for e in D.edges(): print(e)for n in D.nodes(): print(n)
# M = nx.adjacency_matrix(D)# MT = nx.adjacency_matrix(T)M = nx.to_numpy_matrix(D)MT = nx.to_numpy_matrix(T)M2 = [email protected]
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 operationshow(T)show(T)```
```import itertools
def compute_permutations(string):    # Generate all permutations of the string    permutations = itertools.permutations(string)
# Convert each permutation tuple to a string    permutations = [''.join(permutation) for permutation in permutations]
return permutations
# Prompt the user for a stringstring = input("Enter a string: ")
# Compute permutationspermutations = compute_permutations(string)
# Display the permutationsprint("Permutations:")for permutation in permutations:    print(permutation)```
```def get_ldap_user(member_cn, user, passwrd):    '''    Get an LDAP user and return the SAMAccountName    '''    #---- Setting up the Connection    #account used for binding - Avoid putting these in version control    bindDN = str(user) + "@unt.ad.unt.edu"    bindPass = passwrd
#set some tuneables for the LDAP library.    ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW)    #ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, CACERTFILE)        conn = ldap.initialize('ldaps://unt.ad.unt.edu')    conn.protocol_version = 3    conn.set_option(ldap.OPT_REFERRALS, 0)
#authenticate the connection so that you can make additional queries    try:        result = conn.simple_bind_s(bindDN, bindPass)     except ldap.INVALID_CREDENTIALS:        result = "Invalid credentials for %s" % user        sys.exit()
#build query in the form of (uid=user)    ldap_query = '(|(displayName=' + member_cn + ')(cn='+ member_cn + ')(name=' + member_cn + '))'    ldap_info = conn.search_s('DC=unt,DC=ad,DC=unt,DC=edu', ldap.SCOPE_SUBTREE, filterstr=ldap_query)    sAMAccountName = str(ldap_info[0][1]['sAMAccountName']).replace("[b'", "").replace("']","")    return sAMAccountName```