as the title say i have been searching the solution of this problem :
TypeError: 'list' object is not callable
for a while, but i did find only answers about naming variables with defaults names like, for instance, list. And i think this is not my case, in particular this the concerned code:
next_matrix = 0
c = 0
routes = []
mapp_matrix = []
mapp = []
def del_nl(l):
for i in range(len(l)):
del l[i][-1]
# check if there is a valid route in a map from a starting point
def route(n_map, n_command, s_point):
for i in n_command:
if i == 'N':
s_point[0] = s_point[0] - 1
elif i == 'S':
s_point[0] = s_point[0] + 1
elif i == 'E':
s_point[1] = s_point[1] + 1
elif i == 'W':
s_point[1] = s_point[1] -1
try:
if n_map[s_point[0]][s_point[1]] != '.':
return False
except IndexError:
return False
return True
## Getting datas for every map ##
with open("/home/senso/programming/ctf_magio/input-sample.txt", "r") as f:
for line in f:
# i am reading values for the dimension of the map
if c == next_matrix:
line = line.split(" ")
int_list = [int(i) for i in line]
if not c == 0:
del_nl(mapp)
mapp_matrix.append(mapp[:])
del mapp[:]
# reading the commands
elif c == next_matrix + 1:
route = list(line)
del route[-1]
routes.append(route)
next_matrix = next_matrix + int_list[0] + 2
else:
#building the map
mapp.append(list(line))
c = c+1
del_nl(mapp)
mapp_matrix.append(mapp[:])
ship_alive = 0
for i in range(len(mapp_matrix)):
for j in range(len(mapp_matrix[i])):
for z in range(len(mapp_matrix[i][j])):
#oh my god is O(n^3), will it explode??
if mapp_matrix[i][j][z] == '.':
point = [j, z]
if route(mapp_matrix[i], routes[i], point):
ship_alive = 1 + ship_alive
and i get this error
File "capitanSonar.py", line 78, in
if route(mapp_matrix[i], routes[i], point):
TypeError: 'list' object is not callable
If i try to call 'route' with static lists it works.
Any help is appreciated.
# reading the commands
elif c == next_matrix + 1:
route = list(line) # <- Here. Pick a different name for the list
del route[-1]
routes.append(route)
next_matrix = next_matrix + int_list[0] + 2
else:
#building the map
mapp.append(list(line))
c = c+1
Related
This is my code for a programming problem in a CS course that involves tokenizing a string by its opening and closing parentheses.
def expand(S):
if "(" in S:
open, close = parentheses_pair(S)
open = int(int(open) + int(1))
samp = S[open, close]
currstr = samp
innerstr = ""
if "(" in samp:
open, close = parentheses_pair(S)
currstr = samp[:open]
innerstr = samp[open, close+1]
innerstr = expand(innerstr)
output = ""
for i in range(1, len(currstr), 2):
letter = currstr[i-1]
number = currstr[i]
output += letter*number
output += innerstr
sorted_out = sorted(output)
output = "".join(sorted_out)
return output
else:
return ""
def parentheses_pair(S):
counter = 0
openpar = S.find("(")
currind = S.find("(")
found = False
while not found:
if S[currind] == "(":
counter += 1
elif S[currind] == ")":
if counter == 1:
found = True
break
else:
counter -= 1
currind += 1
return int(openpar), int(currind)
When I used type on both open and close, <class 'int'> was returned by the terminal so I really don't know why it won't accept the variables as the string indices on samp = S[open, close].
This is a password generator, I couldn't really determine where the problem is, but from the output, I could say it's around turnFromAlphabet()
The function turnFromAlphabet() converts an alphabetical character to its integer value.
The random module, I think doesn't do anything here as it just decides whether to convert a character in a string to uppercase or lowercase. And if a string is in either, when sent or passed to turnFromAlphabet() it is converted to lowercase first to avoid errors but there are still errors.
CODE:
import random
import re
#variables
username = "oogisjab" #i defined it already for question purposes
index = 0
upperOrLower = []
finalRes = []
index2a = 0
#make decisions
for x in range(len(username)):
decision = random.randint(0,1)
if(decision is 0):
upperOrLower.append(True)
else:
upperOrLower.append(False)
#Apply decisions
for i in range(len(username)):
if(upperOrLower[index]):
finalRes.append(username[index].lower())
else:
finalRes.append(username[index].upper())
index+=1
s = ""
#lowkey final
s = s.join(finalRes)
#reset index to 0
index = 0
def enc(that):
if(that is "a"):
return "#"
elif(that is "A"):
return "4"
elif(that is "O"):
return "0" #zero
elif(that is " "):
# reduce oof hackedt
decision2 = random.randint(0,1)
if(decision2 is 0):
return "!"
else:
return "_"
elif(that is "E"):
return "3"
else:
return that
secondVal = []
for y in range(len(s)):
secondVal.append(enc(s[index]))
index += 1
def turnFromAlphabet(that, index2a):
alp = "abcdefghijklmnopqrstuvwxyz"
alp2 = list(alp)
for x in alp2:
if(str(that.lower()) == str(x)):
return index2a+1
break
else:
index2a += 1
else:
return "Error: Input is not in the alphabet"
#real final
finalOutput = "".join(secondVal)
#calculate some numbers and chars from a substring
amount = len(finalOutput) - round(len(finalOutput)/3)
getSubstr = finalOutput[-(amount):]
index = 0
allFactors = {
};
#loop from substring
for x in range(len(getSubstr)):
hrhe = re.sub(r'\d', 'a', ''.join(e for e in getSubstr[index] if e.isalnum())).replace(" ", "a").lower()
print(hrhe)
#print(str(turnFromAlphabet("a", 0)) + "demo")
alpInt = turnFromAlphabet(hrhe, 0)
print(alpInt)
#get factors
oneDimensionFactors = []
for p in range(2,alpInt):
# if mod 0
if(alpInt % p) is 0:
oneDimensionFactors.append(p)
else:
oneDimensionFactors.append(1)
indexP = 0
for z in oneDimensionFactors:
allFactors.setdefault("index{0}".format(index), {})["keyNumber"+str(p)] = z
index+=1
print(allFactors)
I think that you are getting the message "Error: input is not in the alphabet" because your enc() change some of your characters. But the characters they becomes (for example '#', '4' or '!') are not in your alp variable defined in turnFromAlphabet(). I don't know how you want to fix that. It's up to you.
But I have to say to your code is difficult to understand which may explain why it can be difficult for you to debug or why others may be reluctant to help you. I tried to make sense of your code by removing code that don't have any impact. But even in the end I'm not sure I understood what you tried to do. Here's what I understood of your code:
import random
import re
#username = "oogi esjabjbb"
username = "oogisjab" #i defined it already for question purposes
def transform_case(character):
character_cases = ('upper', 'lower')
character_to_return = character.upper() if random.choice(character_cases) == 'upper' else character.lower()
return character_to_return
username_character_cases_modified = "".join(transform_case(current_character) for current_character in username)
def encode(character_to_encode):
translation_table = {
'a' : '#',
'A' : '4',
'O' : '0',
'E' : '3',
}
character_translated = translation_table.get(character_to_encode, None)
if character_translated is None:
character_translated = character_to_encode
if character_translated == ' ':
character_translated = '!' if random.choice((True, False)) else '_'
return character_translated
final_output = "".join(encode(current_character) for current_character in username_character_cases_modified)
amount = round(len(final_output) / 3)
part_of_final_output = final_output[amount:]
all_factors = {}
for (index, current_character) in enumerate(part_of_final_output):
hrhe = current_character
if not hrhe.isalnum():
continue
hrhe = re.sub(r'\d', 'a', hrhe)
hrhe = hrhe.lower()
print(hrhe)
def find_in_alphabet(character, offset):
alphabet = "abcdefghijklmnopqrstuvwxyz"
place_found = alphabet.find(character)
if place_found == -1 or not character:
raise ValueError("Input is not in the alphabet")
else:
place_to_return = place_found + offset + 1
return place_to_return
place_in_alphabet = find_in_alphabet(hrhe, 0)
print(place_in_alphabet)
def provide_factors(factors_of):
for x in range(1, int(place_in_alphabet ** 0.5) + 1):
(quotient, remainder) = divmod(factors_of, x)
if remainder == 0:
for current_quotient in (quotient, x):
yield current_quotient
unique_factors = set(provide_factors(place_in_alphabet))
factors = sorted(unique_factors)
all_factors.setdefault(f'index{index}', dict())[f'keyNumber{place_in_alphabet}'] = factors
print(all_factors)
Is near what your wanted to do?
i am coding python in PyCharm and it is giving me this warning:
type 'list' doesn't have expected attribute 'tolist'
however I have declared my variable list, and here is my code:
...
my_list = []
big_list = []
i= 0
count = 0
while i < len(data):
if data[i][3] < 0:
i += 1
continue
my_list.append([data[i][0], data[i][1], data[i][2], data[i][3]])
if i == len(df) - 1:
count += 1
self.myfancyfunction(my_list, count)
big_list.append(my_list)
elif i < len(data) - 1 and data[i][3] != data[i + 1][3]:
count += 1
self.myfancyfunction(my_list, count)
big_list.append(my_list)
my_list = []
cluster += 1
i += 1
in the two instances of self.myfancyfunction(my_list, count), the my_list variable is underlined and shows the above error.
Could you please help to fix this?
update
here is my fancy function:
def myfancyfunction(self, array_ls, count):
dict1 = {}
dict2 = {}
array_ls = np.asarray(array_ls)
array_ls = array_ls[:, 2].astype(int)
self.info_ids.append(array_ls.tolist())
sys.stdout.flush()
with open('myfile.txt', "r") as myfile:
for line in myfile:
if int(line.split()[0]) in array_ls:
for element in line.split()[1:]:
key = element.split(":")[0]
value = float(element.split(":")[1])
if key in self.reference:
if not str(key) in dict1:
dict1[str(key)] = 1
dict2[str(key)] = value
else:
dict1[str(key)] += 1
dict2[str(key)] += value
self.info_freq.append(dict1)
self.info_vals.append(dict2)
I am inside a class and have a couple of functions.
I have a string like '....(((...((...' for which I have to generate another string 'ss(4)h5(3)ss(3)h2(2)ss(3)'.
'.' corresponds to 'ss' and the number of continous '.' is in the bracket.
'(' corresponds to 'h5' and the number of continuos '(' is in the bracket.
Currently I'm able to get the output 'ss(4)h5(3)ss(3)' and my code ignores the last two character sequences.
This is what I have done so far
def main():
stringInput = raw_input("Enter the string:")
ssCount = 0
h5Count = 0
finalString = ""
ssString = ""
h5String = ""
ssCont = True
h5Cont = True
for i in range(0, len(stringInput), 1):
if stringInput[i] == ".":
h5Cont = False
if ssCont:
ssCount = ssCount + 1
ssString = "ss(" + str(ssCount) + ")"
ssCont = True
else:
finalString = finalString + ssString
ssCont = True
ssCount = 1
elif stringInput[i] == "(":
ssCont = False
if h5Cont:
h5Count = h5Count + 1
h5String = "h5(" + str(h5Count) + ")"
h5Cont = True
else:
finalString = finalString + h5String
h5Cont = True
h5Count = 1
print finalString
main()
How to modify the code to get the desired output?
I don’t know about modifying your existing code, but to me this can be done very succinctly and pythonically using itertools.groupby. Note that I’m not sure if the 'h2' in your expected output is a typo or if it should be 'h5', which I’m assuming.
from itertools import chain, groupby
string = '....(((...((...'
def character_count(S, labels): # this allows you to customize the labels you want to use
for K, G in groupby(S):
yield labels[K], '(', str(sum(1 for c in G)), ')' # sum() counts the number of items in the iterator G
output = ''.join(chain.from_iterable(character_count(string, {'.': 'ss', '(': 'h5'}))) # joins the components into a single string
print(output)
# >>> ss(4)h5(3)ss(3)h5(2)ss(3)
#Kelvin 's answer is great, however if you want to define a function yourself, you could do it like this:
def h5ss(x):
names = {".": "ss", "(": "h5"}
count = 0
current = None
out = ""
for i in x:
if i == current:
count += 1
else:
if current is not None:
out += "{}({})".format(names[current], count)
count = 1
current = i
if current is not None:
out += "{}({})".format(names[current], count)
return out
I am not sure why do i get this error from the console:
<<
print stirngp[state[i][j]]
^
SyntaxError: invalid syntax
<<
Furthermore it seems that the IDE put a red close on the following code line
line = raw_input("Enter:")
I am not sure what did i do wrong, the following code is as shown below
def isTerminal(state):
stateT = zip(*state)
for i in range(3):
if all(state[i][0] == j for j in state[i]) and state[i][0] != 0:
return state[i][0]
if all(stateT[i][0] == j for j in stateT[i]) and stateT[i][0] != 0:
return stateT[i][0]
if (state[0][0] == state[1][1] == state[2][2]) or \
(state[0][2] == state[1][1] == state[2][0]):
if state[1][1] != 0:
return state[1][1]
for i in range(3):
if 0 in state[i]:
return None
return 0
def succ(state):
# print state
countX = 0
countO = 0
for i in range(3):
for j in range(3):
if state[i][j] == 1: countX = countX + 1
if state[i][j] == -1: countO = countO + 1
if countX > countO:
player = "MIN"
else:
player = "MAX"
succList = []
v = {"MIN":-1,"MAX":1}
for i in range(3):
for j in range(3):
if state[i][j] == 0:
succ = [k[:] for k in state]
succ[i][j] = v[player]
succList = succList + [succ]
# print succList
return succList
def nextplay(player):
if player == "MIN":
return "MAX"
else:
return "MIN"
def minimax(state,alpha,beta,player):
value = isTerminal(state)
if value != None:
# print "TERMINAL:", state, value, player
return value
if player == "MIN":
for y in succ(state):
beta = min(beta, minimax(y,alpha,beta,"MAX"))
if beta <= alpha: return alpha
return beta
if player == "MAX":
for y in succ(state):
alpha = max(alpha, minimax(y,alpha,beta,"MIN"))
if alpha >= beta: return beta
return alpha
def printing(state):
p = {-1:"O",0:".",1:"X"}
for i in range(3):
for j in range(3):
print p[state[i][j]],
print ""
print ""
def main():
state = [[0,0,0],
[0,0,0],
[0,0,0]]
val = isTerminal(state)
while val == None:
line = raw_input("Enter:")
x = line.split(",")
a = int(x[0]); b = int(x[1])
state[a][b] = 1
if isTerminal(state) != None:
printing(state)
return
# determine which successive state is better
succList = succ(state)
succValList = []
for i in succList:
succValList = succValList + [(minimax(i,-1,1,"MAX"),i)]
succValList.sort(key=lambda x:x[0])
state = succValList[0][1] # can also randomly choose other states of the same minimax value
printing(state)
val = isTerminal(state)
if __name__ == '__main__':
main()
As far as i know you can't use raw_input() in Python 3. It's been changed to just input()
http://docs.python.org/dev/whatsnew/3.0.html
also what is stringp? is it an existing list?
if so then state[i][j] MUST return an integer so you can retrieve the item at that index of stringp[]