How to initialize a matrix with random characters in Python

2 Answers

0 votes
import random

ROWS = 3
COLS = 4

def print_matrix(matrix):
    for row in matrix:
        # join with spacing similar to setw(3)
        print("".join(f"{ch:>3}" for ch in row))

def get_random_character():
    characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    
    return random.choice(characters)

def initialize_matrix_with_random_characters(rows, cols):
    return [[get_random_character() for _ in range(cols)] for _ in range(rows)]

def main():
    matrix = initialize_matrix_with_random_characters(ROWS, COLS)
    print_matrix(matrix)

if __name__ == "__main__":
    main()



'''
run:

  i  T  z  E
  O  g  6  b
  v  E  I  T

'''

 



answered 13 hours ago by avibootz
0 votes
import random
import string

def generate_random_char_matrix(rows, cols, charset=None):
    """
    Generate a matrix (list of lists) filled with random characters.

    :param rows: Number of rows in the matrix
    :param cols: Number of columns in the matrix
    :param charset: Optional string of characters to choose from
    :return: 2D list (matrix) of random characters
    """
    # Validate inputs
    if not isinstance(rows, int) or not isinstance(cols, int) or rows <= 0 or cols <= 0:
        raise ValueError("Rows and columns must be positive integers.")

    # Default charset: uppercase letters
    if charset is None:
        charset = string.ascii_uppercase

    # Ensure charset is not empty
    if not charset:
        raise ValueError("Character set cannot be empty.")

    # Create matrix
    matrix = [[random.choice(charset) for _ in range(cols)] for _ in range(rows)]
    return matrix

if __name__ == "__main__":
    rows, cols = 5, 8
    matrix = generate_random_char_matrix(rows, cols, string.ascii_letters + string.digits)

    # Print matrix in a readable format
    for row in matrix:
        print(" ".join(row))



'''
run:

x o b s y W y 9
B y 5 8 r y 3 l
c 0 m l V r o W
Q n K T l f o d
N j r L j e q U

'''

 



answered 12 hours ago by avibootz
...