UNT CSCE 2100 Assignment 6

0 likes • Nov 18, 2022 • 0 views
Python

More Python Posts

Create a Floyd’s Triangle

0 likes • May 31, 2023 • 0 views
Python
```def generate_floyds_triangle(num_rows):    triangle = []    number = 1    for row in range(num_rows):        current_row = []        for _ in range(row + 1):            current_row.append(number)            number += 1        triangle.append(current_row)    return triangle

def display_floyds_triangle(triangle):    for row in triangle:        for number in row:            print(number, end=" ")        print()

# Prompt the user for the number of rowsnum_rows = int(input("Enter the number of rows for Floyd's Triangle: "))
# Generate Floyd's Trianglefloyds_triangle = generate_floyds_triangle(num_rows)
# Display Floyd's Triangledisplay_floyds_triangle(floyds_triangle)```

Print pyramid pattern

0 likes • Nov 19, 2022 • 0 views
Python
`def print_pyramid_pattern(n):         # outer loop to handle number of rows    # n in this case    for i in range(0, n):             # inner loop to handle number of columns        # values changing acc. to outer loop        for j in range(0, i+1):                     # printing stars            print("* ",end="")              # ending line after each row        print("\r") print_pyramid_pattern(10)`

Topological sort

0 likes • Nov 19, 2022 • 0 views
Python
`#Python program to print topological sorting of a DAGfrom collections import defaultdict  #Class to represent a graphclass Graph:    def __init__(self,vertices):        self.graph = defaultdict(list) #dictionary containing adjacency List        self.V = vertices #No. of vertices      # function to add an edge to graph    def addEdge(self,u,v):        self.graph[u].append(v)      # A recursive function used by topologicalSort    def topologicalSortUtil(self,v,visited,stack):          # Mark the current node as visited.        visited[v] = True          # Recur for all the vertices adjacent to this vertex        for i in self.graph[v]:            if visited[i] == False:                self.topologicalSortUtil(i,visited,stack)          # Push current vertex to stack which stores result        stack.insert(0,v)      # The function to do Topological Sort. It uses recursive     # topologicalSortUtil()    def topologicalSort(self):        # Mark all the vertices as not visited        visited = [False]*self.V        stack =[]          # Call the recursive helper function to store Topological        # Sort starting from all vertices one by one        for i in range(self.V):            if visited[i] == False:                self.topologicalSortUtil(i,visited,stack)          # Print contents of stack        print(stack)  g= Graph(6)g.addEdge(5, 2);g.addEdge(5, 0);g.addEdge(4, 0);g.addEdge(4, 1);g.addEdge(2, 3);g.addEdge(3, 1);  print("Following is a Topological Sort of the given graph")g.topologicalSort()`

Multiply Two Matrices

0 likes • May 31, 2023 • 0 views
Python
```# 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)```

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 rowsnum_rows = int(input("Enter the number of rows for Pascal's Triangle: "))
# Generate Pascal's Trianglepascals_triangle = generate_pascals_triangle(num_rows)
# Display Pascal's Triangledisplay_pascals_triangle(pascals_triangle)```

check prop lambda

0 likes • Nov 19, 2022 • 0 views
Python
`def check_prop(fn, prop):  return lambda obj: fn(obj[prop])  check_age = check_prop(lambda x: x >= 18, 'age')user = {'name': 'Mark', 'age': 18}check_age(user) # True`