I'm starting off with python after having done C++ for a few years, so i'm still fresh on it's features. Hence, any improvements on how to make the code more "Pythonic" would be appreciated.
Now the problem. It works perfectly on my machine, but keeps giving a runtime error (NZEC) at SPOJ.
I admit my solution is a bit more twisted than it should be, but there is no reason for it not to work
def unique(s):
n = len(s)
if n == 0:
return []
u = {}
try:
for x in s:
u[x] = 1
except TypeError:
del u # move on to the next method
else:
return u.keys()
try:
t = list(s)
t.sort()
except TypeError:
del t # move on to the next method
else:
assert n > 0
last = t[0]
lasti = i = 1
while i < n:
if t[i] != last:
t[lasti] = last = t[i]
lasti += 1
i += 1
return t[:lasti]
# Brute force is all that's left.
u = []
for x in s:
if x not in u:
u.append(x)
return u
def xcombinations(items, n):
if n == 0:
yield []
else:
for i in xrange(len(items)):
for cc in xcombinations(items[:i] + items[i+1:], n-1):
yield [items[i]] + cc
def empty(li):
if li == []:
return False
else:
return True
# test the above functions ... the main part begins here
P='W'
F='L'
tests=input()
for count in range(0,tests):
somearray = map(str, raw_input().split())
num=int(somearray[0])
pw =float(somearray[1]) #pw - winning probability , pl - losing probability
pl =1-pw
charList=[]
k=0
for i in range(0,num):
charList.append(P)
size = len(charList)-1
finalprob=0
for k in range (0,num+1):
for l in range(0,k):
charList.pop(l)
charList.insert(l,F)
result1 =[]
for pm in xcombinations(charList,size+1):
result1.append(pm)
result=unique(result1)
x=[]
a=[]
for x in result:
if x[size]=='L':
a.append(result.index(x))
for ele in a:
result[ele]=[]
result2 = filter(empty,result)
prob=0
for opt in result2:#the logic checks the previous match to decide current probability
AW=pw
AL=pl #initializing
if(opt[0]=='W'):
prob1=AW
elif(opt[0]=='L'):
prob1=AL
#for all the rest
for h in range(1,num):
if opt[h-1]=='W':
AW=pl
AL=pw
elif opt[h-1]=='L':
AW=pw
AL=pl
if(opt[h]=='W'):
prob1*=AW
elif(opt[h]=='L'):
prob1*=AL
prob+=prob1
finalprob+=prob
del result2[0:]
str(finalprob)
print finalprob