adsense

Wednesday, 13 July 2016

Transposition Cipher (Decrypt)



The previous post was about encrypting a text with Transposition Cipher but now we will make a program to decrypt the message provided that you have the key.

Source Code :-

-------------------------------------------------------------

# Transposition Cipher Decryption
import math, pyperclip

def main():
    myMessage = input("Enter the encoded text"" ")
    myKey = int(input("Enter the key"" "))

    plaintext = decryptMessage(myKey, myMessage)


# Print with a | (called "pipe" character) after it in case

# there are spaces at the end of the decrypted message.
    print(plaintext + '|')

    pyperclip.copy(plaintext)


def decryptMessage(key, message):
    
# The transposition decrypt function will simulate the "columns" and    
#"rows" of the grid that the plaintext is written on by using a list    

# of strings. First, we need to calculate a few values.

    # The number of "columns" in our transposition grid:    
    numOfColumns = math.ceil(len(message) / key)
   
 # The number of "rows" in our grid will need:    
    numOfRows = key
    # The number of "shaded boxes" in the last "column" of the grid:    
    numOfShadedBoxes = (numOfColumns * numOfRows) - len(message)

    # Each string in plaintext represents a column in the grid.    
    plaintext = [''] * numOfColumns

    # The col and row variables point to where in the grid the next   
 # character in the encrypted message will go.    
    col = 0   
    row = 0
    for symbol in message:
        plaintext[col] += symbol
        col += 1 # point to next column
 
       # If there are no more columns OR we're at a shaded box, go back to
        # the first column and the next row.       
        if (col == numOfColumns) or (col == numOfColumns - 1 and row >= numOfRows - numOfShadedBoxes):
            col = 0            row += 1
    return ''.join(plaintext)



# If transpositionDecrypt.py is run (instead of imported as a module) call
#the main() function.if __name__ == '__main__':
    main()

---------------------------------------------

Result :-




If you face any problem just let me know in the comments below. Don't forget to subscribe for more such posts . :)


Reversi


To all my viewers I'm currently a member of the internship program for a human welfare council and I need your help to assist the people who need us by donating any amount you can. YOUR SMALL GESTURE WILL HELP A FAMILY SMILE. Follow the link and you will get to our campaign page :


Please after funding whatever amount you can share me the screenshot of the receipt to my email - sumanmukherjee2001@gmail.com
So that I can send you a receipt for the contribution you made and tell the happiness you shared. 😊


Reversi is a board game that is played on a grid, so we’ll use a Cartesian coordinate system with XY coordinates. It is a
game played with two players. Our version of the game will have a computer AI that is more advanced than the AI we made for Tic Tac Toe. In fact, this AI is so good that it will probably
beat you almost every time you play.



Reversi has an 8 × 8 board and tiles that are black on one side and white on the other (our game
will use O’s and X’s instead).


The black player and white player take turns placing down a new tile of their color. Any of the opponent’s tiles that are
between the new tile and the other tiles of that color are flipped. The goal of the game is to have as many of the tiles with your color as possible.

Each player can quickly flip many tiles on the board in one or two moves. Players must always make a move that captures at least one tile. The game ends when a player either cannot make a
move, or the board is completely full. The player with the most tiles of their color wins. The AI we make for this game will simply look for any corner moves they can take. If there are
no corner moves available, then the computer will select the move that claims the most tiles.

Source Code :-

---------------------------------------------------------------------------------

# Reversi
import random
import sys def drawBoard(board):
# This function prints out the board that it was passed. Returns None.
HLINE = ' +---+---+---+---+---+---+---+---+'
VLINE = ' | | | | | | | | |' print(' 1 2 3 4 5 6 7 8')
print(HLINE)
for y in range(8):
print(VLINE)
print(y+1, end=' ')
for x in range(8):
print('| %s' % (board[x][y]), end=' ')
print('|')
print(VLINE)
print(HLINE) def resetBoard(board):
# Blanks out the board it is passed, except for the original starting position.
for x in range(8):
for y in range(8):
board[x][y] = ' ' # Starting pieces:
board[3][3] = 'X'
board[3][4] = 'O'
board[4][3] = 'O'
board[4][4] = 'X' def getNewBoard():
# Creates a brand new, blank board data structure.
board = []
for i in range(8):
board.append([' '] * 8) return board def isValidMove(board, tile, xstart, ystart):
# Returns False if the player's move on space xstart, ystart is invalid.
# If it is a valid move, returns a list of spaces that would become the player's if they made a move here.
if board[xstart][ystart] != ' ' or not isOnBoard(xstart, ystart):
return False board[xstart][ystart] = tile # temporarily set the tile on the board. if tile == 'X':
otherTile = 'O'
else:
otherTile = 'X' tilesToFlip = []
for xdirection, ydirection in [[0, 1], [1, 1], [1, 0], [1, -1], [0, -1], [-1, -1], [-1, 0], [-1, 1]]:
x, y = xstart, ystart
x += xdirection # first step in the direction
y += ydirection # first step in the direction
if isOnBoard(x, y) and board[x][y] == otherTile:
# There is a piece belonging to the other player next to our piece.
x += xdirection
y += ydirection
if not isOnBoard(x, y):
continue
while board[x][y] == otherTile:
x += xdirection
y += ydirection
if not isOnBoard(x, y): # break out of while loop, then continue in for loop
break
if not isOnBoard(x, y):
continue
if board[x][y] == tile:
# There are pieces to flip over. Go in the reverse direction until we reach the original space, noting all the tiles along the way.
while True:
x -= xdirection
y -= ydirection
if x == xstart and y == ystart:
break
tilesToFlip.append([x, y]) board[xstart][ystart] = ' ' # restore the empty space
if len(tilesToFlip) == 0: # If no tiles were flipped, this is not a valid move.
return False
return tilesToFlip def isOnBoard(x, y):
# Returns True if the coordinates are located on the board.
return x >= 0 and x <= 7 and y >= 0 and y <=7 def getBoardWithValidMoves(board, tile):
# Returns a new board with . marking the valid moves the given player can make.
dupeBoard = getBoardCopy(board) for x, y in getValidMoves(dupeBoard, tile):
dupeBoard[x][y] = '.'
return dupeBoard def getValidMoves(board, tile):
# Returns a list of [x,y] lists of valid moves for the given player on the given board.
validMoves = [] for x in range(8):
for y in range(8):
if isValidMove(board, tile, x, y) != False:
validMoves.append([x, y])
return validMoves def getScoreOfBoard(board):
# Determine the score by counting the tiles. Returns a dictionary with keys 'X' and 'O'.
xscore = 0
oscore = 0
for x in range(8):
for y in range(8):
if board[x][y] == 'X':
xscore += 1
if board[x][y] == 'O':
oscore += 1
return {'X':xscore, 'O':oscore} def enterPlayerTile():
# Lets the player type which tile they want to be.
# Returns a list with the player's tile as the first item, and the computer's tile as the second.
tile = ''
while not (tile == 'X' or tile == 'O'):
print('Do you want to be X or O?')
tile = input().upper() # the first element in the tuple is the player's tile, the second is the computer's tile.
if tile == 'X':
return ['X', 'O']
else:
return ['O', 'X'] def whoGoesFirst():
# Randomly choose the player who goes first.
if random.randint(0, 1) == 0:
return 'computer'
else:
return 'player' def playAgain():
# This function returns True if the player wants to play again, otherwise it returns False.
print('Do you want to play again? (yes or no)')
return input().lower().startswith('y') def makeMove(board, tile, xstart, ystart):
# Place the tile on the board at xstart, ystart, and flip any of the opponent's pieces.
# Returns False if this is an invalid move, True if it is valid.
tilesToFlip = isValidMove(board, tile, xstart, ystart) if tilesToFlip == False:
return False board[xstart][ystart] = tile
for x, y in tilesToFlip:
board[x][y] = tile
return True def getBoardCopy(board):
# Make a duplicate of the board list and return the duplicate.
dupeBoard = getNewBoard() for x in range(8):
for y in range(8):
dupeBoard[x][y] = board[x][y] return dupeBoard def isOnCorner(x, y):
# Returns True if the position is in one of the four corners.
return (x == 0 and y == 0) or (x == 7 and y == 0) or (x == 0 and y == 7) or (x == 7 and y == 7) def getPlayerMove(board, playerTile):
# Let the player type in their move.
# Returns the move as [x, y] (or returns the strings 'hints' or 'quit')
DIGITS1TO8 = '1 2 3 4 5 6 7 8'.split()
while True:
print('Enter your move, or type quit to end the game, or hints to turn off/on hints.')
move = input().lower()
if move == 'quit':
return 'quit'
if move == 'hints':
return 'hints' if len(move) == 2 and move[0] in DIGITS1TO8 and move[1] in DIGITS1TO8:
x = int(move[0]) - 1
y = int(move[1]) - 1
if isValidMove(board, playerTile, x, y) == False:
continue
else:
break
else:
print('That is not a valid move. Type the x digit (1-8), then the y digit (1-8).')
print('For example, 81 will be the top-right corner.') return [x, y] def getComputerMove(board, computerTile):
# Given a board and the computer's tile, determine where to
# move and return that move as a [x, y] list.
possibleMoves = getValidMoves(board, computerTile) # randomize the order of the possible moves
random.shuffle(possibleMoves) # always go for a corner if available.
for x, y in possibleMoves:
if isOnCorner(x, y):
return [x, y] # Go through all the possible moves and remember the best scoring move
bestScore = -1
for x, y in possibleMoves:
dupeBoard = getBoardCopy(board)
makeMove(dupeBoard, computerTile, x, y)
score = getScoreOfBoard(dupeBoard)[computerTile]
if score > bestScore:
bestMove = [x, y]
bestScore = score
return bestMove def showPoints(playerTile, computerTile):
# Prints out the current score.
scores = getScoreOfBoard(mainBoard)
print('You have %s points. The computer has %s points.' % (scores[playerTile], scores[computerTile])) print('Welcome to Reversi!') while True:
# Reset the board and game.
mainBoard = getNewBoard()
resetBoard(mainBoard)
playerTile, computerTile = enterPlayerTile()
showHints = False
turn = whoGoesFirst()
print('The ' + turn + ' will go first.') while True:
if turn == 'player':
# Player's turn.
if showHints:
validMovesBoard = getBoardWithValidMoves(mainBoard, playerTile)
drawBoard(validMovesBoard)
else:
drawBoard(mainBoard)
showPoints(playerTile, computerTile)
move = getPlayerMove(mainBoard, playerTile)
if move == 'quit':
print('Thanks for playing!')
sys.exit() # terminate the program
elif move == 'hints':
showHints = not showHints
continue
else:
makeMove(mainBoard, playerTile, move[0], move[1]) if getValidMoves(mainBoard, computerTile) == []:
break
else:
turn = 'computer' else:
# Computer's turn.
drawBoard(mainBoard)
showPoints(playerTile, computerTile)
input('Press Enter to see the computer\'s move.')
x, y = getComputerMove(mainBoard, computerTile)
makeMove(mainBoard, computerTile, x, y) if getValidMoves(mainBoard, playerTile) == []:
break
else:
turn = 'player' # Display the final score.
drawBoard(mainBoard)
scores = getScoreOfBoard(mainBoard)
print('X scored %s points. O scored %s points.' % (scores['X'], scores['O']))
if scores[playerTile] > scores[computerTile]:
print('You beat the computer by %s points! Congratulations!' % (scores[playerTile] - scores[computerTile]))
elif scores[playerTile] < scores[computerTile]:
print('You lost. The computer beat you by %s points.' % (scores[computerTile] - scores[playerTile]))
else:
print('The game was a tie!') if not playAgain():
break

---------------------------------------------------------------------------------

Result :-




If you face any problem, let me know in the comments below and don't forget to subscribe for more. :)


Transposition Cipher (Encrypting)


To all my viewers I'm currently a member of the internship program for a human welfare council and I need your help to assist the people who need us by donating any amount you can. YOUR SMALL GESTURE WILL HELP A FAMILY SMILE. Follow the link and you will get to our campaign page :


Please after funding whatever amount you can share me the screenshot of the receipt to my email - sumanmukherjee2001@gmail.com
So that I can send you a receipt for the contribution you made and tell the happiness you shared. 😊

Instead of replacing characters with other characters, the transposition cipher jumbles up themessage’s symbols into an order that makes the original message unreadable. Before we startwriting code, let’s encrypt the message “Common sense is not so common.” with pencil and paper. Including the spaces and punctuation, this message has 30 characters. We will use the number 8 for the key.The first step is to draw out a number of boxes equal to the key. We will draw 8 boxes since our key for this example is 8


The second step is to start writing the message you want to encrypt into the boxes, with one
character for each box. Remember that spaces are a character (this book marks the boxes with (s)
to indicate a space so it doesn’t look like an empty box).

We only have 8 boxes but there are 30 characters in the message. When you run out of boxes,
draw another row of 8 boxes under the first row. Keep creating new rows until you have written
out the full message.

The steps for encrypting are:
1. Count the number of characters in the message and the key.
2. Draw a number of boxes equal to the key in a single row. (For example, 12 boxes for a
key of 12.)
3. Start filling in the boxes from left to right, with one character per box.
4. When you run out of boxes and still have characters left, add another row of boxes


Source Code :-

-------------------------------------------------------------

# Transposition Cipher Encryption
import pyperclip

def main():
    myMessage = input("Enter your text to encode" " ")
    myKey = int(input("Enter the key"))

    ciphertext = encryptMessage(myKey, myMessage)

    # Print the encrypted string in ciphertext to the screen, with    
# a | (called "pipe" character) after it in case there are spaces at    

# the end of the encrypted message.   
    print(ciphertext + '|')

    # Copy the encrypted string in ciphertext to the clipboard.    

    pyperclip.copy(ciphertext)


def encryptMessage(key, message):
    # Each string in ciphertext represents a column in the grid.    

    ciphertext = [''] * key

    # Loop through each column in ciphertext.    
    for col in range(key):
        pointer = col

 # Keep looping until pointer goes past the length of the message.        
        while pointer < len(message):
    
# Place the character at pointer in message at the end of the            
# current column in the ciphertext list.            
           ciphertext[col] += message[pointer]

            # move pointer over            
           pointer += key

    
#Convert the ciphertext list into a single string value and return it.    
       return ''.join(ciphertext)

# If transpositionEncrypt.py is run 

#(instead of imported as a module) call
# the main() function.
if __name__ == '__main__':
    main()

Result :-



If you have any problem let me know in the comments below or mail me. Do subscribe for more like this . :)


Tuesday, 12 July 2016

The Caesar Cypher

      To all my viewers I'm currently a member of the internship program for a human welfare council and I need your help to assist the people who need us by donating any amount you can. YOUR SMALL GESTURE WILL HELP A FAMILY SMILE. Follow the link and you will get to our campaign page :



Please after funding whatever amount you can share me the screenshot of the receipt to my email - sumanmukherjee2001@gmail.com
So that I can send you a receipt for the contribution you made and tell the happiness you shared. 😊


The Caesar Cipher was one of the earliest ciphers ever invented. In this cipher, you encrypt a message by taking each letter in the message (in cryptography, these letters are called symbols because they can be letters, numbers, or any other sign) and replacing it with a “shifted” letter. If you shift the letter A by one space, you get the letter B. If you shift the letter A by two spaces,
you get the letter C.
This more safe Cypher than the Reverse Cypher because it require your key but however it also can be easily cracked because there are only 26 keys available and the computer won't take long to use all 26 keys.It woul take about a hundread of a second to calculate for the computer.

With this source code, you can both encrypt or decrypt a message provided that you know the key.





















Source Code :-




---------------------------------------------------------------------------------
MAX_KEY_SIZE = 26


def getMode():
    while True:
        print('Do you wish to encrypt or decrypt a message?')
        mode = input().lower()
        if mode in 'encrypt e decrypt d'.split():
            return mode
        else:
            print('Enter either "encrypt" or "e" or "decrypt" or "d".')

def getMessage():
     print('Enter your message:')
     return input()

def getKey():
    key = 0    while True:
        print('Enter the key number (1-%s)' % (MAX_KEY_SIZE))
        key = int(input())
        if (key >= 1 and key <= MAX_KEY_SIZE):
            return key

def getTranslatedMessage(mode, message, key):
    if mode[0] == 'd':
        key = -key
    translated = ''
    for symbol in message:
       if symbol.isalpha():

             num = ord(symbol)
             num += key

          if symbol.isupper():
             if num > ord('Z'):
                  num -= 26             
             elif num < ord('A'):
                  num += 26          
           elif symbol.islower():
             if num > ord('z'):
                  num -= 26             
             elif num < ord('a'):
                  num += 26
          translated += chr(num)

       else:
          translated += symbol

    return translated

mode = getMode()
message = getMessage()
key = getKey()

print('Your translated text is:')
print(getTranslatedMessage(mode, message, key))

---------------------------------------------------------------------------------

Result:-


Encryption 



Decryption



If you face any problem just inform to me in the comments below and don't forget to check my blog daily :)


The Reverse Cypher

                     

To all my viewers I'm currently a member of the internship program for a human welfare council and I need your help to assist the people who need us by donating any amount you can. YOUR SMALL GESTURE WILL HELP A FAMILY SMILE. Follow the link and you will get to our campaign page :


Please after funding whatever amount you can share me the screenshot of the receipt to my email - sumanmukherjee2001@gmail.com

So that I can send you a receipt for the contribution you made and tell the happiness you shared. 😊


The reverse cipher encrypts a message by printing it in reverse order. So "How are you" will be "uoy era woh".But its is a very weak cypher. Just by lookink at the text, you can figure out that the letters are just reverse. But to begin with Cryptography, it is the best one to start with as it is easy and develops some concept of cryptography for newbies.


To decrypt, you simply reverse the reversed message to get the original


message. The encryption and decryption steps are the same


 
  


Source code:-

-------------------------------------------------------------
 message = input("enter your message" " ")
translated = ''
i = len(message) - 1while i >= 0:
        translated = translated + message[i]
        i = i - 1
print(translated)
-------------------------------------------------------------

Result :-


For any queries please feel free to comment below .

Getting started with Python and Pycharm :-

        To all my viewers I'm currently a member of the internship program for a human welfare council and I need your help to assist the people who need us by donating any amount you can. YOUR SMALL GESTURE WILL HELP A FAMILY SMILE. Follow the link and you will get to our campaign page :



Please after funding whatever amount you can share me the screenshot of the receipt to my email - sumanmukherjee2001@gmail.com
So that I can send you a receipt for the contribution you made and tell the happiness you shared. 😊



  Getting started with 

                    Python and Pycharm :-


Installing Python :-


Follow the steps to download and install python for windows :-

Step 1 -> Open a new tab in your browser .



Step 2 -> Type Python.org and hit enter in the address bar .



Step 3 -> Click on the DOWNLOAD button.



Step 4 -> Click on Python 3.5.2 and not Python 2.7.12 or other.



Step 5 -> Your Python 3.5.2 will start downloading.




Installing Pycharm :-

               

To all my viewers I'm currently a member of the internship program for a human welfare council and I need your help to assist the people who need us by donating any amount you can. YOUR SMALL GESTURE WILL HELP A FAMILY SMILE. Follow the link and you will get to our campaign page :


Please after funding whatever amount you can share me the screenshot of the receipt to my email - sumanmukherjee2001@gmail.com
So that I can send you a receipt for the contribution you made and tell the happiness you shared. 😊



Follow the steps to install Pycharm :-

Step 1 -> Open a new tab in your browser.



Step 2 -> Go to Goolgle.com


Step 3 -> Type Pycharm and select the first link .


Step 4 -> Click on DOWNLOAD from the site.


Step 5 -> Click on Download the COMMUNITY version .



Step 6 -> Pycharm will start downloading. 





Monday, 11 July 2016

Python Programming

To all my viewers I'm currently a member of the internship program for a human welfare council and I need your help to assist the people who need us by donating any amount you can. YOUR SMALL GESTURE WILL HELP A FAMILY SMILE. Follow the link and you will get to our campaign page :


Please after funding whatever amount you can share me the screenshot of the receipt to my email - sumanmukherjee2001@gmail.com
So that I can send you a receipt for the contribution you made and tell the happiness you shared. 😊





 C'mon now we need to work hard from here on to get into python. However at the end you'll keep on saying in your mind ,"It was so simple stupid and you thought programming is not for me".

So, we'll start the course with the basic knowledge of variables,strings,integer,float .

                                        Variables :-


Wait you're like , "man I've heard about it. But where the shit I've used them  ?" 
It was your maths teacher who taught you about this in your junior classes . Remember 'linear equations','quadratic equation' where you needed to find the value of  X,Y and so on.
Yeah same with here. 

In python variable stores a data so that you can use it any time in your program later. Think it like a box that can hold values !


Here in the example, 
1. 'adam' is given a value "boy".
2. 'christie' is given a value "girl" .

so whenever in our program we type 'adam' , python will search for the name and then will see what is the value . It will then show or use the value assigned to it. Similarly in case of 'christie' , python will search and use the value that we've given to it.
So, when we type 'adam', python will return as shown in the picture.


'adam' returns "boy" and 'christie' returns "girl".

Q. Why to use variables ?

Ans. Well, when you write a program it happens that you have to type the same data again and again. So, to reduce the efforts ,you can store the data in a variable and call it anytime you want them.

Example :-


Here, I've used it for a simple equation.

                                      Strings :-


In python. text values are called STRINGS .A string in python begins and ends with a quotes.However the quotes are not a part of the value's text. 


Strings can have any keyword in them and can be as long as you want !
 You can also add stings like numbers . Just type a string give a '+' sign between them (without quotes) and then type another string and repeat as much as you want.

Q. Can we store a string in a variable and then add them ?
Ans. Hell yeah dude ! you can just go for it .




PYTHON - BEGINNER'S GUIDE

To all my viewers I'm currently a member of the internship program for a human welfare council and I need your help to assist the people who need us by donating any amount you can. YOUR SMALL GESTURE WILL HELP A FAMILY SMILE. Follow the link and you will get to our campaign page :


Please after funding whatever amount you can share me the screenshot of the receipt to my email - sumanmukherjee2001@gmail.com
So that I can send you a receipt for the contribution you made and tell the happiness you shared. 😊




Python is an awesome language for those who want to learn programming but have no past experience with writing codes. While there are many programming languages out there , python remains the basic choice for an intermediate because of its simplicity yet strong performance .It is a high-level programming language.                             (picture source-www.i-programmer.info)

Acoording to a 
survey done in 
2015, Python was
the most popular 
language even 
ahead of java !              
Python was conceived in the late 1980s[1] and its implementation was started in December 1989[2] by Guido van Rossum at CWI in the Netherlands as a successor to the ABC programming language capable of exception handling and interfacing with the Amoeba operating system.[3] Van Rossum is Python's principal author, and his continuing central role in deciding the direction of Python is reflected in the title given to him by the Python community, Benevolent Dictator for Life (BDFL). (source-wikipedia)
With python you can code awesome stuffs so why to sit there and read this article . Get started today for free with this blog ! Share it friends and help them too .


Saturday, 9 July 2016

TIC TAC TOE - A GIUDE TO PYTHON 3


To all my viewers I'm currently a member of the internship program for a human welfare council and I need your help to assist the people who need us by donating any amount you can. YOUR SMALL GESTURE WILL HELP A FAMILY SMILE. Follow the link and you will get to our campaign page :


Please after funding whatever amount you can, share me the screenshot of the receipt along with my your name and contact number(optional) to my email : sumanmukherjee2001@gmail.com
So that I can send you a receipt for the contribution you made and tell the happiness you shared. 😊





So, here we go our first tutorial on programming. Let’s start the basic thing that every python programmer must have made . Yeah its nothing but a TIC TAC TOE game..

This uses an algorithm named “Minimax Algorithm. And yeah this code is strictly for PYTHON 3 not PYTHON 2.


















You can get the Python file for this game here :-

https://mega.nz/#!74B1kLRD!cYJ9XTuFGCTam5BiXhV72Crp2-AdWze9EsDKTDxaPZY