Python Program to Randomly Fill in 0s and 1s into a 4x4 2-Dimension List and Find the Rows and Columns with the Most Number of 1s

Python is a popular programming language that is widely used for data analysis, machine learning, and web development. In this blog post, we will discuss how to write a Python program to randomly fill in 0s and 1s into a 4x4 2-Dimension list, print the list, and find the rows and columns with the most number of 1s.

Python Program to Randomly Fill in 0s and 1s into a 4x4 2-Dimension List and Find the Rows and Columns with the Most Number of 1s

Table of Contents:

  • Introduction
  • Generating a 4x4 2-Dimension List with Random 0s and 1s
  • Output

| Learn Python with " Computer Courses - All in One " 

Introduction

A 2-Dimension list is a list of lists in Python. It is a useful data structure for storing and manipulating data. In this blog post, we will create a 4x4 2-Dimension list with random 0s and 1s, print the list, and find the rows and columns with the most number of 1s.

Generating a 4x4 2-Dimension List with Random 0s and 1s:

l = []

m = []

x = 0


for k in range(4):

    for g in range(4):

        m.append(int(input('Enter Element')))

    l.append(m[x:x+4])

    x += 4


for i in l:

    print(i)

print()


# Print the list and find the rows and columns with the most number of 1s

max_row = 0

max_col = 0

row_no = 0

col_no = 0


for i in range(4):

    row = 0

    col = 0


    for j in range(4):

        if l[i][j] == 1:

            row += 1

        if l[j][i] == 1:

            col += 1


    if row > max_row:

        max_row = row

        row_no = i

    if col > max_col:

        max_col = col

        col_no = i


print("Row with the most number of 1s is row", row_no, "with", max_row, "1s")

print("Column with the most number of 1s is column", col_no, "with", max_col, "1s")

| Practice Python MCQ with "Python MCQ Programs Interview  " Android App.  

Output:

Enter Element1
Enter Element1
Enter Element0
Enter Element1
Enter Element0
Enter Element1
Enter Element1
Enter Element0
Enter Element0
Enter Element1
Enter Element0
Enter Element1
Enter Element0
Enter Element1
Enter Element1
Enter Element0
[1, 1, 0, 1]
[0, 1, 1, 0]
[0, 1, 0, 1]
[0, 1, 1, 0]

Row with the most number of 1s is row 0 with 3 1s
Column with the most number of 1s is column 1 with 4 1s

In this blog post, we explored a Python program that generates a random 4x4 matrix filled with 0s and 1s. We then printed the matrix and analyzed it to identify the rows and columns with the most number of 1s. Understanding how to work with matrices and perform such analyses is valuable in many computational applications, such as image processing, data analysis, and machine learning.

Post a Comment

0 Comments