Why my code is getting NZEC run time error? - python

Question source: SPOJ.. ORDERS
def swap(ary,idx1,idx2):
tmp = ary[idx1]
ary[idx1] = ary[idx2]
ary[idx2] = tmp
def mkranks(size):
tmp = []
for i in range(1, size + 1):
tmp = tmp + [i]
return tmp
def permutations(ordered, movements):
size = len(ordered)
for i in range(1, size): # The leftmost one never moves
for j in range(0, int(movements[i])):
swap(ordered, i-j, i-j-1)
return ordered
numberofcases = input()
for i in range(0, numberofcases):
sizeofcase = input()
tmp = raw_input()
movements = ""
for i in range(0, len(tmp)):
if i % 2 != 1:
movements = movements + tmp[i]
ordered = mkranks(sizeofcase)
ordered = permutations(ordered, movements)
output = ""
for i in range(0, sizeofcase - 1):
output = output + str(ordered[i]) + " "
output = output + str(ordered[sizeofcase - 1])
print output

Having made your code a bit more Pythonic (but without altering its flow/algorithm):
def swap(ary, idx1, idx2):
ary[idx1], ary[idx2] = [ary[i] for i in (idx2, idx1)]
def permutations(ordered, movements):
size = len(ordered)
for i in range(1, len(ordered)):
for j in range(movements[i]):
swap(ordered, i-j, i-j-1)
return ordered
numberofcases = input()
for i in range(numberofcases):
sizeofcase = input()
movements = [int(s) for s in raw_input().split()]
ordered = [str(i) for i in range(1, sizeofcase+1)]
ordered = permutations(ordered, movements)
output = " ".join(ordered)
print output
I see it runs correctly in the sample case given at the SPOJ URL you indicate. What is your failing case?

Related

how do i leave the list with only 1 person

The problem:
https://www.beecrowd.com.br/judge/problems/view/1032
I can't get the numbers out of the people list, this method I did gives the error "pop index out of range".
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# PRIME LIST
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
from audioop import reverse
numerosPrimos = 3501
primos = []
for i in range(2, numerosPrimos + 1):
for j in range(2, int(i ** 0.5) + 1):
if i % j == 0:
break
else:
primos.append(i)
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# PEOPLE LIST
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
numeroPessoas = int(input())
pessoas = []
for l in range(1, numeroPessoas + 1):
pessoas.append(l)
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# REMOVING PEOPLE
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# pessoasEliminada = pessoas
p = primos[0]
pessoas.sort(reverse=True)
mult = 1
while len(pessoas) >= 1 and p <= 3501:
pessoas.pop(len(pessoas) - p)
print(pessoas)
p = p + p

Program does not print the return value of a function

I have a piece of code to calculate one matrix from another. But when I try to print the output of the function the code runs without any errors but does not print anything. Furthermore, if I try to print the input matrix to the function and then call the function, the original input does not get printed. It prints fine when I don't call this function inf_mat. Does anybody know what might be the reason?
import numpy as np
from itertools import permutations
def inf_mat(adjacency, l_max):
## Influence matrix - Returns the influence matrix corresponding to the input adjacency matrix
inf_arr = np.zeros(np.shape(adjacency))
print(inf_arr)
norm_mat = adjacency
for i in range(np.shape(norm_mat)[0]):
for j in range(np.shape(norm_mat)[1]):
if norm_mat[i,j] != 0:
norm_mat[i,j] = 1
for i in range(np.shape(inf_arr)[0]):
for j in range(np.shape(inf_arr)[1]):
ind_lists = []
for k in range(l_max-1):
all_ind = [m for m in range(np.shape(adjacency)[1])]
all_ind.remove(i)
if j != i:
all_ind.remove(j)
ind_lists.append(list(permutations(all_ind, k+1)))
pairwise_list = []
for p in range(len(ind_lists)):
pairs = []
for q in range(len(ind_lists[p])):
mult_list = [i]
for r in range(len(ind_lists[p][q])):
mult_list.append(ind_lists[p][q][r])
mult_list.append(j)
pairs.append(mult_list)
pairwise_list.append(pairs)
inf_sum = adjacency[i,j]
norm_sum = norm_mat[i,j]
for t in range(len(pairwise_list)):
for t_ind in range(len(pairwise_list[t])):
inf_ele = 1
norm_ele = 1
for s in range(len(pairwise_list[t_ind])-1):
inf_ele *= adjacency[s,s+1]
norm_ele *= norm_mat[s,s+1]
inf_sum += inf_ele
norm_sum += norm_ele
inf_arr[i,j] = inf_sum/norm_sum
return inf_arr/l_max
def readFile(Filename):
fileObj = open(Filename, "r")
words = fileObj.read().splitlines()
fileObj.close()
return words
topo_list = readFile("EMT_RACIPE.topo")
topo_list.remove(topo_list[0])
gene_list = []
for i in range(len(topo_list)):
topo_list[i] = topo_list[i].split()
for j in range(2):
if gene_list.count(topo_list[i][j]) == 0:
gene_list.append(topo_list[i][j])
adjacency = np.zeros(shape = (len(gene_list),len(gene_list)))
for i in range(len(gene_list)):
indices = []
for j in range(len(topo_list)):
if topo_list[j].count(gene_list[i]) > 0:
indices.append(j)
for k in range(len(indices)):
if topo_list[indices[k]][0] == gene_list[i]:
if topo_list[indices[k]][2] == '1':
adjacency[i, gene_list.index(topo_list[indices[k]][1])] = 1
if topo_list[indices[k]][2] == '2':
adjacency[i, gene_list.index(topo_list[indices[k]][1])] = -1
if topo_list[indices[k]][1] == gene_list[i]:
if topo_list[indices[k]][2] == '1':
adjacency[gene_list.index(topo_list[indices[k]][0]), i] = 1
if topo_list[indices[k]][2] == '2':
adjacency[gene_list.index(topo_list[indices[k]][0]), i] = -1
N22E82 = adjacency
print(N22E82)
inf_N22E82 = inf_mat(N22E82, 10)
print(inf_N22E82)

How to give each Category a color?

We have a code to draw circles on the Location on the map with the name of each category. Now the circles and text are one color. How do we get them in different color's by category? Example: Category Garden: Blue, Category Stone: Grey.
So far the code:
size(1500,800)
background(1)
nofill()
stroke('#f91')
pen(.2)
fill('#f91', 0.05)
rotate(90)
font("Avenir", "bold", 10)
align('left')
def mapValue(value, fromMin, fromMax, toMin, toMax):
# Figure out how 'wide' each range is
fromSpan = fromMax - fromMin
toSpan = toMax - toMin
# Convert the from range into a 0-1 range (float)
valueScaled = float(value - fromMin) / float(fromSpan)
# Convert the 0-1 range into a value in the to range.
return toMin + (valueScaled * toSpan)
def xOfDot(lon):
return mapValue(lon, -100, 100, 0, WIDTH)
def yOfDot(lat):
return mapValue(lat, -90, 90, HEIGHT, 0)
with open('theft-alerts.json', 'r') as inputFile:
data = json.load(inputFile)
print len(data)
artworksPerCity = {}
for stolenArt in data:
if stolenArt.has_key('Category'):
city = stolenArt['Category']
if stolenArt.has_key('nItemsStolen'):
numbersStolen = int(stolenArt['nItemsStolen'])
if artworksPerCity.has_key(city):
# Adjust the value stored for this city
artworksPerCity[city] = artworksPerCity[city] + numbersStolen
else:
# Create new key with new value
artworksPerCity[city] = numbersStolen
# Draw circle on the map
radius = artworksPerCity[city] /2
x = xOfDot(stolenArt['Lon'])
y = yOfDot(stolenArt['Lat'])
arc(x, y, radius)
text(city, x, y)
print artworksPerCity
Here is a sketch of what I intend to include in my pure python data utility.
def hexidecimalDiget(n,deHex = false):
if(n<0):
print "negitive values not supported by call to hexidecimalDiget("+str(n)+")"
return None
elif(n < 10):
return str(n)
elif(n < 15):
return ["a","b","c","d","e"][n-10]
elif(n in ["a","b","c","d","e"]):
if deHex:
return ["a","b","c","d","e"].index(n)
return n
else:
print "call to hexidecimalDiget("+str(n)+") not supported!"
return None
def colorFormHexArray(arr):
if len(arr)!=3 and len(arr)!=6:
print "invalid length for color on call to colorFormHexArray("+str(arr)+")"
return None
elif None in arr:
print "cannot make color from None arguments in "+str(arr)
return None
else:
ret = "#"
for k in arr:
if(type(k) == list):
for k2 in k:
ret+=hexidecimalDiget(k)
else:
ret+=hexidecimalDiget(k)
return ret
def arrayFromColor(c):
c = c.replace("#","")
col = []
for n,k in enumerate(c):
if(len(c) == 3):
col.append([hexidecimalDiget(k,deHex = True)])
elif(len(c) == 6):
col.append([hexidecimalDiget(c[(n+1)*2-2],deHex = True),hexidecimalDiget(c[(n+1)*2-2],deHex = True)])
return(col)
def intFromHexPair(hp):
ret = 0
for n,k in enumerate(hp):
digBase = 16**(len(hp)-n-1)
ret+=digBase*hexidecimalDiget(hp[0],deHex = True)
return ret
def hexPairFromInt(I,minDigits = 1,maxDigits = 256):
if I<0:
print "negitive numbers not supported by hexPairFromInt"
k= 0
while(16**(k+1) <= I):
k+=1
if k < minDigits:
k = minDigits
if k > minDigits:
print("maxDigitsExceeded")
ret = []
while k>=0
dig = 16**k
ret.append(hexidecimalDiget(int(I)%(dig))
I -= dig
k-=1
return ret
def specColor(start,end,bottom,top):
start = arrayFromColor(start)
end = arrayFromColor(end)
def ret(v):
if( v<start or c>end ):
print("value out of range "+str([start,end]))
return('#aa0000') #eyo <- error red
else:
starts = [intFromHexPair(k) for k in start]
ends = [intFromHexPair(hp) for k in end]
normalized = (v-bottom)/(top-bottom)
return colorFormHexArray([hexPairFromInt(int((starts[n]-ends[n])*normalized),minDigits = 1,maxDigits = 256) for n,k in enumerate(starts)])
return ret
This seems excessive and hasn't even been slightly tested yet (just a stetch up atm) but I'll be testing and incorporating this code here tonight :: http://krewn.github.io/KPlot/

The cmd is taking forever to run a python program

For some reason, the cmd is taking 2 minutes to run a 18 line python program. I ran it again but it did not do anything.
Can anyone tell me why it is taking that long?
from array import *
file = open("IntegerArray.txt" , "r")
input_array = array('i')
for line in file:
c = int(line)
input_array.append(c)
top_array = input_array[:len(input_array)//2]
bottom_array = input_array[len(input_array)//2:]
inversion = 0
max_index = len(top_array)
for i in range(0, max_index):
for j in range(i + 1, max_index):
if top_array[i] > top_array[j]:
temp = top_array[i]
top_array[i] = top_array[j]
top_array[j] = temp
inversion = inversion + 1
print "inversion = ", inversion
Not related to the time, but you can simplify this:
temp = top_array[i]
top_array[i] = top_array[j]
top_array[j] = temp
to
top_array[i], top_array[j] = top_array[j], top_array[i]

Memory overflow in Python

I have 67000 files, I need to read them and extract similarities between the words, but when I run the code my laptop becomes much slower, I can't open any other application, and then a memory overflow error shows up (even when I run on around 10 000 of the files). Is there a way to clear the memory after every for loop maybe, or will running the code on all files be impossible to do? Below is the code:
def isAscii(s):
for c in s:
if c not in string.printable:
return False
return True
windowSize = 2
relationTable = {}
probabilities = {}
wordCount = {}
totalWordCount = 0
def sim(w1, w2):
numerator = 0
denominator = 0
if (w1 in relationTable) and (w2 in relationTable):
rtw1 = {}
rtw2 = {}
rtw1 = relationTable[w1]
rtw2 = relationTable[w2]
for word in rtw1:
rtw1_PMI = rtw1[word]['pairPMI']
denominator += rtw1_PMI
if(word in rtw2):
rtw2_PMI = rtw2[word]['pairPMI']
numerator += (rtw1_PMI + rtw2_PMI)
for word in rtw2:
rtw2_PMI = rtw2[word]['pairPMI']
denominator += rtw2_PMI
if(denominator != 0):
return float(numerator)/denominator
else:
return 0
else:
return -1
AllNotes = {}
AllNotes = os.listdir("C:/Users/nerry-san/Desktop/EECE 502/MedicalNotes")
fileStopPunctuations = open('C:/Users/nerry-san/Desktop/EECE 502/stopPunctuations.txt')
stopPunctuations = nltk.word_tokenize(fileStopPunctuations.read())
for x in range (0, 10):
fileToRead = open('C:/Users/nerry-san/Desktop/EECE 502/MedicalNotes/%s'%(AllNotes[x]))
case1 = fileToRead.read()
text = nltk.WordPunctTokenizer().tokenize(case1.lower())
final_text = []
for index in range(len(text)):
word = text[index]
if (word not in stopPunctuations):
final_text.append(word)
for index in range (len(final_text)):
w1 = final_text[index]
if(isAscii(w1)):
for index2 in range(-windowSize, windowSize+1):
if (index2 != 0):
if ( index + index2 ) in range (0, len(final_text)):
w2 = final_text[index + index2]
if(isAscii(w2)):
totalWordCount += 1
if (w1 not in wordCount):
wordCount[w1] = {}
wordCount[w1]['wCount'] = 0
try:
wordCount[w1][w2]['count'] += 1
wordCount[w1]['wCount'] += 1
except KeyError:
wordCount[w1][w2] = {'count':1}
wordCount[w1]['wCount'] += 1
for word in wordCount:
probabilities[word]={}
probabilities[word]['wordProb'] = float (wordCount[word]['wCount'])/ totalWordCount
for word in wordCount:
relationTable[word] = {}
for word2 in wordCount[word]:
if ( word2 != 'wCount'):
pairProb = float(wordCount[word][word2]['count'])/(wordCount[word]['wCount'])
relationTable[word][word2] = {}
relationTable[word][word2]['pairPMI'] = math.log(float(pairProb)/(probabilities[word]['wordProb'] * probabilities[word2]['wordProb']),2)
l = []
for word in relationTable:
l.append(word)
for index in range (0, len(l)):
word = l[index]
simValues = []
for index2 in range (0, len(l)):
word2 = l[index2]
if(word!= word2):
simVal = sim(word,word2)
if(simVal > 0):
simValues.append([word2, simVal])
simValues.sort(key= operator.itemgetter(1), reverse = True)
Every time you open a file, use the "with" statement. This will ensure the file is closed when the loop finishes (or rather when the with block is exited.

Categories

Resources