Search code examples
pythonabstract-syntax-treesys

Index slicing in Python using ast and sys module


In a certain encrypted message which has information about the locations, the characters are jumbled such that first character of the first word is followed by the first character of the second word, then it is followed by second character of the first word and so on.

Let’s say the location is Chennai, Kolkata.

The encrypted message says ckhoelnknaatia.

Sample Input: ckhoelnknaatia

Sample Output: chennai, kolkata

If the size or length of the two words wouldn’t match then the smaller word is appended with # and then encrypted in the above format.

To do this, I have to follow the code snippet:

import ast, sys

input_str = sys.stdin.read()

# Type your code here

print(message1, message2)

I do not have required knowledge for ast and sys module to solve this.


Solution

  • Try this one

    import sys
    
    input_str = input('type here\n')
    # if you need system arguments while running prgram like
    # python hello.py ckhoelnknaatia
    # input_str = sys.argv[1]
    
    length_of_string = len(input_str)
    # 1st message stars from index 0 
    message1 = input_str[0: length_of_string: 2]
    # 2nd message stars from index 1 
    
    message2 = input_str[1: length_of_string: 2]
    # Remove all #s from output 
    message1 = message1.replace('#', '')
    message2 = message2.replace('#', '')
    
    print(message1, message2)