In: Computer Science
3. The Hofstadter Conway sequence is defined by a(1)=a(2)=1 and (for n>2 by) a(n)=a(a(n-1))+a(n-a(n-1)). Write a function to quickly compute this sequence.
>>> [hc(i) for i in range(1,20)] [1, 1, 2, 2, 3, 4, 4, 4, 5, 6, 7, 7, 8, 8, 8, 8, 9, 10, 11]
The programming language used is Python 3.8.
The function name is hc() which takes in the parameter value n.
The code snippet of the function is:
def hc(n):
List = [0, 1, 1]
if n<= 0:
return 0
if n==1:
List.pop(0)
List.pop(1)
print(List)
elif n==2:
List.pop(0)
print(List)
else:
for i in range(3,n+1):
List.append( List[List[i - 1]] + List[i - List[i - 1]])
List.pop(0)
print(List)
Initially a list List[] is created with values 0,1,1 in it.
And based on the value of n passed to it the contents in the list is printed.
If the value of n is less than or equal to 0 no output will be printed.
List.pop() function was used to remove the value 0 from the list List[] as this value was only added for calculations.
The screenshot of the code and the output generated is attached for your reference:
Hope it helps!!!