Before posting the solutions on the blog, I solve them on Coderbyte. Thus, when I have started writing the post, I have observed that my initial solution makes use of two for loops. That means the initial solution has a quadratic time complexity – O(N^2), which is not desired. However, the new solution is making use of only one for loop, and the new time complexity is O(N) – linear time complexity.
Proceeding further, the requirements for the challenge are as follows:
Have the function ASCIIConversion(str) take the str parameter being passed and return a new string where every character, aside from the space character, is replaced with its corresponding decimal character code. For example: if str is “dog” then your program should return the string 100111103 because d = 100, o = 111, g = 103. Use the Parameter Testing feature in the box below to test your code with different arguments.
The first step is to create a new variable that will store the new string, composed of the decimal character code of each character.
def ASCIIConversion(string): newStr = ''
To convert each character from the string to its corresponding decimal character code, I am using a for loop. This for loop iterates over each character from the string and converts it to its ASCII code. One exception is when the character is a space. If the character is a space, then that space is added to the new string as well.
def ASCIIConversion(string): newStr = '' for chr in string: if chr.isspace(): newStr = newStr + ' ' else: newStr += str(ord(chr))
The solution also makes use of three Python functions – isspace(), str(), which are self-explanatory and ord. The ord function returns the character’s corresponding ASCII code. Since it returns a number, it is converted back to a string using the str function. The reason for doing this is that the ASCII code is concatenated to the new string.
The last step is to return the newly created string, representing the ASCII code of the initial string. Thus, below is the second solution that uses only one for loop – O(N).
def ASCIIConversion(string): newStr = '' for chr in string: if chr.isspace(): newStr = newStr + ' ' else: newStr += str(ord(chr)) return newStr
Below is the initial solution, which uses two for loops – O(N^2).
def ASCIIConversion(string): words = string.split() newStr = '' for word in words: for chr in word: newStr += str(ord(chr)) newStr += ' ' return newStr
Suggestions for improvements or different solutions are highly appreciated. Thus, leave a comment!