I developed a recursive algorithm and wrote it in Python. When I measure the runtime with different parameters, it seems to take exponential time. Moreover; it takes more than an hour and a half to end with small numbers such as 50. (I did not wait until it ends, but it seems that it has not finished within a reasonable period of time, suppose it is exponential).
So, I'm curious about the runtime complexity of this algorithm. Can someone help me get the equation T (n, m)? Or figure out big-oh?
The algorithm below:
def find(search, searchIndex, source, sourceIndex, indexes):
found = None
if searchIndex < len(search):
found = False
while sourceIndex < len(source):
if search[searchIndex] == source[sourceIndex]:
if find(search, searchIndex + 1, source, sourceIndex + 1, indexes):
found = True
if indexes[searchIndex] is None:
indexes[searchIndex] = sourceIndex
elif indexes[searchIndex] != sourceIndex:
indexes[searchIndex] = -1
sourceIndex = sourceIndex + 1
return found if found is not None else True
def theCards(N, colors):
allcards = ['R' if isPrime(i) else 'B' for i in range(1, N + 1)]
indexes = [None] * len(colors)
find(colors, 0, allcards, 0, indexes)
return indexes
if __name__ == "__main__":
print theCards(7, list("BBB"))
I don’t know if I need to understand the problem and the algorithm to get the worst working time, but here is the problem I tried to solve:
Problem:
SRC SEA, SEA SRC , SEA SRC. SEA SRC, -1.
;
BRRBRBR (N = 7), - BBB:
"B" "BBB" 0 . "B" 3 , "B" 5- . ; BBB, , , [0,3,5].
, - BRRBRB (N = 6), - RBR:
"R" "RBR" 1 2. 3 "B" 4 "R" . "R" , . , B R, . , [-1,4,5].
, , - [B, R, R, B, R, B, R, 'B', 'B', 'B', 'R', 'B', 'R', 'B', 'B', 'B', 'R', 'B', 'R', 'B ',' B ',' B ',' R ',' B ',' B ',' B ',' B ',' B ',' R ',' B ',' R ',' B ',' B, B, B, B, B, B, 'B', 'R', 'B', 'B', 'B', 'B', 'B', 'R', 'B', 'B', 'B', 'B', ' 'B'] (N = 58)
- RBRRBRBBRBRRBBRRBBBRRBBBRR. [-1, -1, -1, -1, -1, -1, -1, -1, 17, 18, 19, 23, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 47, 53], , , = (
:
, "" -1 . (, , ) , . . , .
, , T (n, m), n m - .
, ! =)
EDIT - IVIad:
def find2(search, source):
indexes = list()
last = 0
for ch in search:
if last >= len(source):
break
while last < len(source) and source[last] != ch:
last = last + 1
indexes.append(last)
last = last + 1
return indexes
def theCards(N, colors):
allcards = ['R' if isPrime(i) else 'B' for i in range(1, N + 1)]
indexes = find2(colors, allcards)
colors.reverse()
allcards.reverse()
indexesreversed = find2(colors, allcards)
indexesreversed.reverse()
indexesreversed = [len(allcards) - i - 1 for i in indexesreversed]
return [indexes[i] + 1 if indexes[i] == indexesreversed[i] else - 1 for i in range(0, len(indexes))]
if __name__ == "__main__":
print theCards(495, list("RBRRBRBBRBRRBBRRBBBRRBBBRR"))