Kick start RE (Test set skipped) error using python - python

I was practicing on google kick start Round A 2016 ( Country Leader ) but iam getting error that says Runtime error and can't figure what is wrong.
here is my code
First one :
T = int(input().strip())
tries = []
for i in range(1, T + 1):
N = int(input().strip())
persons = list()
for t in range(1, N + 1):
persons.append(input().strip())
tries.append(persons)
winners = []
for t in tries:
points = 0
temp = ''
for per in t:
per_ltr = per.replace(' ','')
if len(set(per_ltr)) > points:
points = len(set(per_ltr))
temp = per
winners.append(temp)
num = 1
for one in winners:
print(f'Case #{num}: {one}')
num += 1
another one :
T = int(input())
winner = []
for i in range(T):
N = int(input())
persons = []
for j in range(N):
persons.append(input())
points = len(set(persons[0]))
temp = persons[0]
for per in persons:
if len(set(per)) > points:
points = len(set(per))
temp = per
winner.append(temp)
num = 1
for one in winner:
print(f'Case #{num}: {one}')
num += 1

Related

how to select a value referring to the last repeated item in a list

I have 5 columns ( NO = index of vehicle / LEADER = index of the vehicle of the front / SEC = instant in seconds / X = position of the vehicle)
Some vehicles stop ( X stay the same for a while) and I want to get the exact time it starts to move again. Then, calculate the difference between their instant and their respective 'leader' vehicle.
I made a code but it has so many bugs
OBS: Some vehicles never stop or stop,but never return to move. I want to remove them too.
Here's my code:
dados = pd.read_excel('teste-reaction_001.xlsx')
n=dados["NO"].unique()
final=np.zeros(1)
for i in n:
botao = 0
array_aux=dados[dados["NO"] == i ]["X"]
df = pd.DataFrame(array_aux)
aux=df.diff().to_numpy()
count1 = 0
aux1 = []
for j in aux:
if j == 0:
botao = 1
elif j != 0 and botao == 1:
aux1=np.where(aux==j)[0]
aux1=aux1[np.where(aux1>=count1)[0]]
break
else :
botao = 0
count1 = count1 + 1
aux2=dados["SEC"][dados[dados["NO"]==i]["SEC"].index[aux1]].values[0]
final=np.append(final,aux2)
tr=np.zeros(1)
for i in n:
aux=dados[dados["NO"] == i ]["LEADER"].unique()[0]
aux1=np.where(dados["NO"].unique()==i)[0]
aux2=np.where(dados["NO"].unique()==aux)[0]
if aux2>-1:
aux3=final[int(aux1)]-final[aux2]
else:
aux3 = "s"
tr=np.append(tr,aux3)
columns = ["N", "TR"]
tabela = np.array([dados["NO"].unique(), tr[1:]])
res = pd.DataFrame(data=tabela.T,index=np.arange(len(tabela.T)), columns=columns)

the code show bad input and index out of range on the lines, how can i fix it

what‘s the problem with my code and how can I fix it.
The problems are in lines:
world[r].append(element)
world = createWorld()
world = createWorld()
Now I show all of the code, but it seems too long need more text to make it available to post, so ignore this part.so ignore this part.so ignore this part.so ignore this part.so ignore this part.so ignore this part.so ignore this part.so ignore this part.so ignore this part.so ignore this part.so ignore this part.
This was the error given:
IndexError: list index out of range
There are more details in the code below, appreciate it if you can help:)
import random
SIZE = 4
EMPTY = " "
PERSON = "P"
PET = "T"
POOP = "O"
ERROR = "!"
CLEANED = "."
MAX_RANDOM = 10
def clean(world, endRow, endColumn):
print("Scooping the poop")
for r in range(SIZE):
for c in range(SIZE):
if world[r][c] == POOP:
world[r][c] = CLEANED
def count(world, endRow, endColumn):
print("Counting number of occurances of a character")
number = 0
element = input("Enter character: ")
for r in range(SIZE):
for c in range(SIZE):
if world[r][c] == element:
number += 1
return(element, number)
def createElement():
tempNum = random.randrange(MAX_RANDOM)+1
if ((tempNum >= 1) and (tempNum <= 5)):
tempElement = EMPTY
elif ((tempNum >= 6) and (tempNum <= 7)):
tempElement = PERSON
elif (tempNum == 8):
tempElement = PET
elif ((tempNum >= 9) and (tempNum <= 10)):
tempElement = POOP
else:
tempElement = ERROR
return(tempElement)
def createWorld():
world = []
r = 0
while (r < SIZE):
world.append([])
c = 0
while (c < SIZE):
element = createElement()
world[r].append(element)
c = c + 1
r = r + 1
return(world)
def display(world):
print("OUR WORLD")
print("========")
r = 0
while (r < SIZE):
c = 0
while (c < SIZE):
print(world[r][c], end="")
c = c + 1
print()
r = r + 1
print("========\n")
def getEndPoint():
endRow = int(input("Enter the row: "))
while not 0 <= endRow <= 3:
print("Invalid input. Row value should be in range 0-3")
endRow = int(input("Enter the row: "))
endColumn = int(input("Enter the column: "))
while not 0 <= endColumn <= 3:
print("Invalid input. Column value should be in range 0-3")
endColumn = int(input("Enter the column: "))
return (endRow, endColumn)
def start():
world = createWorld()
display(world)
endRow, endColumn = getEndPoint()
element, number = count(world, endRow, endColumn)
print("# occurances of %s=%d" % (element, number))
clean(world, endRow, endColumn)
display(world)
start()
You need to update the r value in the outer loop, currently it is being updated in the inner loop.
def createWorld():
world = []
r = 0
while (r < SIZE):
world.append([])
c = 0
while (c < SIZE):
element = createElement()
world[r].append(element)
c = c + 1
r = r + 1
return (world)

google codejam shows python runtime error

This code is for the Google codejam competition. The below code is compiling correctly on my PC and gives the correct result for the sample code. However it is showing runtime error whenever I try to run it on the google website. I have been messing with it for one hour and still have no idea what's wrong with it.
def reversort(reverList):
global totalScore
length = len(reverList)
score = 0
for i in range(length - 1):
minimum = reverList.index(min(reverList[i: ]))
tempList = reverList[i:minimum + 1]
tempList.reverse()
reverList[i: minimum + 1] = tempList
score += minimum - i + 1
totalScore.append(score)
if __name__ == "__main__":
t = int(input())
totalScore = []
rev = []
for i in range(t):
n = int(input())
apen = []
for j in range(n):
apen.append(int(input()))
reversort(apen)
print("Case #{}: {}".format(i+1,totalScore[i]))
rev.append(apen)
try this
reverse = int(input())
for i in range(1, reverse + 1):
a = int(input())
b = list(map(int, input().split()))
out = 0
for index in range(a-1):
min_index = b.index(min(b[index:a]))
b[index: min_index + 1] = reversed(b[index: min_index + 1])
out += (min_index) - (index) + 1
print("Case #{}: {}".format(i, out))

Hash table problem for education perposes

The problem is this:
It is required to create and use the hash table structure in a problem
large number of keys.
Here are the steps:
Creating one million (1,000,000) visits to a department store
and Credit Card Payment.
From the very large number of different cards, a relatively small subset is created
as follows. Credit cards for visits will have
sixteen (16) specific fixed digits eg 1234567890123456,
but in four (4) of the sixteen (16) random positions they will also have
four characters: X, Y, Z, W in random order.
eg 12Y45W789012Z4X6
In the other places the prices are the initial ones.
I have written the codes. Is is supposed to run super fast but it runs super slowly and I don't know why... Currently, I am running my code for 10,000 cards. Could you help me? Please excuse my poor english...
The code is bellow:
import string
import random
import time
random.seed(1059442)
global max_load_factor
max_load_factor = 0.6
def printGreaterThan2(num):
while True:
if num % 2 == 1:
isPrime = True
for x in range(3,int(num**0.5),2):
if num % x == 0:
isPrime = False
break
if isPrime:
return num
num += 1
N = printGreaterThan2(1000)
arr = [ [] for _ in range(N)]
arr = [ None for _ in range(N)]
def CreatNewItem():
letters = "WXZY"
days = ["Mon", "Tue", "Wed" , "Thu" , "Fri", "Sat"]
s = ''
count = 0
num = ['1','2','3','4','5','6','7','8','9','0','1','2','3','4','5','6']
list_a = []
while(count!=4):
a = random.randint(0,15)
b = random.choice(letters)
if b not in num and a not in list_a:
num[a] = b
count = count + 1
list_a.append(a)
s = ''.join(num)
d = random.randint(0,5)
day = days[d]
money = random.randint(10,100)
a = [s,day,money]
return a
def hash(key, tablesize):
sum = 0
for pos in range(len(key)):
sum = sum + ord(key[pos])
hash = sum % tablesize
return hash
#--------------------------------------
def rehash(oldhash , tablesize):
rehash = ( oldhash + 1 ) % tablesize
return rehash
#--------------------------------------
def put2 (arr,a,N,lenght,collitions):
if float(lenght)/float(N) >= max_load_factor:
(arr,N,collitions) = Resize(arr,N,lenght,collitions)
key = a[0]
i = hash(key,N)
j =0
while (True):
if arr[i] is None:
arr[i] = a
lenght = lenght + 1
break
elif arr[i][0] == key:
arr[i][2] = arr[i][2] + a[2]
arr[i][1] = arr[i][1] + a[1]
break
else:
if j == 0 :
collitions = collitions +1
j = 1
i = rehash(i,N)
return (lenght,N,arr,collitions )
#----------------------------------------
def Resize(arr,N,lenght,collitions):
print("resize")
N = printGreaterThan2(2*N)
collitions = 0
arr2 = [ [] for _ in range(N)]
arr2 = [ None for _ in range(N)]
for p in arr:
if p is not None:
(lenght,N,arr2,collitions)=put2(arr2,p,N,lenght,collitions)
return (arr2,N,collitions)
#-----------------------------------------
l = 0
cards = []
collitions = 0
t0 = time.time()
i=0
while i!=10000:
b = CreatNewItem()
(l,N,arr,collitions) = put2(arr,b,N,l,collitions)
i=i+1
t1 = time.time() - t0
print('\ntime is {:0.20f}'.format(t1))

Converting string using list in python

I've been trying to rearrange the string by reversing a particular strings consecutively from the given string input and the limit is given as input.
for example
limit is 3
if input is Hellothegamestarts
output must be Heltolhegemastastr
and it is saved in separate array
The code is:
while True:
t = int(input())
if t == 0:
break
string = raw_input()
string = string.encode('utf-8')
leng = len(string)
r = t/leng
m = []
leng = 0
for i in range(r):
if r % 2 == 0:
l = 0
l = leng + t
for i in range(t):
temp = string[l]
m.append(temp)
l = l - 1
r = r + 1
leng = leng + t
else:
l = 0
l = leng
for i in range(t):
temp = string[l]
m.append(temp)
l = l + 1
r = r + 1
leng = leng + t
print m
the output i got is [] and asks for next input for t.
Any help is appreciated.
Take the blocks in chunks of 3s, and reverse the odd ones, eg:
import re
s = 'Hellothegamestarts'
r = ''.join(
el if idx % 2 == 0 else el[::-1]
for idx, el in enumerate(re.findall('.{,3}', s))
)
# Heltolhegemastastr
Maybe you can try -
t = int(input())
if t == 0:
break;
string = raw_input()
m = ''
leng = len(string)
i = 0
while i < leng:
if (i/t) % 2 != 0:
m = m + string[i+t-1:i-1:-1]
else:
m = m + string[i:i+t]
i = i + t
print(m)
Alternatively you can try this
def myfunc(s, count):
return [''.join(x) for x in zip(*[list(s[z::count]) for z in range(count)])]
a='Hellothegamestarts'
lst=myfunc(a,3)
print "".join([i if lst.index(i) in range(0,len(lst),2) else i[::-1] for i in lst])
myfun i didn't write it.It's from here

Categories

Resources