Source Code
print("Unit 6")
myName = "" # add your name
print("Name: " + myName)
def main():
done = False
while not done:
print("Welcome to the Main Function")
print("Menu")
print("E1 - Example 1")
print("Q - Quit")
choice = input("Choice: ")
match choice:
case "E1":
example1()
case "E2":
example2()
case "E3":
example3()
case "E4":
example4()
case "Q":
print("Quitting!")
done = True
# default case
case _:
print("Invalid, try again!")
# define Example 1 Function
def example1():
print("Example 1")
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
# iterate over each element of the 2D list
for row in grid:
for element in row:
print(element, end=" ")
print()
# iterate over each row
for row in grid:
print(row)
# iterate over the first column
for row in grid:
print(row[0])
# define Example 2 Function
def example2():
print("Example 2")
rows, cols = 3, 3
table = [[0 for c in range(cols)] for r in range(rows)]
print("Original")
print(table)
print("Updated")
table[0][0] = 1
print(table)
table2 = []
for r in range(rows):
row = []
for c in range(cols):
row.append(0)
table2.append(row)
# define Example 3 Function
def example3():
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Sum of all values
print("Sum of Values")
print(sum(sum(row) for row in matrix))
# Sum of all values
total = 0
for row in matrix:
total += sum(row)
print("Sum of Values (again)")
print(total)
# define Example 4 Function
def example4():
matrix = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10]
]
print("Original")
print(matrix)
print("Flatten")
flat = [num for row in matrix for num in row]
print(flat)
# equivalent
flat2 = []
for row in matrix:
for num in row:
flat2.append(num)
print(flat2)
main()Last updated