We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
import math
import os
import random
import re
import sys
#
Complete the 'countArray' function below.
#
The function is expected to return a LONG_INTEGER.
The function accepts following parameters:
1. INTEGER n
2. INTEGER k
3. INTEGER x
#
def _build_dp(last, s, array, rest, x, n):
if len(rest)>n:
return 0
if n==2:
if s!=x:
return 1
else:
return 0
_count=0
if (len(rest)==n):
for i in rest:
if i!=s:
_count+=_build_dp(s, i, array, [ j for j in rest if j!=i ], x, n-1)
else:
for i in array:
if i!=s:
_count+=_build_dp(s, i, array, [ j for j in rest if j!=i ], x, n-1)
return _count
def countArray(n, k, x):
_count=0
for i in range(2, k+1):
_count+=_build_dp(1, i, range(1, k+1), [ i for i in range(2, k+1) if i!=x], x, n-1)
return _count
if name == 'main':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input[0])
k = int(first_multiple_input[1])
x = int(first_multiple_input[2])
answer = countArray(n, k, x)
fptr.write(str(answer) + '\n')
fptr.close()
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Construct the Array
You are viewing a single comment's thread. Return to all comments →
how to avoid recusrion?
!/bin/python3
import math import os import random import re import sys
#
Complete the 'countArray' function below.
#
The function is expected to return a LONG_INTEGER.
The function accepts following parameters:
1. INTEGER n
2. INTEGER k
3. INTEGER x
#
def _build_dp(last, s, array, rest, x, n): if len(rest)>n: return 0 if n==2: if s!=x: return 1 else: return 0
_count=0 if (len(rest)==n): for i in rest: if i!=s: _count+=_build_dp(s, i, array, [ j for j in rest if j!=i ], x, n-1) else: for i in array: if i!=s: _count+=_build_dp(s, i, array, [ j for j in rest if j!=i ], x, n-1) return _count
def countArray(n, k, x): _count=0 for i in range(2, k+1): _count+=_build_dp(1, i, range(1, k+1), [ i for i in range(2, k+1) if i!=x], x, n-1) return _count
if name == 'main': fptr = open(os.environ['OUTPUT_PATH'], 'w')