0

Currently I have a list of substitutions for specific letters in the alphabet. The letter a is replaced by whatever value is at the first index, b with whatever is at the second index, and so on.

One feature that I appreciate in Python is the ability to perform list comprehensions. However, when I attempted to perform this with concatenation, I did not get positive results.

letters = ["ka","zu","mi","te","ku","lu","ji","ri","ki","zu","me","ta","rin","to","mo",
           "no","ke","shi","ari","chi","do","ru","mei","na","fu","zi"]

def nameToNinja(str):
    name = ""
    for i in str:
        i=i.lower()
        if ord(i) >= 97 and ord(i) <= 122:
            name+= letters[ord(i.lower()) - 97]
        else:
            name += i
    return name


name = "Obama"
print("Your ninja name is: {0}".format(nameToNinja(name)))

My attempt at turning the function into a list comprehension in Python does not work. In fact, the only error I am receiving is Syntax Error.

Attempt:

def nameToNinja(str):
    return ''.join([letters[ord(i.lower()) - 97] if ord(i.lower()) >= 97 and ord(i.lower()) <= 122 else i 
    for i in str)

What is the correct way to shorten the original function into a concatenated list comprehension.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161
Veer Singh
  • 913
  • 2
  • 11
  • 26

3 Answers3

2
letters = ["ka","zu","mi","te","ku","lu","ji","ri","ki","zu","me","ta","rin","to","mo","no","ke","shi","ari","chi","do","ru","mei","na","fu","zi"]

def nameToNinja(str):
    return ''.join([letters[ord(i.lower()) - 97] if (97 <= ord(i.lower()) <= 122) else i.lower() for i in str])

name = "Obama"
print("Your ninja name is: {0}".format(nameToNinja(name)))
corinna
  • 629
  • 7
  • 18
2

This calls .lower() only once per letter:

def name_to_ninja(s):
    return ''.join(letters[ord(x) - 97] if ord(x) >= 97 and ord(x) <= 122 else x 
                   for x in (y.lower() for y in s))
name = "Obama"
print("Your ninja name is: {0}".format(name_to_ninja(name)))

Output:

Your ninja name is: mozukarinka
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
-1
letters = ["ka","zu","mi","te","ku","lu","ji","ri","ki","zu","me","ta","rin","to","mo","no","ke","shi","ari","chi","do","ru","mei","na","fu","zi"]

name = "Obama"

ninja_name = ''.join(
        [letters[ord(i)-ord('a')] if i.islower() else i for i in name]
        )

print("Name:", name, "Ninjaname:", ninja_name)
aghast
  • 14,785
  • 3
  • 24
  • 56
  • 2
    This isn't quite the same: consider what happens to a letter which is originally uppercase. – DSM Apr 15 '16 at 04:04
  • Compare your result `Ozukarinka` to the desired result `mozukarinka`. You should always test your solution. – Mike Müller Apr 15 '16 at 09:36