From a book that programmers can learn (Python): Decoding messages

Problem: Decrypting the message (code the example string) > A message is encoded as a text stream, which is read character by character. The content of the stream is a list of integer values separated by commas, and each number is a positive number in the range that can be handled by the C ++ int type. However, which character the number represents depends on the current decoding mode. There are three modes, one of uppercase, lowercase, and symbols. In uppercase mode, individual numbers represent uppercase letters. This is because the remainder of dividing a number by 27 is the remainder of dividing by the alphabet, and the eighth letter of the alphabet is H. The same is true for lowercase mode, but it represents lowercase letters. The remainder of dividing the number by 27 corresponds to the letters of the alphabet (1 is a). For example, if the input is 56, the output will be b. This is because the remainder of 57 divided by 27 is 2, and the second letter of the alphabet is b. For symbol mode, use the remainder of the number divided by 9. Convert this remainder according to Table 2-3. For example, 19 is an exclamation mark. This is because the remainder of dividing 19 by 9 is 1. The decryption mode at the beginning of the message is uppercase mode. The decoding mode is switched each time the result of the remainder operation (using either 27 or 9 depending on the mode) becomes 0. If the current mode is uppercase, return to lowercase mode, if the current mode is lowercase, return to symbolic mode, and if symbolic mode, return to uppercase mode again. Table 2-3 Decoding in symbol mode Numbers and symbols 1     ! 2     ? 3     , 4     . 5 (space) 6     ; 7     " 8 \ n (line feed) As an example, as shown in the image below The processing procedure is switched from uppercase (U) to lowercase (L) and symbol (P). Column (c) Shows the divisor used in the current mode. Column (d) is the remainder of the input in column (A) divided by the divisor of column (c). The processing results are shown in column (e). If (d) is 0, it switches to the next mode. Example string ⇨ 18,12312,171,763,98423,1208,216,11,500,18,241,0,32,20620,27,10 ![2-3.png](https://qiita-image-store.s3.amazonaws.com/0/120949/357f9367-5778-53fb-f8d8-e4b5fc383d16.png)

Now, as usual, I was instructed to break down this into a small problem as to how to make it into Python code, so I will show you the details.

--Read one character at a time until you reach the end of the line (this is solved with Python's input ()) --Convert a string representing a number to an integer. (This is also solved by Python input ()) --Convert integer values from 1 to 26 to uppercase alphabet. --Convert integer values from 1 to 26 to lowercase alphabets. --Convert integer values from 1 to 8 to symbols according to Table 2-3. --Remember the decryption mode.

I would like to proceed with the above contents. So, immediately

Converts integer values from 1 to 26 to uppercase letters.

If it is the contents of a book, it can be converted to characters from A to Z by matching it with the ASCII character code and adding some character code to the integer values from input 1 to 26. I am proceeding with.

Like last time, I will try a different method in Python without using ASCII character code, but in Python it is rather rudimentary or it is okay to put it in a list and extract it with an index. If this --Convert integer values from 1 to 26 to uppercase alphabet. --Convert integer values from 1 to 26 to lowercase alphabets. --Convert integer values from 1 to 8 to symbols according to Table 2-3. I think we can handle it.

test12.py


#!/usr/bin/env python
#coding:utf-8

from ConsoleOut import cout   #cout in python<<Prepare a class to use(Taught me)
import enum
import math


UPPERCASE = [' ','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']
LOWERCASE = [' ','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']
PUNCTUATION = [' ','!','?',',','.',' ',';','"','\n']

modeType = UPPERCASE


while modeType in [UPPERCASE,LOWERCASE,PUNCTUATION]:
    cout << "Enter some numbers ending with -1: "
    digit = input()
    if modeType == UPPERCASE:
        cout << "Number read: " + digit + "\n"
        digit = int(digit) % 27
        cout << ". Modulo 27: " + UPPERCASE[digit] + "\n"
        if digit == 0:
            modeType = LOWERCASE
        else:
            continue

    elif modeType == LOWERCASE:
        cout << "Number read: " + digit + "\n"
        digit = int(digit) % 27
        cout << ". Modulo 27: " + LOWERCASE[digit] + "\n"
        if digit == 0:
            modeType = PUNCTUATION
        else:
            continue

    elif modeType == PUNCTUATION:
        cout << "Number read: " + digit + "\n"
        digit = int(digit) % 9
        cout << ". Modulo 27: " + PUNCTUATION[digit] + "\n"
        if digit == 0:
            modeType = UPPERCASE
        else:
            continue
・ ・ ・ ・(Terminal execution)
>>> import test12
Enter some numbers ending with -1: 18
Number read: 18
. Modulo 27: R
Enter some numbers ending with -1: 12312
Number read: 12312
. Modulo 27:  
Enter some numbers ending with -1: 171
Number read: 171
. Modulo 27: i
Enter some numbers ending with -1: 763
Number read: 763
. Modulo 27: g
Enter some numbers ending with -1: 98423
Number read: 98423
. Modulo 27: h
Enter some numbers ending with -1: 1208
Number read: 1208
. Modulo 27: t
Enter some numbers ending with -1: 216
Number read: 216
. Modulo 27:  
Enter some numbers ending with -1: 11
Number read: 11
. Modulo 27: ?
Enter some numbers ending with -1: 500
Number read: 500
. Modulo 27:  
Enter some numbers ending with -1: 18
Number read: 18
. Modulo 27:  
Enter some numbers ending with -1: 241
Number read: 241
. Modulo 27: Y
Enter some numbers ending with -1: 0
Number read: 0
. Modulo 27:  
Enter some numbers ending with -1: 32
Number read: 32
. Modulo 27: e
Enter some numbers ending with -1: 20620
Number read: 20620
. Modulo 27: s
Enter some numbers ending with -1: 27
Number read: 27
. Modulo 27:  
Enter some numbers ending with -1: 10
Number read: 10
. Modulo 27: !
Enter some numbers ending with -1: 


For the time being, it is now possible to output from integer values to alphabets and symbols by switching modes with an infinite loop, but there are many subtle points such as the part where extra spaces appear on the way and how to exit the infinite loop. However, it worked for the time being.

By the way, here is the answer for C ++

char outputCharacter;
enum modeType {UPPERCASE,LOWERCASE,PUNCTUATION};
modeType mode = UPPERCASE;
char digitChar;
do {
    digitChar = cin.get();
    int number = (digitChar - '0');
    digitChar = cin.get();
    while ((digitChar != 10)&&(digitChar != ',')){
        number = number * 10 + (digitChar - '0');
        digitChar = cin.get();
    }
    switch (mode){
        case UPPERCASE:
            number = number % 27;
            outputCharacter = number + 'A' - 1;
            if(number == 0){
                mode = LOWERCASE;
                continue;
            }
            break;
        case LOWERCASE:
            number = number % 27;
            outputCharacter = number + 'a' - 1;
            if (number == 0){
                mode = PUNCTUATION;
                continue;
            }
            break;
        case PUNCTUATION:
            number = number % 9;
            switch(number){
                case 1: outputCharacter = '!';break;
                case 2: outputCharacter = '?';break;
                case 3: outputCharacter = ',';break;
                case 4: outputCharacter = '.';break;
                case 5: outputCharacter = ' ';break;
                case 6: outputCharacter = ';';break;
                case 7: outputCharacter = '"';break;
                case 8: outputCharacter = '\';break; 
            }
            if(number == 0){
                mode = UPPERCASE;
                continue;
            }
            break;
        }
        cout << outputCharacter;
    }while (digitChar != 10);
    cout << "\n";

                  

This time I couldn't divide it into small pieces, so I wrote my own python code while looking at the answer code.

Recommended Posts

From a book that programmers can learn (Python): Decoding messages
From a book that programmers can learn ... (Python): Pointer
From a book that programmers can learn ... (Python): About sorting
From a book that programmers can learn (Python): Find the mode
From a book that programmers can learn ... (Python): Review of arrays
From a book that programmers can learn (Python): Statistical processing-deviation value
From a book that programmers can learn (Python): Conditional search (maximum value)
From a book that programmers can learn ... Collect small problem parts
From a book that programmers can learn: Verification of rune checksum (fixed length)
From a book that programmers can learn ... Verification of rune checksum (variable length) Part 2
From a book that programmers can learn: Converting characters that represent numbers to integer types
From a book that makes the programmer's way of thinking interesting (Python)
8 services that even beginners can learn Python (from beginners to advanced users)
"Python Kit" that calls a Python script from Swift
I made a Docker image that can call FBX SDK Python from Node.js
Programmer's way of thinking is from XX book (Python)
"A book that understands Flask from scratch" Reading memo
Programmer's way of thinking is from XX book (Python)
A mechanism to call a Ruby method from Python that can be done in 200 lines
A memo that reads data from dashDB with Python & Spark
A Python program in "A book that gently teaches difficult programming"
python Condition extraction from a list that I often forget
A Python program that aggregates time usage from icalendar data
[Python] Make a graph that can be moved around with Plotly
Make a Kindle book that images mathematical formulas from TeX files
Created a library for python that can easily handle morpheme division
About psd-tools, a library that can process psd files in Python
I made a shuffle that can be reset (reverted) with Python
[Python algorithm] A program that outputs Sudoku answers from a depth-first search
[python] I made a class that can write a file tree quickly
Call a Python function from p5.js.
Touch a Python object from Elixir
python / Make a dict from a list.
Features that can be extracted from time series data
From a book that programmers can learn ... (Python): About sorting
This and that about pd.DataFrame
About Boxplot and Violinplot that visualize the variability of independent data
I created a template for a Python project that can be used universally
[Python] A program that finds a pair that can be divided by a specified value
Extract lines that match the conditions from a text file with python
Try using APSW, a Python library that SQLite can get serious about
[Python] I made a utility that can access dict type like a path
I made a simple timer that can be started from the terminal
Build a Python virtual environment that anyone can understand September 2016 (pyenv + virutalenv)
I made a module PyNanaco that can charge nanaco credit with python
Spiral book in Python! Python with a spiral book! (Chapter 14 ~)
[Python] A program that creates stairs with #
Send a message from Python to Slack
# 5 [python3] Extract characters from a character string
Create a deb file from a python package
[Python] Create a LineBot that runs regularly
Generate a class from a string in Python
Use Django from a local Python script
A typed world that begins with Python
Manipulate BigQuery tables from a Python client
A program that plays rock-paper-scissors using Python
Call a command from Python (Windows version)
Learn dynamic programming in Python (A ~ E)
[Python] A program that rounds the score
A class for PYTHON that can be operated without being aware of LDAP
I tried to create a class that can easily serialize Json in Python
I want to create a priority queue that can be updated in Python (2.7)
I registered PyQCheck, a library that can perform QuickCheck with Python, in PyPI.
A python script that draws a band diagram from the VASP output file EIGENVAL