ab / col.py
theapps's picture
Upload 36 files
ca165c7 verified
import csv
import numpy as np
import random # Import the random module
def change_fourth_occurrence(matrix):
for col in range(len(matrix[0])):
count = 1
for row in range(1, len(matrix)):
if matrix[row][col] == matrix[row - 1][col]:
count += 1
else:
count = 1
if count == 4:
current_number = matrix[row][col]
# Generate a random number within the range [current_number-1, current_number+1]
next_number = random.choice([current_number - 1, current_number + 1])
matrix[row][col] = next_number
count = 1
# Post-processing: Ensure there are no negative numbers in the matrix
matrix[matrix < 0] = 0
# Read the matrix from CSV
input_matrix = []
with open('matrix2.csv', 'r') as file:
csv_reader = csv.reader(file)
for row in csv_reader:
input_matrix.append([int(num) for num in row])
# Convert the matrix to a NumPy array for easy column indexing
input_matrix = np.array(input_matrix)
# Call the function to modify the matrix
change_fourth_occurrence(input_matrix)
# Write the modified matrix back to CSV
with open('matrix5.csv', 'w', newline='') as file:
csv_writer = csv.writer(file)
csv_writer.writerows(input_matrix)