Codice Python (flow + soluzione)
from graphviz import Digraph
def crea_diagramma_pari(nome_file="diagramma_colonna_pari"):
dot = Digraph(comment="Colonna con più pari", graph_attr={"rankdir":"TB"})
# Nodi
dot.node("S","Start")
dot.node("I","Input: matrice M (m×n)")
dot.node("A","best_count=-1\\nbest_col=-1\\ncol=0")
dot.node("C1","col < n ?")
dot.node("B","count=0\\nrow=0")
dot.node("C2","row < m ?")
dot.node("EV","M[row][col] % 2 == 0 ?")
dot.node("INC","count = count + 1")
dot.node("RUP","row = row + 1")
dot.node("CMP","count > best_count ?")
dot.node("UPD","best_count = count\\nbest_col = col")
dot.node("CUP","col = col + 1")
dot.node("O","Output: best_col")
dot.node("T","Stop")
# Archi
dot.edge("S","I"); dot.edge("I","A"); dot.edge("A","C1")
dot.edge("C1","B",label="Sì"); dot.edge("C1","O",label="No"); dot.edge("O","T")
dot.edge("B","C2")
dot.edge("C2","EV",label="Sì"); dot.edge("C2","CMP",label="No")
dot.edge("EV","INC",label="Sì"); dot.edge("EV","RUP",label="No")
dot.edge("INC","RUP"); dot.edge("RUP","C2")
dot.edge("CMP","UPD",label="Sì"); dot.edge("CMP","CUP",label="No")
dot.edge("UPD","CUP"); dot.edge("CUP","C1")
dot.render(filename=nome_file, directory="/var/www/eternia", format="png", cleanup=True)
print(f"Diagramma salvato: /var/www/eternia/{nome_file}.png")
def colonna_con_piu_pari(M):
m, n = len(M), len(M[0])
best_count, best_col = -1, -1
for col in range(n):
count = 0
for row in range(m):
if M[row][col] % 2 == 0:
count += 1
if count > best_count:
best_count, best_col = count, col
return best_col
if __name__ == "__main__":
crea_diagramma_pari()
M = [
[2, 1, 5, 9],
[4, 2, 6,10],
[6, 3, 7,11],
[8, 4, 8,12],
]
print("Output:", colonna_con_piu_pari(M)) # 0