In: Computer Science
Question: Reverse engineering (Python if possible)
In the FizzBuzz question, it's an exercise to calculate a value based on whether the input was divisible by 3, 5, or both. If we looped that function through integers from one, the first 10 return values would be:
None # For input 1 None # For input 2 '3' None '5' '3' None None '3' '5'
In this exercise, we'll try to reverse engineer the output of a similar process.
The sequence of numbers is generated as follows. Instead of checking division by 3 and 5, we have designated, say, three numbers 2, 4, 5. Whenever the input is divisible by 2, our output will include the letter a, when by 4, the letter b, when by 5, the letter c. Otherwise there is no output. So the generated sequence from one onwards would be
None # for input 1 'a' # for input 2 None # for input 3 'ab' # for input 4 'c' 'a' None 'ab' None 'ac' # for input 10
To make things interesting, we will not include the None values, giving us the sequence
'a' 'ab' 'c' 'a' 'ab' 'ac'
This is the input for the exercise. Your task is to "reverse engineer" a, b, c from the sequence. That is, you'll infer what integer values each letter corresponds to. There are multiple possible solutions: your solution should pick the lowest possible values.
Here's another example:
'a' 'b' 'a' 'a' 'b' 'a'
The solution is a = 3, b = 5. (You may confirm these are the lowest possible values that match the sequence.)
Complete the function reverse_engineer. Note that the test cases may have up to twenty different letters to reverse engineer and up to four-digit integers as solutions.
Code screenshot:
reverse_engg.py
def rev_engg(divisors,n):
# List that stores result
res = []
# From integers 1 to n
for i in range(1,n+1):
# Initilize an empty string
s = ''
# Check for each divisor
for j in
range(len(divisors)):
# If i is
divisible
if
i%divisors[j]==0:
# Then append corresponding character
s += chr(97+j)
# If string is not empty then
append s to res
if s!='':
res.append(s)
# Return res
return res
# Function calling
print(rev_engg([3,5],10))
print(rev_engg([2,4,5],10))
output screenshot: