How to debug and to fix syntax error in python - python

I'm trying to combine these two lists to the string "an abu is smart".
list1=["a","ab","i","smar"]
list2=["t","s","u","n",]
def merge_list(list1, list2):
merged=""
b=-1
result=''.join([str(a) + b for a,b in zip(list1,list2)])
return result
But I'm getting this error:
Traceback (most recent call last):
File "main.py", in <module>
merged=merge_list(list1,list2)
File "main.py",in merge_list
result=''.join([str(a) + b for a,b in zip(list1,list2)])
File "main.py",in <listcomp>
result=''.join([str(a) + b for a,b in zip(list1,list2)])
TypeError: Can't convert 'NoneType' object to str implicitly
How can I fix this?

list1=["a","ab","i","smar"]
list2=["t","s","u","n"]
def merge_list(list1, list2):
merged=""
b=-1
result=' '.join([str(a) + b for a,b in zip(list1,list2[::-1])])
return result
print(merge_list(list1, list2))
Output
'an abu is smart'

Related

How To Transpose matrix list

I am trying to Transpose matrix list but error:
def transpose_matriks(mat_a):
def wrapper():
temp_row = []
temp_mat = []
for i in range(0, pjg_matriks(mat_a)):
for j in range(0, lbr_matriks(mat_a)):
temp_row.append( mat_a[j][i])
temp_mat.append(temp_row)
temp_row = []
return temp_mat
return wrapper
#transpose_matriks
def matrixY():
X = [3,2,4,5]
return matrixY
print(matrixY())
erorr problem TypeError: object of type 'function' has no len() :
Traceback (most recent call last):
File "C:\Users\ASUS X441U\PycharmProjects\PfModul4\coba.py", line 23, in <module>
print(matrixX())
File "C:\Users\ASUS X441U\PycharmProjects\PfModul4\coba.py", line 4, in wrapper
rows = len (matrix)
TypeError: object of type 'function' has no len()
the output should be like this
matrixY = [3,4,2,5]

Setting two argument in one data

First, this is my code:
import re
clientaddress = ('192.168.10.111', 43567)
x = re.search("\d+.\d+.\d+.\d+\$", clientaddress)
print (x)
if x:
print("YES! We have a match!")
else:
print("No match")
Here is the problem. the 'ClientAddress' is imported from another server and its format is like this:
('IP', port)
So we have an (str, int).
the error is :
Traceback (most recent call last):
File "./prog.py", line 6, in <module>
File "/usr/lib/python3.7/re.py", line 183, in search
return _compile(pattern, flags).search(string)
TypeError: expected string or bytes-like object
After that, if I use this code:
import re
clientaddress = str('192.168.31.111', 43567)
clientaddress = ('192.168.31.111', 43567)
x = re.search("\d+.\d+.\d+.\d+\$", clientaddress)
print (x)
if x:
print("YES! We have a match!")
else:
print("No match")
The error that appeared is :
Traceback (most recent call last):
File "./prog.py", line 4, in <module>
TypeError: str() argument 2 must be str, not int
clientAddress is a tuple containing a string as the first element.
so index the tuple first and do the checking then. (clientaddress[0])
clientaddress = ('192.168.10.111', 43567)
x = re.search("\d+.\d+.\d+.\d+$", clientaddress[0])
print(x)

How i fix Traceback (most recent call last):

Hello I tried to fix this but I couldn't
This is my code:
import random
Cromosomas=[[random.randint(1, 1010) for i in range(3)] for j in range(800)]
Z=[]
Fitness=[]
P=[]
C=[]
Padres=[]
def funcOb(Arreglo):
return 0.2*Arreglo[0]**2+0.08*Arreglo[1]**2+0.18*Arreglo[2]**2+0.1*(Arreglo[0]*Arreglo[1])+0.04*(Arreglo[0]*Arreglo[2])+0.06*(Arreglo[1]*Arreglo[2])-0.14*Arreglo[0]-0.11*Arreglo[1]-0.1*Arreglo[2]+120+abs(Arreglo[0]+Arreglo[1]+Arreglo[2]-1000)-10
for i in range(0,800):
Z.append(funcOb(Cromosomas[i]))
for i in range(0,800):
Fitness.append(1/(1+Z[i]))
total=sum(Fitness)
for i in range(0,800):
P.append(Fitness[i]/total);
A=0
for i in P:
A=A+i
C.append(A)
R=[random.random()for i in range(800)]
for i in range(0,800):
for j in range(0,800):
if R[i]<=C[j]:
Cromosomas[i]=Cromosomas[j]
break
def mutar(Arreglo1,Arreglo2):
b=random.randint(0, 2)
if Arreglo1[b]<=Arreglo2[b]:
Arreglo2[b]=Arreglo1[b]
return Arreglo2
if Arreglo1[b]>=Arreglo2[b]:
Arreglo1[b]=Arreglo2[b]
return Arreglo1
for i in range(0,800):
r=random.random()
if r<(0.3):
n=Cromosomas[i]
if n not in Padres:
Padres.append(n)
r=0
for i in range(0,len(Padres)-1):
if len(Padres)==1:
Cromosomas[i]=[Padres[i][0],Padres[i][1],Padres[i][2]]
else:
lista=mutar(Padres[i],Padres[i+1])
Cromosomas[i]=[lista[0],lista[1],lista[2]]
for i in range(0,480):
Cromosomas[Cromosomas==random.randint(1, 2400)]=random.randint(1, 800)
for m in range(0,800):
print(funcOb(Cromosomas[m]))
error:
Traceback (most recent call last):
File "main.py", line 59, in <module>
print(funcOb(Cromosomas[m]))
File "main.py", line 10, in funcOb
return 0.2*Arreglo[0]**2+0.08*Arreglo[1]**2+0.18*Arreglo[2]
**2+0.1*(Arreglo[0]*Arreglo[1])+0.04*(Arreglo[0]*Arreglo[2])+0.
06*(Arreglo[1]*Arreglo[2])-0.14*Arreglo[0]-0.11*Arreglo[1]-0.1*
Arreglo[2]+120+abs(Arreglo[0]+Arreglo[1]+Arreglo[2]-1000)-10
TypeError: 'int' object has no attribute '__getitem__'
This error occurs when I try to run the last function of my code and I have no idea why the function that I call at the end is already one that I had already used and it does not give me a problem, also if I try other methods such as defining another function appears the same mistake.
ThankĀ“s for help

Accessing instance variables using index

I have a class which keeps track of errors encountered during a search operation
class SearchError(object):
def __init__(self,severity=0,message=''):
self.severity = severity
self.message = message
My idea is to make the instance variables indexable.
So if I have
a=SearchError(1,"Fatal Error")
I get
>>> a[0]
1
>>> a[1]
'Fatal Error'
>>> a.severity
1
>>> a.message
'Fatal Error'
To do this I add a __getitem__ method to the class. The class now becomes
class SearchError(object):
def __init__(self,severity=0,message=''):
self.severity = severity
self.message = message
def __getitem__(self,val):
if isinstance(val,slice):
return [self.__getitem__(i) for i in xrange(val.start,val.stop,val.step)]
elif val==0:
return self.severity
elif val==1:
return self.message
else:
raise IndexError
This does what I want but fails in cases such as
>>> a[:2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 23, in __getitem__
TypeError: an integer is required
Or even
>>> a[-1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 29, in __getitem__
IndexError
I understand my implementation of __getitem__ is limited. What I need to know is -
Is this the way to make instance variables indexable (Without using a list as variable container)?
How do I make the object behave 'sanely' as far as indexing goes?
This does everything:
>>> from collections import namedtuple
>>> _SearchError = namedtuple("SearchError", "severity message")
>>> def SearchError(severity=0, message=''):
return _SearchError(severity, message)
xrange requires all its arguments to be integers, but slice objects have None for unspecified attributes.
The best way to implement what you're after is to use namedtuple:
from collections import namedtuple
class SearchError(namedtuple('SearchError', 'severity message')):
def __new__(cls, severity=0, message=''):
return super(SearchError, cls).__new__(cls, severity, message)
The problem here is that slice objects default to having None values as attributes. So, a[:2] passes in slice(None,2,None). When you break this apart and try to pass it to xrange, you'll get a TypeError:
>>> xrange(None,2,None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required
Try a[0:2:1] and your code will work. Ultimately, you could do something like:
val.start = 0 if val.start is None else val.start
val.stop = 2 if val.stop is None else val.stop
val.stop = 2-val.stop if val.stop < 0 else val.stop
val.step = 1 if val.step is None else val.step
to unravel your slices into useable indices (In the general case, it'd be better to use len(self) instead of 2, but I don't know if your object has defined __len__.
Or, even better:
start,stop,step = val.indices(len(self))
Similarly, in the case where you do a[-1], you're not passing in a slice, a 0 or a 1, so you hit the else clause where you to raise an IndexError.
I mucked around the code and found the following solution.
It uses lists but to only store the names of the variables - Not the actual values. Additionally it also provides the method add to add a new variable with a given name and value. The new variable will also be indexable. (The add function is not needed by my class, but is nice to have around)
Thanks to #mgilson for nudging me in this direction
class SearchError(object):
def __init__(self,severity=0,message=''):
self.severity = severity
self.message = message
self._length = 2
self._vars_list = ['severity','message',]
def __getitem__(self,val):
if isinstance(val,slice):
steps = val.indices(self._length)
return [self.__getitem__(i) for i in xrange(*steps)]
elif val < 0:
i = self._length + val
if i < 0:
raise IndexError,"Index Out of range for SearchError object"
else:
return self.__getitem__(i)
else:
try:
return getattr(self,self._vars_list[val])
except IndexError:
raise IndexError,"Index Out of range for SearchError object"
def add(self,var_name,value):
self._vars_list.append(var_name)
self._length += 1
setattr(self,var_name,value)
The results
>>> a=SearchError(1,"Fatal Error")
>>> a[-1]
'Fatal Error'
>>> a[-2]
1
>>> a[-3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 14, in __getitem__
IndexError: Index Out of range for SearchError object
>>> a[2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 21, in __getitem__
IndexError: Index Out of range for SearchError object
>>> a[1]
'Fatal Error'
>>> a[0]
1
>>> a[:]
[1, 'Fatal Error']
>>> a.add('new_severity',8)
>>> a[:]
[1, 'Fatal Error', 8]
>>> a[3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 21, in __getitem__
IndexError: Index Out of range for SearchError object
>>> a[2]
8
>>> a.new_severity
8
>>> a[:3]
[1, 'Fatal Error', 8]
>>> a[:4]
[1, 'Fatal Error', 8]
>>> a[:2]
[1, 'Fatal Error']
As far as I can see, you need lists (to either store the actual variables or their names). If someone has a better alternative please do post

Python TypeErrors: "' list' object is not callable" and "'function' object is unsubscriptable"

I have the following code:
from random import randint,choice
add=lambda x:lambda y:x+y
sub=lambda x:lambda y:x-y
mul=lambda x:lambda y:x*y
ops=[[add,'+'],[sub,'-'],[mul,'*']]
def gen_expression(length,left,right):
expr=[]
for i in range(length):
op=choice(ops)
expr.append([op[0](randint(left,right)),op[1]])
return expr
def eval_expression (expr,x):
for i in expr:
x=i[0](x)
return x
def eval_expression2 (expr,x):
for i in expr:
x=i(x)
return x
[snip , see end of post]
def genetic_arithmetic(get,start,length,left,right):
batch=[]
found = False
for i in range(30):
batch.append(gen_expression(length,left,right))
while not found:
batch=sorted(batch,key=lambda y:abs(eval_expression(y,start)-get))
print evald_expression_tostring(batch[0],start)+"\n\n"
#combine
for w in range(len(batch)):
rind=choice(range(length))
batch.append(batch[w][:rind]+choice(batch)[rind:])
#mutate
for w in range(len(batch)):
rind=choice(range(length))
op=choice(ops)
batch.append(batch[w][:rind]+[op[0](randint(left,right)),op[1]]+batch[w][rind+1:])
found=(eval_expression(batch[0],start)==get)
print "\n\n"+evald_expression_tostring(batch[0],start)
When I try to call to call genetic_artihmetic with eval_expression as the sorting key, I get this:
Traceback (most recent call last):
File "<pyshell#113>", line 1, in <module>
genetic_arithmetic(0,10,10,-10,10)
File "/home/benikis/graming/py/genetic_number.py", line 50, in genetic_arithmetic
batch=sorted(batch,key=lambda y:abs(eval_expression(y,start)-get))
File "/home/benikis/graming/py/genetic_number.py", line 50, in <lambda>
batch=sorted(batch,key=lambda y:abs(eval_expression(y,start)-get))
File "/home/benikis/graming/py/genetic_number.py", line 20, in eval_expression
x=i[0](x)
TypeError: 'function' object is unsubscriptable
And when I try the same with eval_expression2 as the sorting,the error is this:
Traceback (most recent call last):
File "<pyshell#114>", line 1, in <module>
genetic_arithmetic(0,10,10,-10,10)
File "/home/benikis/graming/py/genetic_number.py", line 50, in genetic_arithmetic
batch=sorted(batch,key=lambda y:abs(eval_expression2(y,start)-get))
File "/home/benikis/graming/py/genetic_number.py", line 50, in <lambda>
batch=sorted(batch,key=lambda y:abs(eval_expression2(y,start)-get))
File "/home/benikis/graming/py/genetic_number.py", line 25, in eval_expression2
x=i(x)
TypeError: 'list' object is not callable
As far as i can wrap my head around this, my guess is that sorted() is trying to recursively sort the sublists,maybe? What is really going on here?
Python version is 2.6 - the one in the debian stable repos.
[snip] here:
def expression_tostring(expr):
expr_str=len(expr)*'('+'x '
for i in expr :
if i[1]=='*':
n=i[0](1)
else:
n=i[0](0)
expr_str+=i[1]+' '+str(n)+') '
return expr_str
def evald_expression_tostring(expr,x):
exprstr=expression_tostring(expr).replace('x',str(x))
return exprstr+ ' = ' + str(eval_expression(expr,x))
x=i[0](x) #here i is a function so you can't perform indexing operation on it
x=i(x) #here i is a list so you can't call it as a function
in both cases the value of i is fetched from expr, may be expr contains different type of object than what you're assuming here.
Try this modification:
def gen_expression(length,left,right):
expr=[]
for i in range(length):
op=choice(ops)
expr.append([op[0], randint(left,right),op[1]])
return expr
def eval_expression (expr,x):
for i in expr:
x=i[0](i[1])
return x
You had expr.append([op[0](randint(left,right)),op[1]]) which will put the return value of the calling the function into the 0th index.

Categories

Resources