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
Related
I'm creating a calculator and here's part of the code:
def _digit_formatting(x):
numbers = '1234567890.'
start_idxs = []
end_idxs = []
is_start = True
try:
for idx, value in enumerate(x):
if value in numbers and is_start:
start_idxs.append(idx)
is_start = False
elif value in numbers and idx == len(x) - 1:
end_idxs.append(len(x) - 1)
elif value in numbers and not is_start:
pass
elif value not in numbers and len(start_idxs) > len(end_idxs):
end_idxs.append(idx-1)
is_start = True
except:
...
if len(start_idxs) > len(end_idxs):
end_idxs.append(start_idxs[-1])
start_idxs.reverse()
end_idxs.reverse()
x = list(x)
for idx in range(len(start_idxs)):
if start_idxs[idx] == end_idxs[idx]:
num = x[start_idxs[idx]:end_idxs[idx]+1]
else:
num = x[start_idxs[idx]:end_idxs[idx]+1]
num = ''.join(num)
x = ''.join(x)
x = x[::-1]
num = num[::-1]
x = x.replace(num, '', 1)
x = list(x)
x.reverse()
num = num[::-1]
temp = f'{int(num):,}'
x.insert(start_idxs[idx], temp)
x = ''.join(x)
return x
def calculate(sv):
# This function is called when there's changes in entry box
if self.input_string_var.get() == '':
self.result_string_var.set('')
# Start
real_result = self.input_string_var.get().replace(',', '')
percent_count = self.input_string_var.get().count('%')
# Formatting input string
x = _digit_formatting(real_result)
print(x)
self.input_string_var.set(x)
if percent_count != 0:
numbers = '0123456789.'
for cnt in range(percent_count):
percent_idx = real_result.find('%', 0)
limit_operator = 2
percent_number = ''
for i in range(percent_idx - 1, -1, -1):
if real_result[i] not in numbers:
limit_operator -= 1
if limit_operator == 0:
break
if limit_operator == 1:
if real_result[i] in '*/':
percent_number = ''
break
else:
percent_number += real_result[i]
if percent_number == '':
percent_number = '1'
else:
percent_number = percent_number[1:][::-1]
real_result = list(real_result)
real_result[percent_idx] = f'/100*{percent_number}'
real_result = ''.join(real_result)
else:
real_result = self.input_string_var.get().replace(',', '')
try:
if eval(real_result) == int(eval(real_result)):
self.result_string_var.set(f'{int(eval(real_result)):,}')
else:
self.result_string_var.set(f'{int(eval(real_result)):,}')
except:
None
if self.input_string_var.get() == '':
self.result_string_var.set('')
# Entry box string variable
self.input_string_var = tk.StringVar()
self.input_string_var.trace('w', lambda name, index, mode: calculate(self.input_string_var))
There is two functions, first is _digit_formatting which is to format the equation to put comma like thousands, million and billion. The calculate function is called every time there's changes on the input string variable. But when I try to set the string variable to equation after formatting there seems to be a mistake, but if I print the value, it is correct. Example if I enter 1200 the value I printed is 1,200 which is correct but the value on the text box is not correct. Sorry if the code is messy, I'm still learning to make a clean code.
I cannot reproduce your code.
If you can take a look of my example.
n = 1234567890
print(f"I have {n:,} Reputations")
Result:
I have 1,234,567,890 Reputations
so i want convert bytes to binary in python, but when i run it, there's none in the result and i got error:
'NoneType' object is not iterable
here's the code i tried
//func biner
def biner(password):
print(password)
password[0]
for my_byte in password:
print(f'{my_byte:0>8b}', end=' ')
//func to use the result from func biner
def skalar(key, biner):
if len(key) <= key_bytes:
for x in range(len(key),key_bytes):
key = key + "0"
jumbin2 = len(key)
print(jumbin2)
jumbin = biner
print(biner)
hasilenkrip = ''
for a in jumbin:
hasilenkrip += a * jumbin2
print(hasilenkrip)
//how i called the func
enc = b'l\x87\x87\xe6'
ky = maru
tes = biner(enc)
tes1 = skalar(ky, tes)
print(tes1)
Your function currently returns None because there's no return statement. Perhaps instead of using print, you should modify your functions to return an array of outputs.
I suspect what you have in mind is something like this.
# //func biner
def biner(password):
print(password)
password[0]
return ' '.join(f'{my_byte:0>8b}' for my_byte in password)
# //func to use the result from func biner
def skalar(key, biner):
if len(key) <= key_bytes:
for x in range(len(key),key_bytes):
key = key + "0"
jumbin2 = len(key)
print(jumbin2)
jumbin = biner
print(biner)
hasilenkrip = ''
for a in jumbin:
hasilenkrip += a * jumbin2
return hasilenkrip
# print(hasilenkrip)
# //how i called the func
enc = b'l\x87\x87\xe6'
ky = maru
tes = biner(enc)
tes1 = skalar(ky, tes)
print(tes1)
some_bytes = int(input('Enter bytes: '))
print(f'{some_bytes>>4:04b}{some_bytes&0xf:04b} ({some_bytes})')
I did this code:
import itertools
black = "Ellie"
s = "E111e"
messagelist = list(s)
a = s.count("1")
dicta = {}
for x in messagelist:
if not x == "1":
dicta[x] = messagelist.index(x)
print(dicta)
listo = ['l', 'i', 'j',]
result = itertools.combinations_with_replacement(listo, a)
lista2 = []
for each in result:
a =str(each).replace("(", "")
a = a.replace(")", "")
a = a.replace(",", "")
a = a.replace("'", "")
a = a.replace(" ", "")
lista2.append(a)
lista3 = []
for x in lista2:
listexa = list(x)
for item in dicta:
listexa.insert(dicta[item], item)
listexa = "".join(listexa)
lista3.append(listexa)
print(lista3)
if black in lista3:
print("DELETE")
else:
print("IT'S OKAY")
black = blacklisted word
s = user writing it with numbers
The problem is with words that contains more than one egual character like "finishing" that has 2 "n" characters, so in the dict, only 1 "n" will be added how can I solve this?
This will do the trick for you:
(I also tweaked the for loop, where you were iterating over combinations - just to keep it pythonish ;) )
import itertools
def repl(txt, pat):
if(len(pat)==0):
return txt
return repl(txt.replace("1", pat[0], 1), pat[1:])
black = "Ellie"
s = "E111e"
messagelist = list(s)
a = s.count("1")
dicta = {}
listo = ['l', 'i', 'j',]
result = itertools.combinations_with_replacement(listo, a)
lista2 = []
for each in result:
lista2.append("".join(each))
lista3 = []
for x in lista2:
listexa = repl(s, x)
lista3.append(listexa)
print(lista3)
if black in lista3:
print("DELETE")
else:
print("IT'S OKAY")
Consider function repl - the most important improvement. It essentially leverages the fact that python str.replace() can also take 3rd argument, which in essence defines number of replacements to be done - just to replace 1 one at a time.
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().
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.