How to Add Two Matrices in Python

The following program demonstrates how two matrices can be added in python using the list data structure. Matrix addition works by adding corresponding entries in the matrices based on their position. The following sample program adds two 3x3 matrices, but the program can be easily modified for any size matrix. You just need to change the input data,

# matrixadd.py - Matrix addition in python
# The following example adds two 3x3 matrices
m1 = [
    [9, 2, 2],
    [2, 4, 2],
    [9, 9, 9]
]

m2 = [
    [10,1,2],
    [4,2,1],
    [9,3,4]
]

result = [] # start with outer list

for i in range(len(m1)):
    result.append([]) # add the inner list
    for j in range(len(m1[0])):
        result[i].append(m1[i][j] + m2[i][j])

print(result)

Here is a step by step explanation of the program,

  • Matrices are stored in two dimensional list variables.
  • We create a simple empty list for the result.
  • We then iterate through the matrix values. The outer loop iterates through the number of rows. The inner loop iterates through the number of columns.
  • For each row iterated, we add an empty inner list for values in the result variable.
  • We finally compute the sum for each corresponding elements in matrices and then append it to the inner list for each row of the result.

Following is the output from the above program,

python3 matrixadd.py
[[19, 3, 4], [6, 6, 3], [18, 12, 13]]

How to Reverse a Number in Python

The following python program reverses a given multi-digit number. In this example, we simply print the digits in reverse order without removing redundant zeros. For example, if the input number is "1000", the reversed number displayed will be "0001" instead of "1".

number = int(input("Enter a number: "))
reverse_number = ''

while number > 0:
    last_digit = number % 10
    reverse_number = reverse_number + str(last_digit)
    number = number // 10

print("Reverse number is: ", reverse_number)

The above program uses the following logic to reverse the number,

  1. Extract the last digit using the modulus operator (Remainder of a number after dividing by 10)
  2. Add the last digit as the first digit in the reversed string
  3. Now remove the last digit from the original number dividing it with 10 (note the use of integer division operator //. The / operator if used will return a fraction!)
  4. Repeat from step 1 until the original number has no remaining digits

The following program uses a slightly different approach. In this example, we store the reversed number as an integer instead of a string. This ensures that when we reverse "1000", we get "1" instead of "0001". Note that before adding the last digit we multiply the previous number by 10 to increase its place value.

number = int(input("Enter a number: "))
reverse_number = 0

while number > 0:
    last_digit = number % 10
    reverse_number = reverse_number*10 + last_digit
    number = number // 10

print("Reverse number is: ", reverse_number)

The output of the program when run from console,

Enter a number: 9899
Reverse number is:  9989

Python Program to Draw a Square and Chess Board Using Turtle

For simple drawing, python provides a built-in module named turtle. This behaves like a drawing board and you can use various drawing commands to draw over it. The basic commands control the movement of the drawing pen itself. We start with a very basic drawing program and work our way through to draw a complete chess board using python turtle.

The following python program draws a square shape using the basic turtle commands,

import turtle

board = turtle.Turtle()

board.forward(100) # move forward
board.right(90) # turn pen right 90 degrees

board.forward(100)
board.right(90)

board.forward(100)
board.right(90)

board.forward(100)
board.right(90)

turtle.done()

This can be easily encapsulated into a simple box function as shown below,

import turtle

def draw_box(t):
    for i in range(0,4):
        board.forward(100) # move forward
        board.right(90) # turn pen right 90 degrees

board = turtle.Turtle()

draw_box(board)

turtle.done()

But what if we want to draw different squares at different locations? The following python program shows how it can be done using turtle commands. The draw_box() function is enhanced to draw the square at a specific location. The following program draws a 3x3 grid of 30 pixel boxes.

import turtle

def draw_box(t,x,y,size):
    t.penup() # no drawing!
    t.goto(x,y) # move the pen to a different position
    t.pendown() # resume drawing
    for i in range(0,4):
        board.forward(size) # move forward
        board.right(90) # turn pen right 90 degrees

board = turtle.Turtle()

start_x = 50 # starting x position of the grid
start_y = 50 # starting y position of the grid
box_size = 30 # pixel size of each box in the grid
for i in range(0,3): # 3x3 grid
    for j in range(0,3):
        draw_box(board,start_x + j*box_size, start_y + i*box_size, box_size)

turtle.done()

Let us now enhance the above python program to draw a chess board. This program illustrates the use of color in turtle drawing,

import turtle

def draw_box(t,x,y,size,fill_color):
    t.penup() # no drawing!
    t.goto(x,y) # move the pen to a different position
    t.pendown() # resume drawing

    t.fillcolor(fill_color)
    t.begin_fill()  # Shape drawn after this will be filled with this color!

    for i in range(0,4):
        board.forward(size) # move forward
        board.right(90) # turn pen right 90 degrees

    t.end_fill() # Go ahead and fill the rectangle!


def draw_chess_board():
    square_color = "black" # first chess board square is black
    start_x = 0 # starting x position of the chess board
    start_y = 0 # starting y position of the chess board
    box_size = 30 # pixel size of each square in the chess board
    for i in range(0,8): # 8x8 chess board
        for j in range(0,8):
            draw_box(board,start_x+j*box_size,start_y+i*box_size,box_size,square_color)
            square_color = 'black' if square_color == 'white' else 'white' # toggle after a column
        square_color = 'black' if square_color == 'white' else 'white' # toggle after a row!


board = turtle.Turtle()
draw_chess_board()
turtle.done()

Following is the chess board output from the above python program,

Chess Board Drawing Using Python Turtle Module

How to Generate Cryptographically Secure Random Numbers in Python

Generating a cryptographically secure random number is very easy in python 3.6 and above. You can use the new secrets module and the function randbelow() for it. This function returns a random number below the specified value. The following python 3.6+ program demonstrates the use of secrets module for secure random numbers,

import secrets

# generate 5 secure random numbers between 100 and 999
for i in range(0,5):
    v = 100+ secrets.randbelow(900) # 100+0 to 100+899
    print(v)

In python 3.5 and below, we can use random module and SystemRandom class. This uses the os.urandom() under the covers and hence the cryptographic strength depends on the underlying operating system implementation.

import random

rand_gen = random.SystemRandom()
for i in range(0,5):
    v = 100+ rand_gen.randint(0,899) # 100+0 to 100+899
    print(v)

Python Program to Check for Armstrong Number

What is an Armstrong number?

An Armstrong number is an n-digit number such that the sum of it digits raised to the power n is the number itself. For example, 153 is a 3 digit Armstrong number since,

153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153

Another example is the 4 digit Armstrong number - 1634,

1634 = 1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634

Armstrong numbers are also known as narcissistic numbers in recreational mathematics.

Python Program to Check for Armstrong Numbers

The following python program checks whether a given number is an Armstrong number. It also prints the order of the Armstrong number.

number = int(input("Please enter a number: "))

num_str = str(number)
num_len = len(num_str)

sum_of_digits = 0
for d in num_str:
    sum_of_digits += int(d) ** num_len # power operation

if number == sum_of_digits:
    print("{} is an Armstrong number of order {}".format(number,num_len))
else:
    print("{} is NOT an Armstrong number".format(number))

Following are the steps in the above program,

  • We first accept an input from user and convert it into a number
  • We convert the number to a string and find its length
  • We then iterate through each digit character and then find the sum of the digits raised to the power of length of the string(which is the number of digits in the number)
  • Finally we check whether the sum is same as the original number. If they are same, this number is an Armstrong number!

Python Program to Print All 3 Digit Armstrong Numbers

The following python program prints all the 3 digit Armstrong numbers. We have extracted the logic used in the above program to a separate function named is_arm(),

def is_arm(number):
    num_str = str(number)
    num_len = len(num_str)

    sum_of_digits = 0
    for d in num_str:
        sum_of_digits += int(d) ** num_len # power operation

    if number == sum_of_digits:
        return True
    else:
        return False

for n in range(100,1000): # 100 to 999
    if is_arm(n):
        print("{} is an Armstrong number of order {}".format(n,len(str(n))))

Following is the output from the above python program,

153 is an Armstrong number of order 3
370 is an Armstrong number of order 3
371 is an Armstrong number of order 3
407 is an Armstrong number of order 3

Python Program to Print All Armstrong Numbers Below a Specified Number

The following python program prints all Armstrong numbers below a specified number. It also prints the order of the Armstrong number.

def is_arm(number):
    num_str = str(number)
    num_len = len(num_str)

    sum_of_digits = 0
    for d in num_str:
        sum_of_digits += int(d) ** num_len # power operation

    if number == sum_of_digits:
        return True
    else:
        return False

limit = int(input("Please enter the limit for Armstrong number check: "))

for n in range(1,limit+1): # 1 to limit (inclusive)
    if is_arm(n):
        print("{} is an Armstrong number of order {}".format(n,len(str(n))))

Following is the sample output from the above python program,

Please enter the limit for Armstrong number check: 9999
1 is an Armstrong number of order 1
2 is an Armstrong number of order 1
3 is an Armstrong number of order 1
4 is an Armstrong number of order 1
5 is an Armstrong number of order 1
6 is an Armstrong number of order 1
7 is an Armstrong number of order 1
8 is an Armstrong number of order 1
9 is an Armstrong number of order 1
153 is an Armstrong number of order 3
370 is an Armstrong number of order 3
371 is an Armstrong number of order 3
407 is an Armstrong number of order 3
1634 is an Armstrong number of order 4
8208 is an Armstrong number of order 4
9474 is an Armstrong number of order 4