Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Code (lots of it, sorry):
#nea practice
def re_election():
print("A re-election is needed")
choice = int(input("Which test vote file would you like to use: "))
correct_choices = [1, 2]
while choice not in correct_choices:
choice = int(input("Error, try again: "))
if choice == 1:
filename = "Test1_Votes.txt"
elif choice == 2:
filename = "Test2_Votes.txt"
with open(filename, 'r'):
f = open(filename)
lines = f.readlines()
linecount = 0
candidates = ['a', 'b', 'c', 'd', 'e']
for line in lines:
linecount +=1
valid_votes = linecount
num_seats = 2
quota = int((valid_votes/(num_seats + 1))+ 1)
print("\n")
print("Quota is: " + str(quota))
all_lines = []
a_scores = []
b_scores = []
c_scores = []
d_scores = []
e_scores = []
for line in lines:
line = line.rstrip("\n") # strip new line character
lst = [int(x) for x in line.split(',')] # split line and cast to int
all_lines.append(lst)
a_scores.append(lst[0])
b_scores.append(lst[1])
c_scores.append(lst[2])
d_scores.append(lst[3])
e_scores.append(lst[4])
print(all_lines)
#fp
a_fp_votes = a_scores.count(1)
b_fp_votes = b_scores.count(1)
c_fp_votes = c_scores.count(1)
d_fp_votes = d_scores.count(1)
e_fp_votes = e_scores.count(1)
all_fp_votes = [a_fp_votes, b_fp_votes, c_fp_votes, d_fp_votes, e_fp_votes]
print(all_fp_votes)
candidates_fp_votes = dict(zip(candidates, all_fp_votes))
#sp
a_sp_votes = a_scores.count(2)
b_sp_votes = b_scores.count(2)
c_sp_votes = c_scores.count(2)
d_sp_votes = d_scores.count(2)
e_sp_votes = e_scores.count(2)
all_sp_votes = [a_sp_votes, b_sp_votes, c_sp_votes, d_sp_votes, e_sp_votes]
candidates_sp_votes = dict(zip(candidates, all_sp_votes))
#tp
a_tp_votes = a_scores.count(3)
b_tp_votes = b_scores.count(3)
c_tp_votes = c_scores.count(3)
d_tp_votes = d_scores.count(3)
e_tp_votes = e_scores.count(3)
all_tp_votes = [a_tp_votes, b_tp_votes, c_tp_votes, d_tp_votes, e_tp_votes]
candidates_tp_votes = dict(zip(candidates, all_tp_votes))
all_new_fp_votes = all_fp_votes
candidates_new_fp_votes = candidates_fp_votes
if (sum([x >= quota for x in [a_fp_votes, b_fp_votes, c_fp_votes, d_fp_votes, e_fp_votes]])) >= 2:
print("Quota Achieved")
quota_achieved = True
else:
print("Quota Not Achieved")
quota_achieved = False
if quota_achieved == True:
"""
Tiebreaker system
"""
final_vals = [a for a, b in candidates_fp_votes.items() if
list(candidates_fp_votes.values()).count(b) > 1]
print("Duplicates are: ")
for i in final_vals:
print(i)
print(final_vals)
if not final_vals:
print("No tiebreaker sys required")
winners = []
for i in range(2):
winner = max(candidates_fp_votes, key=candidates_fp_votes.get)
winners.append(winner)
del candidates_fp_votes[winner]
print("Winners are: " + winners[0] + " and " + winners[1])
f.close()
exit()
else:
print("Implementing step 1")
candidates_fp_votes[final_vals[0]] = candidates_fp_votes[final_vals[0]] + candidates_sp_votes[
final_vals[0]]
candidates_fp_votes[final_vals[1]] = candidates_fp_votes[final_vals[1]] + candidates_sp_votes[
final_vals[1]]
step1_vals = [a for a, b in candidates_fp_votes.items() if
list(candidates_fp_votes.values()).count(b) > 1]
print("Duplicates are: ")
for i in step1_vals:
print(i)
if not step1_vals:
print("No tiebreaker sys required")
winners = []
for i in range(2):
winner = max(candidates_fp_votes, key=candidates_fp_votes.get)
winners.append(winner)
del candidates_fp_votes[winner]
print("Winners are: " + winners[0] + " and " + winners[1])
f.close()
exit()
else:
print("Implementing step 2b")
candidates_fp_votes[step1_vals[0]] = candidates_fp_votes[step1_vals[0]] + \
candidates_tp_votes[final_vals[0]]
candidates_fp_votes[step1_vals[1]] = candidates_fp_votes[step1_vals[1]] + \
candidates_tp_votes[final_vals[1]]
step2b_vals = [a for a, b in candidates_fp_votes.items() if
list(candidates_fp_votes.values()).count(b) > 1]
print("Duplicates are: ")
for i in step2b_vals:
print(i)
print(step2b_vals)
if not step2b_vals:
print("No tiebreaker sys required")
winners = []
for i in range(2):
winner = min(candidates_fp_votes, key=candidates_fp_votes.get)
winners.append(winner)
del candidates_fp_votes[winner]
print("Winners are: " + winners[0] + " and " + winners[1])
f.close()
exit()
else:
print("There is a tie breaker which cannot be resolved between " + step2b_vals[0] + " and " +
step2b_vals[1])
f.close()
exit()
"""
STV
"""
eliminated = 0
while quota_achieved == False:
new_candidates = ['a', 'b', 'c', 'd', 'e']
eliminated_candidate = min(candidates_new_fp_votes, key=candidates_new_fp_votes.get)
print(eliminated_candidate + " has been eliminated ")
eliminated +=1
candidate_positions_in_list = [0, 1, 2, 3, 4]
candidate_and_positions = dict(zip(candidates, candidate_positions_in_list))
eliminated_candidate_position_in_list = (candidate_and_positions.get(eliminated_candidate))
for i, row in enumerate(all_lines):
#traversing each column
for j, c in enumerate(row):
#in each column in the row check for '1', if found replace by '0'
if j == eliminated_candidate_position_in_list and c== 1:
row[j] = 0
#in the same row check for '2', if found replace my 1
if 2 in row:
ind = row.index(2)
row[ind] = 1
print(all_lines)
a_new_scores = []
b_new_scores = []
c_new_scores = []
d_new_scores = []
e_new_scores = []
for list in all_lines:
a_new_scores.append(list[0])
b_new_scores.append(list[1])
c_new_scores.append(list[2])
d_new_scores.append(list[3])
e_new_scores.append(list[4])
a_new_fp_votes = a_new_scores.count(1)
b_new_fp_votes = b_new_scores.count(1)
c_new_fp_votes = c_new_scores.count(1)
d_new_fp_votes = d_new_scores.count(1)
e_new_fp_votes = e_new_scores.count(1)
all_new_fp_votes = [a_new_fp_votes, b_new_fp_votes, c_new_fp_votes, d_new_fp_votes, e_new_fp_votes]
candidates_new_fp_votes = dict(zip(new_candidates, all_new_fp_votes))
all_candidates_fp_votes = candidates_new_fp_votes
# sp
a_new_sp_votes = a_new_scores.count(2)
b_new_sp_votes = b_new_scores.count(2)
c_new_sp_votes = c_new_scores.count(2)
d_new_sp_votes = d_new_scores.count(2)
e_new_sp_votes = e_new_scores.count(2)
all_new_sp_votes = [a_new_sp_votes, b_new_sp_votes, c_new_sp_votes, d_new_sp_votes, e_new_sp_votes]
candidates_new_sp_votes = dict(zip(new_candidates, all_new_sp_votes))
# tp
a_new_tp_votes = a_new_scores.count(3)
b_new_tp_votes = b_new_scores.count(3)
c_new_tp_votes = c_new_scores.count(3)
d_new_tp_votes = d_new_scores.count(3)
e_new_tp_votes = e_new_scores.count(3)
all_new_tp_votes = [a_new_tp_votes, b_new_tp_votes, c_new_tp_votes, d_new_tp_votes, e_new_tp_votes]
candidates_new_tp_votes = dict(zip(new_candidates, all_new_tp_votes))
if eliminated_candidate == 'a':
candidates.remove('a')
try:
all_new_fp_votes.remove(a_new_fp_votes)
except ValueError:
pass
elif eliminated_candidate == 'b':
candidates.remove('b')
try:
all_new_fp_votes.remove(b_new_fp_votes)
except ValueError:
pass
elif eliminated_candidate == 'c':
candidates.remove('c')
try:
all_new_fp_votes.remove(c_new_fp_votes)
except ValueError:
pass
elif eliminated_candidate == 'd':
candidates.remove('d')
try:
all_new_fp_votes.remove(d_new_fp_votes)
except ValueError:
pass
elif eliminated_candidate == 'e':
candidates.remove('e')
all_new_fp_votes.remove(e_new_fp_votes)
del candidates_new_fp_votes
candidates_new_fp_votes = dict(zip(new_candidates, all_new_fp_votes))
if (sum([x >= quota for x in [a_new_fp_votes, b_new_fp_votes, c_new_fp_votes,
d_new_fp_votes, e_new_fp_votes]])) >= 2:
print("Quota Achieved")
quota_achieved = True
"""
Tiebreaker system
"""
print(all_candidates_fp_votes)
final_vals = [a for a, b in candidates_new_fp_votes.items() if list(candidates_new_fp_votes.values()).count(b) > 1]
print("Duplicates are: ")
for i in final_vals:
print(i)
print(final_vals)
if not final_vals:
print("No tiebreaker sys required")
winners = []
for i in range(2):
winner = max(candidates_new_fp_votes, key=candidates_new_fp_votes.get)
winners.append(winner)
del candidates_new_fp_votes[winner]
print("Winners are: " + winners[0] + " and " + winners[1])
f.close()
exit()
else:
print("Implementing step 1")
candidates_new_fp_votes[final_vals[0]] = candidates_new_fp_votes[final_vals[0]] + candidates_new_sp_votes[
final_vals[0]]
candidates_new_fp_votes[final_vals[1]] = candidates_new_fp_votes[final_vals[1]] + candidates_new_sp_votes[
final_vals[1]]
step1_vals = [a for a, b in candidates_new_fp_votes.items() if
list(candidates_new_fp_votes.values()).count(b) > 1]
print("Duplicates are: ")
for i in step1_vals:
print(i)
if not step1_vals:
print("No tiebreaker sys required")
winners = []
for i in range(2):
winner = max(candidates_new_fp_votes, key=candidates_new_fp_votes.get)
winners.append(winner)
del candidates_new_fp_votes[winner]
print("Winners are: " + winners[0] + " and " + winners[1])
f.close()
exit()
else:
print("Implementing step 2b")
candidates_new_fp_votes[step1_vals[0]] = candidates_new_fp_votes[step1_vals[0]] + \
candidates_new_tp_votes[final_vals[0]]
candidates_new_fp_votes[step1_vals[1]] = candidates_new_fp_votes[step1_vals[1]] + \
candidates_new_tp_votes[final_vals[1]]
step2b_vals = [a for a, b in candidates_new_fp_votes.items() if
list(candidates_new_fp_votes.values()).count(b) > 1]
print("Duplicates are: ")
for i in step2b_vals:
print(i)
print(step2b_vals)
if not step2b_vals:
print("No tiebreaker sys required")
winners = []
for i in range(2):
winner = min(candidates_new_fp_votes, key=candidates_new_fp_votes.get)
winners.append(winner)
del candidates_new_fp_votes[winner]
print("Winners are: " + winners[0] + " and " + winners[1])
else:
print("There is a tie breaker which cannot be resolved between " + step2b_vals[0] + " and " +
step2b_vals[1])
f.close()
exit()
else:
if eliminated == 2:
re_election()
else:
quota_achieved = False
print("Quota Not Achieved")
pass
pass
Txt file sample:
1,2,3,0,0
0,0,3,2,1
1,0,0,3,2
1,0,0,2,3
Sorry for having to make you read all that code.
I have had to include all of my code because this is a problem with the entire code and there is no way in which I can make this simpler for you.
In line 293 of the code, I have tried a list out of the values of candidates_new_fp_votes but it is not making the list. The list which is always purple in my IDE is no longer purple. It is not my IDE's fault as I have tried the same in the default python IDE and have also put my code into another python file and the same still happens. I think that something in my code is causing this to happen but I do not know.
When I run the code and select 2 (txt file sample above). It throws the error:
final_vals = [a for a, b in candidates_new_fp_votes.items() if list(candidates_new_fp_votes.values()).count(b) > 1]
TypeError: 'list' object is not callable
I'm assuming this is from candidates_new_fp_votes.values not being able to become a list.
I have tried to google this error for 2 hours straight with the results being of no hope to me.
Any help?
Thanks in advance.
Do not override any builtin function/method/statement in python.
You have overrode list() in:
for list in all_lines:
a_new_scores.append(list[0])
b_new_scores.append(list[1])
c_new_scores.append(list[2])
d_new_scores.append(list[3])
e_new_scores.append(list[4])
You get an exception because after you overrode list() by list variable. It [variable] is not callable:
TypeError: 'list' object is not callable
I have overrode list() in:
for list in all_lines:
a_new_scores.append(list[0])
b_new_scores.append(list[1])
c_new_scores.append(list[2])
d_new_scores.append(list[3])
e_new_scores.append(list[4])
I got an exception because I overrode list() by list variable. It is not callable:
TypeError: 'list' object is not callable
Instead I should have put:
for lst in all_lines:
a_new_scores.append(lst[0])
b_new_scores.append(lst[1])
c_new_scores.append(lst[2])
d_new_scores.append(lst[3])
e_new_scores.append(lst[4])
As this does not override the list().
Related
Not allowed to use "Split(),Reverse(),Join() or regexes" or any other
helping inbuilt python function
input something like this:
" my name is scheven "
output like this:
"ym eman si nevehcs"
you need to consider removing the starting,inbetween,ending spaces aswell in the input
I have tried 2 tries, both failed i will share my try to solve this and maby an idea to improve it
First try:
def reverseString(someString):
#lenOfString = len(someString)-1
emptyList = []
for i in range(len(someString)):
emptyList.append(someString[i])
lenOfString = len(emptyList)-1
counter = 0
while counter < lenOfString:
if emptyList[counter] == " ":
counter+=1
if emptyList[lenOfString] == " ":
lenOfString-=1
else:
swappedChar = emptyList[counter]
emptyList[counter] = emptyList[lenOfString]
emptyList[lenOfString] = swappedChar
counter+=1
lenOfString-=1
str_contactantion = ""
#emptyList = emptyList[::-1]
#count_spaces_after_letter=0
for letter in emptyList:
if letter != " ":
str_contactantion+=letter
#str_contactantion+=" "
str_contactantion+=" "
return str_contactantion
second try:
def reverse(array, i, j):
emptyList = []
if (j == i ):
return ""
for k in range(i,j):
emptyList.append(array[k])
start = 0
end = len(emptyList) -1
if start > end: # ensure i <= j
start, end =end, start
while start < end:
emptyList[start], emptyList[end] = emptyList[end], emptyList[start]
start += 1
end -= 1
strconcat=""
for selement in emptyList:
strconcat+=selement
return strconcat
def reverseStr(someStr):
start=0
end=0
help=0
strconcat = ""
empty_list = []
for i in range(len(someStr)):
if(someStr[i] == " "):
continue
else:
start = i
j = start
while someStr[j] != " ":
j+=1
end = j
#if(reverse(someStr,start,end) != ""):
empty_list.append(reverse(someStr,start,end))
empty_list.append(" ")
for selement in empty_list:
strconcat += selement
i = end + 1
return strconcat
print(reverseStr(" my name is scheven "))
The following works without managing indices:
def reverseString(someString):
result = crnt = ""
for c in someString:
if c != " ":
crnt = c + crnt # build the reversed current token
elif crnt: # you only want to do anything for the first space of many
if result:
result += " " # append a space first
result += crnt # append the current token
crnt = "" # and reset it
if crnt:
result += " " + crnt
return result
reverseString(" my name is scheven ")
# 'ym eman si nevehcs'
Try this:
def reverseString(someString):
result = ""
word = ""
for i in (someString + " "):
if i == " ":
if word:
result = result + (result and " ") + word
word = ""
else:
word = i + word
return result
You can then call it like this:
reverseString(" my name is scheven ")
# Output: 'ym eman si nevehcs'
Try this:
string = " my name is scheven "
def reverseString(someString):
result = ''
curr_word = ''
for i in someString:
if i == ' ':
if curr_word:
if result:
result = f'{result} {curr_word}'
else:
result = f'{result}{curr_word}'
curr_word = ''
else:
curr_word = f'{i}{curr_word}'
return result
print(repr(reverseString(string)))
Output:
'ym eman si nevehcs'
Note: if you're allowed to use list.append method, I'd suggest using a collections.deque as it's more performant than appending to a list. But of course, in the end you'll need to join the list together, and you mentioned that you're not allowed to use str.join, so that certainly poses an issue.
I'm trying to extract data from a SPICE netlist file, specifically the defined parameters. This are the contents (of interest) of the file 'netlist.sp':
.param freq = 860x powS = 0
+ pi = 3.141592
+ nper = 15 cap1 = 68p
+ cycles = 20
+ tper = '1/freq'
+ tstep = 'tper/nper'
+ tstop = 'cycles*tper'
FYI, the + sign means to continue the previous line, and the param = 'equation' evaluates the expression.
So, I'm trying to create a global variable inside Python 3.6 for each one of the parameters. This is the code I got so far:
def isnumber(s):
try:
float(s)
return True
except ValueError:
return False
#This function is needed to convert the '68p' format to '68e-12'
def floatify(st):
if not isnumber(st[-1]):
vals = [ 't', 'g', 'x', 'meg', 'k', 'm', 'u', 'n', 'p', 'f', 'a']
prod = [1e12, 1e9, 1e6, 1e6, 1e3, 1e-3, 1e-6, 1e-9, 1e-12, 1e-15, 1e-18]
pos = vals.index(st[-1])
st = st[:-1]
num = float(st) * prod[pos]
else:
num = float(st)
return num
#This is the main function
def params (file):
fl = 0
strng = '00'
tnum = 0.0
with open(file) as dat:
for line in dat:
if line.startswith('*'):
pass
elif line.startswith('.param '):
fl = 1
spl = line.split()
a = [i for i,x in enumerate(spl) if x=='=']
for i in range(len(a)):
strng = spl[a[i]-1]
try:
tnum = floatify(spl[a[i]+1])
except ValueError:
tnum = eval(spl[a[i]+1])
globals()[strng] = tnum
elif (line.find('+')+1) and fl:
spl = line.split()
a = [i for i,x in enumerate(spl) if x=='=']
for i in range(len(a)):
strng = spl[a[i]-1]
try:
tnum = floatify(spl[a[i]+1])
except ValueError:
temp = spl[a[i]+1]
tnum = eval(temp)
globals()[strng] = tnum
elif (not (line.find('+')+1)) and fl:
break
params('netlist.sp')
#Testing the variables
print('params done')
print('freq = ', freq)
print('powS = ', powS)
print('pi = ', pi)
print('nper = ', nper)
print('cap1 = ', cap1)
print('cycles = ', cycles)
print('tper = ', tper)
print('tstep = ', tstep)
print('tstop = ', tstop)
# Testing the eval function:
print(eval('1/freq'))
print(eval('2*pi'))
The globals()[strng] = tnum statement creates the global variable from the extracted string and assigns the corresponding value.
The output is:
freq = 860000000.0
powS = 0.0
pi = 3.141592
nper = 15.0
cap1 = 6.8e-11
cycles = 20.0
tper = 1/freq
tstep = tper/nper
tstop = cycles*tper
1.1627906976744186e-09
6.283184
So, what I understand from the testing of the eval function is that the global variables created inside the params function are understood only outside of the function itself. I know that to modify a global variable inside a function you have to declare the global var statement inside the function. My question is how to do that in this case when the variables are created dynamically?
Note: The repl.it could be cleaned up quite a bit, but it does work for the example data.
As this repl.it shows, you can do this painlessly with a dictionary.
def fill_param(token):
for key in params.keys():
token = token.replace(key, str(params[key]))
return token
is the key which allows this: it uses str.replace to fill in the values for anything we already know before we eval it:
params[key] = eval(fill_param(value))
The start of process_params() is interesting as well:
global params
tokens = shlex.split(line)[1:]
we import the dictionary, then use shlex.split() to tokenize the string, leaving off the first token (.param or + depending on the line). shlex.split() is nice because it respects quotations.
Full code (in case repl.it dies). Note it leaves a lot to be desired, as I'm spent on this problem. I leave the clean-up as an exercise to the reader.
import shlex
with open("netlist.sp", "w") as f:
f.write("""cabbage
garbage
.param freq = 860x powS = 0
+ pi = 3.141592
+ nper = 15 cap1 = 68p
+ cycles = 20
+ tper = '1/freq'
+ tstep = 'tper/nper'
+ tstop = 'cycles*tper'
sweet american freedom""")
params = {}
def param_it(in_f):
def isnumber(s):
try:
float(s)
return True
except ValueError:
return False
def floatify(st):
if not isnumber(st):
vals = [ 't', 'g', 'x', 'meg', 'k', 'm', 'u', 'n', 'p', 'f', 'a']
prod = [1e12, 1e9, 1e6, 1e6, 1e3, 1e-3, 1e-6, 1e-9, 1e-12, 1e-15, 1e-18]
pos = vals.index(st[-1])
st = st[:-1]
num = float(st) * prod[pos]
else:
num = float(st)
return num
def number(st):
if isnumber(st) or len(st) == 1 and st in '0123456789':
return True
return st[-1] not in '0123456789' and isnumber(st[:-1])
def process_params(line):
global params
tokens = shlex.split(line)[1:]
assert len(tokens) % 3 == 0
for i in range(len(tokens)/3):
key = tokens[i*3]
value = tokens[i*3 + 2]
print "Processing key: %s value: %s... " % (key, value),
if number(value):
try:
value = float(value)
except ValueError:
value = floatify(value)
params[key] = value
else:
try:
params[key] = eval(fill_param(value))
except Exception as e: # eval can throw essentially any exception
print "Failed to parse value for k/v %s:%s" % (key, value)
raise
print "Converted value is : %s\n" % params[key]
def fill_param(token):
for key in params.keys():
token = token.replace(key, str(params[key]))
return token
with open(in_f, "r") as f:
param = False
for line in f:
if line.startswith(".param "):
process_params(line)
param = True
elif param and line.startswith("+"):
process_params(line)
elif param:
break
param_it("netlist.sp")
print params
I cant figure out why line 104 keeps returning invalid syntax, can someone please point me in the right direction? Does it have something to do with the way i used elif? Sorry if this is a newbie question!
Line 104 is the else statement in the for item in workingDict.keys() loops inside printGrammar
import sys
import string
from collections import defaultdict
#default length of 3
stringLength = 3
#get last argument of command line(file)
if len(sys.argv) == 1:
#get a length from user
try:
stringLength = int(input('Length? '))
filename = input('Filename: ')
except ValueError:
print("Not a number")
elif len(sys.argv) == 2:
#get a length from user
try:
stringLength = int(input('Length? '))
filename = sys.argv[1]
except ValueError:
print("Not a number")
elif len(sys.argv) == 3:
filename = sys.argv[2]
stringLength = sys.argv[1].split('l')[1]
else:
print("Invalid input!")
#get start symbol
with open(filename, "r") as grammar:
#read file
lines = grammar.readlines()
start = lines[0].split('=')[0]
start = start.replace(" ", "")
#checks
#print(stringLength)
#print(filename)
#print(start)
def str2dict(filename):
result = defaultdict(list)
with open(filename, "r") as grammar:
#read file
lines = grammar.readlines()
count = 0
#loop through
for line in lines:
#append info
line = line.rstrip()
result[line[0]].append(line.split('=')[1])
return result
workingDict = str2dict("Binary.txt")
print(workingDict)
def printGrammar(result):
sentenceList = []
workList = []
workList.append(start)
i = 0
firstNT = ""
#While the worklist is not empty:
while(len(workList) != 0):
#Get and delete one potential sentence s from the worklist.
symbol = workList.pop()
#If the | s | > N, continue.
if len(str(symbol).replace(" ", "")) > int(stringLength):
continue
else:
if str(symbol) in workingDict.keys():
#append the right derivation
for item in workingDict.get(symbol):
workList.append(list(item.replace(" ", "")))
#workList.append(str(workingDict.get(symbol)))
#add derivation
print(workingDict.keys())
#If s has no nonterminals, print s and continue.
for item in workingDict.keys():
print("test")
print(''.join(item))
if len(item) != 1:
continue
#if the element is in dictionary, dont print
elif ''.join(item) in workingDict.keys():
continue
print(symbol)
#if element is not in dictionary, print
else:
print("THIS IS A TERMINAL!!")
print(item)
#Choose the leftmost nonterminal NT.
print(workList)
#For all productions NT -> rhs:
#Replace NT in s with rhs; call it tmp.
#Store tmp on worklist.
return workList
print (printGrammar(workingDict))
You need to indent the line
print(symbol)
to the same level as continue.
def main():
names=[0]*10
for index in range(len(names)):
names[index] = input("Enter word " + str(index + 1) + ": ")
bubbleSort(names)
print("Names in Alphabetical order:")
print(names)
def bubbleSort(names):
for maxElement in range(len(names)-1, 0, -1):
for index in range(maxElement):
if names[index] > names[index+1]:
temp = names[index]
names[index] = names[index+1]
names[index+1] = temp
found = False
index=0
while found == False and index < len(names):
Searchword= input('enter a searchword:')
if scores[index] == Searchword :
found = True
else:
index = index + 1
if found:
print("Found")
else:
print("Not Found")
main()
Does everything required accept when a Searchword is entered that cannot be found it does not print 'not found' but only keeps asking for input.
Change if scores[index] == Searchword : to if names[index] == Searchword :
Place Searchword= input('enter a searchword:') outside the while loop
It should look something like this:
def main():
names=[0]*10
for index in range(len(names)):
names[index] = input("Enter word " + str(index + 1) + ": ")
bubbleSort(names)
print("Names in Alphabetical order:")
print(names)
def bubbleSort(names):
for maxElement in range(len(names)-1, 0, -1):
for index in range(maxElement):
if names[index] > names[index+1]:
temp = names[index]
names[index] = names[index+1]
names[index+1] = temp
found = False
index=0
Searchword= input('enter a searchword:')
while found == False and index < len(names):
if names[index] == Searchword :
found = True
else:
index = index + 1
if found:
print("Found")
else:
print("Not Found")
main()
you might need input before the loop, ie:
Searchword= input('enter a searchword:')
while found == False and index < len(names):
if scores[index] == Searchword :
found = True
else:
index = index + 1
The following script is supposed to fetch a specific line number and parse it from a live website. It works for like 30 loops but then it seems like enumerate(f) stops working correctly... the "i" in the for loop seems to stop at line 130 instead of like 200 something. Could this be due to the website I'm trying to fetch data from or something else? Thanks!!
import sgmllib
class MyParser(sgmllib.SGMLParser):
"A simple parser class."
def parse(self, s):
"Parse the given string 's'."
self.feed(s)
self.close()
def __init__(self, verbose=0):
"Initialise an object, passing 'verbose' to the superclass."
sgmllib.SGMLParser.__init__(self, verbose)
self.divs = []
self.descriptions = []
self.inside_div_element = 0
def start_div(self, attributes):
"Process a hyperlink and its 'attributes'."
for name, value in attributes:
if name == "id":
self.divs.append(value)
self.inside_div_element = 1
def end_div(self):
"Record the end of a hyperlink."
self.inside_div_element = 0
def handle_data(self, data):
"Handle the textual 'data'."
if self.inside_div_element:
self.descriptions.append(data)
def get_div(self):
"Return the list of hyperlinks."
return self.divs
def get_descriptions(self, check):
"Return a list of descriptions."
if check == 1:
self.descriptions.pop(0)
return self.descriptions
def rm_descriptions(self):
"Remove all descriptions."
self.descriptions.pop()
import urllib
import linecache
import sgmllib
tempLine = ""
tempStr = " "
tempStr2 = ""
myparser = MyParser()
count = 0
user = ['']
oldUser = ['none']
oldoldUser = [' ']
array = [" ", 0]
index = 0
found = 0
k = 0
j = 0
posIndex = 0
a = 0
firstCheck = 0
fCheck = 0
while a < 1000:
print a
f = urllib.urlopen("SITE")
a = a+1
for i, line in enumerate(f):
if i == 187:
print i
tempLine = line
print line
myparser.parse(line)
if fCheck == 1:
result = oldUser[0] is oldUser[1]
u1 = oldUser[0]
u2 = oldUser[1]
tempStr = oldUser[1]
if u1 == u2:
result = 1
else:
result = user is oldUser
fCheck = 1
user = myparser.get_descriptions(firstCheck)
tempStr = user[0]
firstCheck = 1
if result:
array[index+1] = array[index+1] +0
else:
j = 0
for z in array:
k = j+2
tempStr2 = user[0]
if k < len(array) and tempStr2 == array[k]:
array[j+3] = array[j+3] + 1
index = j+2
found = 1
break
j = j+1
if found == 0:
array.append(tempStr)
array.append(0)
oldUser = user
found = 0
print array
elif i > 200:
print "HERE"
break
print array
f.close()
Perhaps the number of lines on that web page are fewer than you think? What does this give you?:
print max(i for i, _ in enumerate(urllib.urlopen("SITE")))
Aside: Your indentation is stuffed after the while a < 1000: line. Excessive empty lines and one-letter names don't assist the understanding of your code.
enumerate is not broken. Instead of such speculation, inspect your data. Suggestion: replace
for i, line in enumerate(f):
by
lines = list(f)
print "=== a=%d linecount=%d === % (a, len(lines))
for i, line in enumerate(lines):
print " a=%d i=%d line=%r" % (a, i, line)
Examine the output carefully.