Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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
share|improve this question
1  
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. –  Bogdan Aug 14 '13 at 13:04
 
@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 –  Sandeep Aug 14 '13 at 13:08
add comment

1 Answer

up vote 1 down vote accepted

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)])
share|improve this answer
 
thnx fr tht @Bogdan? –  Sandeep Aug 14 '13 at 13:20
 
What if i have to get input from a file and output the enocoded string to another file? –  Sandeep Aug 14 '13 at 13:22
 
@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). –  Bogdan Aug 14 '13 at 13:25
 
yes its perfectly okay for me with out files, but im just curious about it. anyway thanks for one liner @Bogdan –  Sandeep Aug 14 '13 at 13:28
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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