I'm not able to solve an exercise. The statement is as follows:
A word was compressed to an integer using the following algorithm:
- Each capital letter from A to Z was mapped to a number between 1 and 26, with the letter A represented by the number 1, the letter B by the number 2 and so on.
- The value of the first letter of the word was placed in the first 5 bits, the least significant, of the integer, the second letter was placed in the next 5 bits and so on, until the last letter of the word.
- After placing each letter in the integer, the remaining bits of the integer were left as 0.
Your task is to recover the original word, given the integer that represents it. To do this, implement a recursive function called decompress that takes the integer x as an argument and returns the original word.
Input
There is no data entry, the function is called for arbitrary values defined in test cases with integer values 0 < x
Output
The function must return a string containing the original word represented by the integer x supplied to the function.
Note
In the first example, the value 65 when divided by 2⁵ generates remainder 1. This value represents the letter 'A'. The same value 65 when the entire division by 2⁵ generates a value of 2. Therefore, the algorithm is executed recursively. In the second execution, the rest of the division of 2 by 2⁵ generates a value of 2 representing the letter 'B'. The entire division generates a zero value indicating end of execution.
For example:
|-----------------------------|------------------|
| Test | Result |
|-----------------------------|------------------|
|print(decompress(65)) | AB |
|-----------------------------|------------------|
|print(decompress(54579234)) | BATATA |
|-----------------------------|------------------|
|print(decompress(6040945729))| ABACATE |
|-----------------------------|------------------|
How can I do it using only one recursive function? So far I've only managed to use two functions, one of which calculates in relation to the integers of which represent the letters of the alphabet and the other to show the formed word
restos = []
palavra_formada = []
alfabeto = {
1: 'A',2: 'B',3: 'C',4: 'D',5: 'E',6: 'F',7: 'G',8: 'H',9: 'I',10: 'J',11: 'K',12: 'L',
13: 'M',14: 'N',15: 'O',16: 'P',17: 'Q',18: 'R',19: 'S',20: 'T',21: 'U',22: 'V',23: 'W',
24: 'X',25: 'Y',26: 'Z',
}
def aux(n):
if n == 0:
return 0
elif n == 1:
restos.append(n % 32)
return 1
else:
restos.append(n % 32)
return aux(n // 32)
def decompress(n):
aux(n)
palavra_resultante = ""
for i in restos:
palavra_formada.append(alfabeto[i])
for j in palavra_formada:
palavra_resultante += j
return palavra_resultante
auxas well, produce the result as a string instead of a list, and return it instead of storing it in a global variable. Then you don't needdecompressanymore (so you can renameauxtodecompress).stringmodule (.ascii_uppercase?) instead of writing out the alphabet