Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,907 questions

51,839 answers

573 users

How to check if a matrix columns contain numbers without repetition in Python

3 Answers

0 votes
def are_columns_unique(matrix):
    if not matrix or not matrix[0]:
        return True  # Handle empty matrix

    rows = len(matrix)
    cols = len(matrix[0])

    for col in range(cols):
        seen = set()
        for row in range(rows):
            if matrix[row][col] in seen:
                return False  # Duplicate found in the column
            seen.add(matrix[row][col])
    return True  # All columns have unique numbers


matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

if are_columns_unique(matrix):
    print("All columns contain unique numbers.")
else:
    print("Some columns contain duplicate numbers.")




'''
run:

All columns contain unique numbers.

'''

 



answered May 28, 2025 by avibootz
0 votes
import numpy as np

matrix = np.array([[1, 2, 3],
                   [4, 5, 6],
                   [7, 8, 9]])

# Check for unique elements in each column
columns_unique = [len(np.unique(matrix[:, col])) == matrix.shape[0] for col in range(matrix.shape[1])]

print(columns_unique)  





'''
run:

[True, True, True]

'''

 



answered May 28, 2025 by avibootz
0 votes
def columns_have_unique_numbers_pythonic(matrix):
    """
    Checks if each column of a matrix contains numbers without repetition.

    Args:
        matrix: A list of lists representing the matrix.

    Returns:
        True if all columns have unique numbers, False otherwise.
    """
    if not matrix or not matrix[0]:
        return True

    num_cols = len(matrix[0])
    for j in range(num_cols):
        column = [row[j] for row in matrix]  # Extract the j-th column
        if len(column) != len(set(column)):
            return False
    return True


matrix1 = [
    [1, 4, 7],
    [2, 5, 8],
    [3, 6, 9]
]
print(f"Matrix 1 columns have unique numbers: {columns_have_unique_numbers_pythonic(matrix1)}")

matrix2 = [
    [1, 4, 7],
    [2, 4, 8],
    [3, 6, 9]
]
print(f"Matrix 2 columns have unique numbers: {columns_have_unique_numbers_pythonic(matrix2)}")

 
 
'''
run:
 
Matrix 1 columns have unique numbers: True
Matrix 2 columns have unique numbers: False
 
'''

 



answered May 28, 2025 by avibootz
...