Home > Back-end >  how to increment any string [input] by 3 then output the resulting string in python
how to increment any string [input] by 3 then output the resulting string in python

Time:01-12

I tried using asciii and tried ord() but I could not use the input of the user and increment it by 3 letters. For example I want to be able to have the following scenario:

input: ABC output: DEF and also! input: xyzab output: abcde

its starting to be mind boggling for me.

for those who wonder this is just a challenge I encountered in the blackhat event last year in Riyadh and obviously couldn't beat.

CodePudding user response:

you can use modulo arithmetic to handle the cases near the end

def shift(text):
    result = ""
    for i in range(len(text)):
        char = text[i]
        if (char.isupper()):
            result  = chr((ord(char)   3 - 65) % 26   65)
        else:
            result  = chr((ord(char)   3 - 97) % 26   97)
    return result

print(shift("ABC"))

print(shift("xyzab"))

CodePudding user response:

for lower and upper english language alphabets, you can use below code

def func(string, increment):
    result = []
    orders = [65, 97]

    for idx, char in enumerate(string):
        is_lower = char.islower()
        new_char = chr(orders[is_lower]   (ord(char)%orders[is_lower]  increment)&)
        result.append(new_char)

    return ''.join(result)


string = "xyzab"
result = "abcde"
assert result == func(string, 3)
  • Related