Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Convert Integer Matrix to String Matrix
Next article icon

Python | Encoding Decoding using Matrix

Last Updated : 30 Dec, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

This article is about how we use the matrix to encode and decode a text message and simple strings.
Encoding process :

  1. Take a String convert to corresponding number shown below
  2. convert to 2D matrix(array). Now we have 2×2 matrix!
  3. When we multiply this matrix with encoding matrix we get encoded 2×2 matrix.
  4. now convert to vector(1D array) and Display to user

Decoding process

  • Take Encoded number convert into 2D matrix(array)
  • Inverse Encoding matrix!
  • Multiply Encoded matrix with inverse of encoding matrix.
  • convert to 1D Matrix(array).then convert to corresponding Alphabets.
  • Code : Encode.py




    # loading libraries
    import numpy as np
      
    a  =  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
    c  =  [[0,0,0,0,0,0,0,0,0,0],
           [0,0,0,0,0,0,0,0,0,0]]
      
    # encode matrix
    ecm = [[3,4], [3,6]]
    i = 0
    l = 0
       
    # Lists of Alphabets and its values
    smallalpha = [" ","a", "b", "c", "d", "e", "f", "g", "h",
                  "i", "j", "k", "l", "m", "n", "o", "p", "q",
                  "r", "s", "t", "u", "v", "w", "x", "y", "z"]
    capitalalpha = [" ","A", "B", "C", "D", "E", "F", "G", "H",
                    "I", "J", "K", "L", "M", "N", "O", "P", "Q",
                    "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
    alphavalues = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
                   13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
                   23, 24, 25, 26, 27]
      
    # string to convert 
    b = "India"
    listb = list(b)
    lenb = len(listb)
       
    # Loop to convert Word to Values that 
    # are further useful for Encoding
    for i in range(lenb):
        for j in range(27):
            if(listb[i]  == smallalpha[j]):
                a[i] = alphavalues[j]
                if(j  == 23):
                    j = 0
                break
            if(j  == 23):
                for k in range(27):
                    if(listb[i]  == capitalalpha[k]):
                        a[i] = alphavalues[k]
                        break
                         
                       
    if(lenb%2 == 1):
        lenb = lenb+1
    a = a[0:lenb]
    tb = b
       
       
    # convert this array to 2D array for further 
    # multiplication with encoding matrix
      
    j = 0
    k = 0
      
    # b[m][n] m is always 2
    n = int(lenb/2)
    for i in range(0,lenb):
        if(j<n):
            c[k][j] = a[i]
            j = j+1
        else:
            k = k+1
            j = 0
            c[k][j] = a[i]
            j = j+1
               
               
    # Multiplay matrix by Encoding 2x2 matrix 
    c = np.matmul(ecm, c)
       
       
    # Convert to 1D array for displaying 
    i = 0
    j = 0
    k = 0
    for i in range(2):
        for j  in range(int(lenb/2)):
            a[k] = c[i][j]
            k = k+1
       
              
    a = a[0:lenb]
    print("Encoding matrix  =  ", ecm)
    print("encrypted form =  ", a)
     
     

    Time Complexity : O(n)(where n is length of message)
    Space Complexity : O(n)
     

    Output:

      Encoding matrix =  [[3, 4], [3, 6]]  Encrypted form =  [63, 46, 12, 81, 48, 12]  

    Code : Decode.py




    # importing libraries
    import numpy as np
    from numpy.linalg import inv
      
      
    # Initial values
    a =[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0]
      
    tdm =[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
          [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
      
    # encoding matrix
    ecm =[[3, 4],
         [3, 6]]
      
    # Lists of Alphabets and its values
    smallalpha = [" ","a", "b", "c", "d", "e", "f", "g", "h",
                  "i", "j", "k", "l", "m", "n", "o", "p", "q",
                  "r", "s", "t", "u", "v", "w", "x", "y", "z"]
    capitalalpha = [" ","A", "B", "C", "D", "E", "F", "G", "H",
                    "I", "J", "K", "L", "M", "N", "O", "P", "Q",
                    "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
    alphavalues = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
                   13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
                   23, 24, 25, 26, 27]
      
      
    # Take inputs
    # elements in Encrypted Matrix
    lenb = 6
    a = [63, 46, 12, 81, 48, 12]
      
    sobj = slice(lenb)
    a = a[sobj]
      
      
    # convert array to 2d matrix to further 
    # multiplication with inverse of 2d matrix
    j = 0
    k = 0
      
    # b[m][n] m is always 2
    n = int(lenb / 2)
    for i in range(0, lenb):
        if(j<n):
            tdm[k][j]= a[i]
            j = j + 1
        else:
            k = k + 1
            j = 0
            tdm[k][j]= a[i]
            j = j + 1
      
              
    # Multiply by inverse matrix
    dcm = inv(ecm)
    dcm = np.matmul(dcm, tdm)
      
      
    # Convert to 1d array for extracting word
    i = 0
    j = 0
    k = 0
    for i in range(2):
        for j in range(int(lenb / 2)):
            a[k]= dcm[i][j]
            k = k + 1
               
      
    # Creating a decoded word
    text = ""
    for i in range(0, lenb):
        for j in range(0, 27):
            if(a[i]== alphavalues[j]):
                text =''.join([text, smallalpha[j]])
      
    print("Decoded message = "+text)
     
     


    Time Complexity :
    O(n)(where n is number of elements)
    Space Complexity : O(n)

    Output:

    Decoded message = india 


    Next Article
    Python - Convert Integer Matrix to String Matrix

    M

    mwadile03
    Improve
    Article Tags :
    • Python
    • Python Programs
    • Python matrix-program
    Practice Tags :
    • python

    Similar Reads

    • Python - Combine Strings to Matrix
      Sometimes while working with data, we can receive separate data in the form of strings and we need to compile them into Matrix for its further use. This can have applications in many domains. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + split
      4 min read
    • Mapping Matrix with Dictionary-Python
      The task of mapping a matrix with a dictionary involves transforming the elements of a 2D list or matrix using a dictionary's key-value pairs. Each element in the matrix corresponds to a key in the dictionary and the goal is to replace each matrix element with its corresponding dictionary value. For
      4 min read
    • Python - Convert Integer Matrix to String Matrix
      Given a matrix with integer values, convert each element to String. Input : test_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6]] Output : [['4', '5', '7'], ['10', '8', '3'], ['19', '4', '6']] Explanation : All elements of Matrix converted to Strings. Input : test_list = [[4, 5, 7], [10, 8, 3]] Output : [
      6 min read
    • Take Matrix input from user in Python
      Matrix is nothing but a rectangular arrangement of data or numbers. In other words, it is a rectangular array of data or numbers. The horizontal entries in a matrix are called as 'rows' while the vertical entries are called as 'columns'. If a matrix has r number of rows and c number of columns then
      5 min read
    • Summation Matrix columns - Python
      The task of summing the columns of a matrix in Python involves calculating the sum of each column in a 2D list or array. For example, given the matrix a = [[3, 7, 6], [1, 3, 5], [9, 3, 2]], the goal is to compute the sum of each column, resulting in [13, 13, 13]. Using numpy.sum()numpy.sum() is a hi
      2 min read
    • Python | Nth Column vertical string in Matrix
      Sometimes, while working with Python Matrix, we can have a problem in which we need to access the Matrix in vertical form and extract strings from the same, that too as a string, not merely as a list of characters. This task has its application in gaming in which we need to extract strings during cr
      7 min read
    • Python | Custom length Matrix
      Sometimes, we need to initialize a matrix in Python of variable length from the list containing elements. In this article, we will discuss the variable length method initialization and certain shorthands to do so. Let's discuss certain ways to perform this. Method #1: Using zip() + list comprehensio
      6 min read
    • Python - Convert Matrix to Dictionary
      The task of converting a matrix to a dictionary in Python involves transforming a 2D list or matrix into a dictionary, where each key represents a row number and the corresponding value is the row itself. For example, given a matrix li = [[5, 6, 7], [8, 3, 2], [8, 2, 1]], the goal is to convert it i
      4 min read
    • Python - Character coordinates in Matrix
      Sometimes, while working with Python data, we can have a problem in which we need to extract all the coordinates in Matrix, which are characters. This kind of problem can have potential application in domains such as web development and day-day programming. Let's discuss certain ways in which this t
      5 min read
    • Python - Convert Strings to Character Matrix
      Sometimes, while dealing with String lists, we can have a problem in which we need to convert the Strings in list to separate character list. Overall converting into Matrix. This can have multiple applications in data science domain in which we deal with lots of data. Lets discuss certain ways in wh
      3 min read
    geeksforgeeks-footer-logo
    Corporate & Communications Address:
    A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
    Registered Address:
    K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
    GFG App on Play Store GFG App on App Store
    Advertise with us
    • Company
    • About Us
    • Legal
    • Privacy Policy
    • In Media
    • Contact Us
    • Advertise with us
    • GFG Corporate Solution
    • Placement Training Program
    • Languages
    • Python
    • Java
    • C++
    • PHP
    • GoLang
    • SQL
    • R Language
    • Android Tutorial
    • Tutorials Archive
    • DSA
    • Data Structures
    • Algorithms
    • DSA for Beginners
    • Basic DSA Problems
    • DSA Roadmap
    • Top 100 DSA Interview Problems
    • DSA Roadmap by Sandeep Jain
    • All Cheat Sheets
    • Data Science & ML
    • Data Science With Python
    • Data Science For Beginner
    • Machine Learning
    • ML Maths
    • Data Visualisation
    • Pandas
    • NumPy
    • NLP
    • Deep Learning
    • Web Technologies
    • HTML
    • CSS
    • JavaScript
    • TypeScript
    • ReactJS
    • NextJS
    • Bootstrap
    • Web Design
    • Python Tutorial
    • Python Programming Examples
    • Python Projects
    • Python Tkinter
    • Python Web Scraping
    • OpenCV Tutorial
    • Python Interview Question
    • Django
    • Computer Science
    • Operating Systems
    • Computer Network
    • Database Management System
    • Software Engineering
    • Digital Logic Design
    • Engineering Maths
    • Software Development
    • Software Testing
    • DevOps
    • Git
    • Linux
    • AWS
    • Docker
    • Kubernetes
    • Azure
    • GCP
    • DevOps Roadmap
    • System Design
    • High Level Design
    • Low Level Design
    • UML Diagrams
    • Interview Guide
    • Design Patterns
    • OOAD
    • System Design Bootcamp
    • Interview Questions
    • Inteview Preparation
    • Competitive Programming
    • Top DS or Algo for CP
    • Company-Wise Recruitment Process
    • Company-Wise Preparation
    • Aptitude Preparation
    • Puzzles
    • School Subjects
    • Mathematics
    • Physics
    • Chemistry
    • Biology
    • Social Science
    • English Grammar
    • Commerce
    • World GK
    • GeeksforGeeks Videos
    • DSA
    • Python
    • Java
    • C++
    • Web Development
    • Data Science
    • CS Subjects
    @GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
    We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
    Lightbox
    Improvement
    Suggest Changes
    Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
    geeksforgeeks-suggest-icon
    Create Improvement
    Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
    geeksforgeeks-improvement-icon
    Suggest Changes
    min 4 words, max Words Limit:1000

    Thank You!

    Your suggestions are valuable to us.

    What kind of Experience do you want to share?

    Interview Experiences
    Admission Experiences
    Career Journeys
    Work Experiences
    Campus Experiences
    Competitive Exam Experiences