1

so Im working on a codesignal problem, and these are the instructions:

Given a string, your task is to replace each of its characters by the next one in the English alphabet; i.e. replace a with b, replace b with c, etc (z would be replaced by a).

Example

For inputString = "crazy", the output should be alphabeticShift(inputString) = "dsbaz".

Input/Output

[execution time limit] 4 seconds (py3)

[input] string inputString

A non-empty string consisting of lowercase English characters.

Guaranteed constraints:
1 ≤ inputString.length ≤ 1000.

[output] string

The resulting string after replacing each of its characters.

this is my code:

def alphabeticShift(inputString):
    abc = "abcdefghijklmnopqrstuvwxyza"
    newString = ""
    for letter in inputString:
        abcIndex = 0
        for abcletter in abc:
          
          if letter == abcletter:
              newString = newString+abc[abcIndex+1]
          abcIndex = abcIndex+1
    return newString

print(alphabeticShift("*_fArgs_uiutgbodsupy"))

I have tried my code in replit and it executes just fine but I keep getting this error when I put it in codesignal:

Traceback (most recent call last):

  File main.py3 in the pre-written template, in getUserOutputs
    userOutput = _rundngpj(testInputs[i])

  File main.py3 in the pre-written template, in _rundngpj
    return alphabeticShift(*_fArgs_asixuqfdhzqc)

  File main.py3 on line 10, in alphabeticShift
    newString = newString+abc[abcIndex+1]
IndexError: string index out of range

I dont know what I am missing as i dont see how anything could be out of range?

2 Answers 2

4

Add a break statement inside the if condition.

if letter == abcletter:
    newString = newString+abc[abcIndex+1]
    break

The reason it fails is when you encounter a, you are trying to replace it twice, once at the start and once in the end of abc which fails.

Sign up to request clarification or add additional context in comments.

Comments

1

You don't exit your for abcLetter loop after having found a letter, and a is there twice. So when letter is "a", you add "b", then you continue to loop, find the other "a" and try to add the letter after it as well — but there is none. A break after you append the letter will fix it.

That said, there is much here that is non-idiomatic, the solution can be much simpler — e.g. by using str.translate:

shift = str.maketrans(
  'abcdefghijklmnopqrstuvwxyz',
  'bcdefghijklmnopqrstuvwxyza',
)
def alphabeticShift(inputString):
    return inputString.translate(shift)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.