Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 days ago.
Improve this question
I´m trying to solve this problem from the Qualification Round of the contest. It successfully solves the sample, but I receive a WA (Wrong Answer) for the cases. Can anyone figure out what is wrong with my code?
I tried my best looked solutions on google, but I could not find any difference between my code and the code of other contestants.
offline = True
if(offline):
f = open("Input")
f = f.read()
f = f.split("\n")
numCases = int(f[0])
readingLine = 1
else:
numCases = int(input())
myFun = []
IPointTo = []
pointsToMe = [[] for _ in range(1)]
def greater(a,b):
if(a>b): return a
return b
def fun(i):
#Returns a pair [fun, max]
#fun = a + b
# a = fun is the sum of the fun() of all children, except the one with the lowest max
# b = greater(fun of myself, max of the child with the lowest max)
# "max" is the value greater(myfun, max of the child with lowest max)
global myFun,IPointTo,pointsToMe
if (pointsToMe[i].__len__() == 0): return [myFun[i],myFun[i]]
a = 0
for j in range(pointsToMe[i].__len__()):
child = pointsToMe[i][j]
aux = fun(child)
a += aux[0]
if(j==0 or aux[1] < lowestMax):
funOfTheChildWithLowestMax = aux[0]
lowestMax = aux[1]
a -= funOfTheChildWithLowestMax
b = greater(myFun[i],lowestMax)
return [a+b,greater(myFun[i],lowestMax)]
for case in range(numCases):
myFun = []
IPointTo = []
for i in range(3):
if(offline):
line = f[readingLine]
readingLine += 1
else:
line = input()
if(i==0):
N = int(line)
if(i==1):
line = line.split(" ")
for x in line: myFun.append(int(x))
if(i==2):
line = line.split(" ")
for x in line: IPointTo.append(int(x)-1)
pointsToMe = [[] for _ in range(N)]
for i in range(N):
if(IPointTo[i] != -1): pointsToMe[IPointTo[i]].append(i)
sum = 0
for i in range(N):
if(IPointTo[i] == -1):
aux = fun(i)
sum += aux[0]
print("Case #{}: {}".format(case + 1, sum))
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am trying to use the code below to find the shortest path between 2 points and by doing so I am attempting to apply the Dijkstra's algorithm. For some reason the code is erroring out I was wondering if someone could have a look.
Any help is appreciated
Error:
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pip/calcdistance.py", line 86, in minDist
if distArray[v] < min and vistSet[v] == False:
TypeError: 'bool' object is not subscriptable
Python Code:
import sys
import csv
size = 100
class CalcCreate:
locationList = []
def __init__(self, size):
self.V = size
self.locationList = [] #Square brackets are an indexing operator
self.distArray = [0 for i in range(size)]
self.vistSet = [0 for i in range(size)]
self.matrix = [[0 for x in range(size)] for y in range (size)]
self.points = []
self.readData()
self.storeDist()
self.INF = 1000000
def readData(self):
with open('/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pip/Locations.csv') as f:
csv_reader = csv.reader(f)
index = 0
next(csv_reader)
for line in csv_reader:
pointName = line[0]
x = line[1]
y = line[2]
number = line[3]
edge = line[4]
water=False
if line[5] == "W":
water=True
self.locationList.append( [pointName, x, y, number, edge, water] ) # etc
if not pointName in self.points:
self.points.append(pointName)
index += 1
f.close()
def storeDist(self):
for index in range(0, len(self.locationList)-1):
if self.locationList[index][4] !="":
start = self.locationList[index][0]
end = self.locationList[index][4]
for indexA in range(0, len(self.points)-1):
if self.points[indexA] == start:
indexPointA = indexA
for indexB in range(0, len(self.points)-1):
if self.points[indexB] == end:
indexPointB =indexB
distance = self.computeDist(start, end)
break
break
def computeDist (self, a, b):
# provide the distance between two points a and b on a path. Assume adjacent
distance=0
return distance
def dijkstra(self, srcsize):
for i in range(self.V):
self.distArray[i] = self.INF
self.vistSet = False
self.distArray[srcsize] = 0
for i in range(self.V):
u = self.minDist(self.distArray, self.vistSet)
self.vistSet[u] = True
for v in range(self.V):
if self.matrix[u][v] > 0 and self.vistSet[v] == False and self.distArray[v] > self.distArray[u] + self.matrix[u][v]:
self.distArray[v] = self.distArray[u] + self.matrix[u][v]
self.printSolution(self.distArray)
def minDist(self, distArray, vistSet):
min = self.INF
for v in range(self.V):
if distArray[v] < min and vistSet[v] == False:
min = distArray[v]
min_index = v
return min_index
def printSolution(self, distArray):
print("Node \tDistance from 0")
for i in range(self.V):
print (i, "\t", distArray[i])
if __name__ == '__main__':
cc = CalcCreate(100)
print(cc.locationList)
cc.graph = cc.locationList
cc.dijkstra(0)
In your dijkstra function, the line self.vistSet = False appears to be missing any indexing, so it replaces the entire vistSet with the boolean False instead of setting the elements of the list to False as you probably meant to do.
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
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
im trying to code this caesar cipher decoder, but whenever the input message has any " "(spaces) it just print " " infinitely
[ps: just started coding]
already tried to change -if- to check if meslist[x] is equal to " ", but it doesent seems like a "valid" thing
here is the code:
import string
letras = list(string.ascii_lowercase)
message = input("qual sua menssagem codificada?")
cod = input("qual a numeração da cifra?")
meslist = list(message)
trans = True
num = len(meslist)
x = 0
while trans:
if num > x:
if meslist[x] in letras:
a = letras.index(meslist[x])
print(letras[a + 2])
x = x + 1
trans = True
else:
print(" ")
trans = True
elif num == 0:
trans = False'
just expecting for it to print it the right way.
I fixed the code as below :
while trans:
if num > x:
if meslist[x] in letras:
a = letras.index(meslist[x])
print(letras[a + 2])
x = x + 1
trans = True
else:
print(" ")
trans = True
# to increase x by 1, to take the next char. in the next loop
x = x + 1
# num == x means the end of the loop
elif num == x:
trans = False
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
The program must use a list of length 10 to count the occurrences of the 10 digits 0-9.
It should print like this:
I am not sure how to get it to add up the occurrences of each number every time it reads a line. Or how to get the totals into a list.
Number of 0's: 5
Number of 1's: 8
Number of 2's: 17
def main():
intro()
inFile = getFile()
file, outfile = convertName(inFile)
count, counts = countLines(file, outfile)
printResults(count, counts)
def intro():
print()
print("Program to count letters in each line")
print("in a file.")
print("You will enter the name of a file.")
print("The program will create an output file.")
print("Written by --------.")
print()
def getFile():
inFile = input("Enter the name of input file: ")
return inFile
def convertName(inFile):
file = open(inFile, "r")
outfile = (inFile.replace(".txt", ".out"))
return file, outfile
def countLines(file, outfile):
outfile = open(outfile, "w")
count = 0
num = 0
numcount1 = []
numcount = []
for line in file:
spl = line.split(" ")
listx = list(spl)
counts = {}
for i in range(0, 10):
count[i] = count[i, 0] + str(listx.count(i))
for spl in line:
if spl.isalnum():
num = num + 1
else:
num = num + 0
pr = str(num)+": "+line+"\n"
outfile.write(pr)
count = count + 1
return count, counts
def printResults(count, counts):
print(count, counts)
main()
def countLines(file, outfile):
s = file.read()
result = [s.count(str(i)) for i in range(10)]
...
More efficient to scan s just once (but a bit more code)
def countLines(file, outfile):
s = file.read()
result = [0] * 10
for c in s:
if c.isdigit():
result[int(c)] += 1
...
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I have implemented the following code which works perfectly without any problem. But I am not satisfied with it because it doesn't look pretty? More than anything I feel like it doesn't look like pythonic way to do it.
So I thought I ll take suggestions from the stackoverflow community. This metod is getting its data from sql query which is in another method that method return a dictionary and based the data in that dictionary I am doing pattern match and counting process. I would like to do this in a pythonic way and return a better data structure.
Here is the code:
def getLaguageUserCount(self):
bots = self.getBotUsers()
user_template_dic = self.getEnglishTemplateUsers()
print user_template_dic
user_by_language = {}
en1Users = []
en2Users = []
en3Users=[]
en3Users=[]
en4Users=[]
en5Users=[]
en_N_Users=[]
en1 = 0
en2 = 0
en3 = 0
en4 = 0
en5 = 0
enN = 0
lang_regx = re.compile(r'User_en-([1-5n])', re.M|re.I)
for userId, langCode in user_template_dic.iteritems():
if userId not in bots:
print 'printing key value'
for item in langCode:
item = item.replace('--','-')
match_lang_obj = lang_regx.match(item)
if match_lang_obj is not None:
if match_lang_obj.group(1) == '1':
en1 += 1
en1Users.append(userId)
if match_lang_obj.group(1) == '2':
en2 += 1
en2Users.append(userId)
if match_lang_obj.group(1) == '3':
en3 += 1
en3Users.append(userId)
if match_lang_obj.group(1) == '4':
en4 += 1
en4Users.append(userId)
if match_lang_obj.group(1) == '5':
en5 += 1
en5Users.append(userId)
if match_lang_obj.group(1) == 'N':
enN += 1
en_N_Users.append(userId)
else:
print "Group didn't match our regex: " + item
else:
print userId + ' is a bot'
language_count = {}
user_by_language['en-1-users'] = en1Users
user_by_language['en-2-users'] = en2Users
user_by_language['en-3-users'] = en3Users
user_by_language['en-4-users'] = en4Users
user_by_language['en-5-users'] = en5Users
user_by_language['en-N-users'] = en_N_Users
user_by_language['en-1'] = en1
user_by_language['en-2'] = en2
user_by_language['en-3'] = en3
user_by_language['en-4'] = en4
user_by_language['en-5'] = en5
user_by_language['en-n'] = enN
return user_by_language
You can avoid all these lists and add the data directly to the user_by_language dict.
I would define it as:
user_by_language = collections.defaultdict(list)
After matching the regex, just do this:
user_by_language['en-%s-users' % match_lang_obj.group(1)].append(userId)
In the end, you grab all the lengths of these elements and save them as en-1, en-2...