2
\$\begingroup\$

the Encoding scheme is given below:

Don't replace the characters in the even places. Replace the characters in the odd places by their place numbers . and if they exceed 'z', then again they will start from 'a'.

example: for a message "hello" would be "ieolt" and for message "maya" would be "naba"

how many lines of code [minimum] do we have to write in order to encode a lengthy string in python in the above format.?

mycode is given below:

def encode(msg):
    encoded_message = ""
    letters = "abcdefghijklmnopqrstuvwxyz"
    index_of_msg = 0
    for char in msg.lower():
        if char.isalpha():
            if index_of_msg%2 == 0 :          
                encoded_message += letters[((letters.rfind(char) )+ (index_of_msg+1))%26]  # changed msg.rfind(char) to index_of_msg
            else:
                encoded_message += char
        else:
            encoded_message += char
        index_of_msg +=1
    return encoded_message
\$\endgroup\$
2
  • 1
    \$\begingroup\$ The examples seem strange, by the way. Does "replace by their place number" mean "replace by the letter corresponding to their place number?". And if yes, for hello, shouldn't the first letter be replaced by a (place == 1)? Edit: oh, I get it, you add the place number to the letter. \$\endgroup\$
    – fjarri
    Commented Aug 14, 2013 at 13:04
  • \$\begingroup\$ @Bogdan in hello as h is in odd place ie 1 thus, it moved by its place number 1 ie h+1 = i Sorry if my actual question confused you \$\endgroup\$
    – Sandeep
    Commented Aug 14, 2013 at 13:08

1 Answer 1

2
\$\begingroup\$

Here's a one liner for you (since the question asks for the minimum number of lines):

encode = lambda s: "".join([(c if (i+1) % 2 == 0 else chr(ord('a') + (ord(c) - ord('a') + i + 1) % 26)) for i, c in enumerate(s)])
\$\endgroup\$
4
  • \$\begingroup\$ thnx fr tht @Bogdan? \$\endgroup\$
    – Sandeep
    Commented Aug 14, 2013 at 13:20
  • \$\begingroup\$ What if i have to get input from a file and output the enocoded string to another file? \$\endgroup\$
    – Sandeep
    Commented Aug 14, 2013 at 13:22
  • \$\begingroup\$ @Sandeep: um, you would write another function that opens the file and reads its contents? The initial question did not say anything about files, and, in any case, the encoding function should not concern itself with file operations (easier to grasp, easier to test etc). \$\endgroup\$
    – fjarri
    Commented Aug 14, 2013 at 13:25
  • \$\begingroup\$ yes its perfectly okay for me with out files, but im just curious about it. anyway thanks for one liner @Bogdan \$\endgroup\$
    – Sandeep
    Commented Aug 14, 2013 at 13:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.