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
Related
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'
I want to compute something using numpy and numba. This is my code:
import numpy as np
from numba import jit,double,int64
#jit(locals=dict(i=int64,j=int64,k=int64,l=int64,suma=double))
def omega_comp_arrays(omega,p_kl,eta,theta,K,L,links_by_ratings_array):
#new_omega = np.zeros(omega.shape)
for rating,links in enumerate(links_by_ratings_array):
for i,j in links:
suma = 0
for k in range(K):
for l in range(L):
omega[i,j,k,l] = p_kl[k,l,rating]*theta[i,k]*eta[j,l]
suma += omega[i,j,k,l]
omega[i,j,:,:] /= suma
return omega
N_nodes=2
N_veins=[1,1]
N_items=2
N_ratings=1
K=2
L=2
##Definim matrius
theta = np.random.rand(N_nodes,K)
eta = np.random.rand(N_items,L)
p_kl = np.random.rand(K,L,N_ratings)
suma = np.sum(theta,axis =1)
theta /=suma[:,np.newaxis]
suma = np.sum(eta,axis=1)
eta /= suma[:,np.newaxis]
suma = np.sum(p_kl,axis =2)
p_kl /=suma[:,:,np.newaxis]
links_by_ratings_array = [np.array([0,0])]
omega = np.ones((N_nodes,N_items,K,L))
omega = omega_comp_arrays(omega,p_kl,eta,theta,K,L,links_by_ratings_array)
The problem occurs when I run the code:
Traceback (most recent call last):
File "test_omega.py", line 39, in <module>
omega = omega_comp_arrays(omega,p_kl,eta,theta,K,L,links_by_ratings_array)
TypeError: 'numpy.int64' object is not iterable
Exception TypeError: "'NoneType' object is not callable" in <bound method ModuleRef.__del__ of <llvmlite.binding.module.ModuleRef object at 0x7f801123d3d0>> ignored
But if I activate the nopython mode, another error appears:
Traceback (most recent call last):
File "test_omega.py", line 39, in <module>
omega = omega_comp_arrays(omega,p_kl,eta,theta,K,L,links_by_ratings_array)
File "/usr/local/lib/python2.7/dist-packages/numba/dispatcher.py", line 330, in _compile_for_args
raise e
numba.errors.TypingError: Caused By:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/numba/compiler.py", line 240, in run
stage()
File "/usr/local/lib/python2.7/dist-packages/numba/compiler.py", line 454, in stage_nopython_frontend
self.locals)
File "/usr/local/lib/python2.7/dist-packages/numba/compiler.py", line 881, in type_inference_stage
infer.propagate()
File "/usr/local/lib/python2.7/dist-packages/numba/typeinfer.py", line 846, in propagate
raise errors[0]
TypingError: failed to unpack int64
File "test_omega.py", line 10
[1] During: typing of exhaust iter at test_omega.py (10)
Failed at nopython (nopython frontend)
failed to unpack int64
File "test_omega.py", line 10
[1] During: typing of exhaust iter at test_omega.py (10)
In other words, I can't do a loop of a list of arrays because the error is in the loop of links (for i,j in links). Any suggestion?
This is the code I currently have:
def uniform_distribution(users,radius):
user_coordinates_distance=[]
user_coordinates=[]
finding_shadowing=[]
r=radius*np.sqrt(np.random.uniform(0,1,users))
angle=2*np.pi*np.random.uniform(0,1,users)
x = r*np.cos(angle)
y = r*np.sin(angle)
user_distance = np.sqrt(x*x+y*y)
x_shadowing=1000*x
y_shadowing=1000*y
x_shadowing=(x_shadowing-x_shadowing%10)/10
y_shadowing=(y_shadowing-y_shadowing%10)/10
finding_shadowing=shadowing(x_shadowing,y_shadowing,shadowing_matrix)
print(finding_shadowing)
for i in range (0,users):
user_coordinates=[x[i],y[i],user_distance[i],finding_shadowing[i]]
user_coordinates_distance.append(user_coordinates)
return (user_coordinates_distance)
And this is the error I get when I run it:
Traceback (most recent call last):
File "C:\Users\Ajit\Desktop\maryland\Sem 2\ENTS 656\project656\main program and functions\main_1.py", line 136, in <module>
user_coordinates=uniform_distribution(attempts,cell_radius)#list [x,y,distance,shadowing]
File "C:\Users\Ajit\Desktop\maryland\Sem 2\ENTS 656\project656\main program and functions\main_1.py", line 81, in uniform_distribution
finding_shadowing=shadowing(x_shadowing,y_shadowing,shadowing_matrix)
TypeError: 'float' object is not callable
What exactly does this error mean?
I have a problem with the following function in python (where swap is a function that I have previously created and that works fine):
def swap (cards):
"""
>>> swap('FBFFFBFFBF')
'BFBBBFBBFB'
>>> swap('BFFBFBFFFBFBBBFBBBBFF')
'FBBFBFBBBFBFFFBFFFFBB'
>>> swap('FFBFBFBFBFBFBFBBFBFBFBFBBFBFBBFBF')
'BBFBFBFBFBFBFBFFBFBFBFBFFBFBFFBFB'
"""
invert=""
for i in cards:
if i is "B":
invert+="F"
else:
invert+="B"
return (invert)
def swap2 (cards):
"""
>>> next('FBFFFBFFBF')
'FFBBBFBBFF'
>>> next('BFFBFBFFFBFBBBFBBBBFF')
'FBBFBFBBBFBFFFBFFFFFF'
>>> next('FFBFBFBFBFBFBFBBFBFBFBFBBFBFBBFBF')
'FFFBFBFBFBFBFBFFBFBFBFBFFBFBFFBFF'
"""
indices=""
for pos, i in enumerate(cards):
if i =="B":
indices+=str(pos)
first= int(indices[0])
last= int(indices[-1])
prefix= cards [:first]
middle= cards [first:last+1]
suffix= cards [last+1:]
middle2=swap(middle)
return (prefix+middle2+suffix)
def turns (cards):
"""
>>> turns('FBFFFBFFBF')
3
>>> turns('BFFBFBFFFBFBBBFBBBBFF')
6
>>> turns('FFBFBFBFBFBFBFBBFBFBFBFBBFBFBBFBF')
14
"""
turn=0
while cards != 'F'*len(cards):
cards=swap2(cards)
turn+=1
return (turn)
if __name__ == '__main__':
import doctest
doctest.testmod()
when I run this function it works fine but if I use doctest to see if there are mistakes it tells me:
TypeError: 'str' object is not an iterator
I don't know where this error comes from.
Can anyone help me?
complete output of the doctest:
File "C:\Users\manuel\Documents\Gent MaStat\programming and algorithms\workspace_python\homeworks\Week 5\looking_up.py", line 25, in __main__.swap2
Failed example:
next('FBFFFBFFBF')
Exception raised:
Traceback (most recent call last):
File "C:\Users\manuel\Anaconda3\lib\doctest.py", line 1321, in __run
compileflags, 1), test.globs)
File "<doctest __main__.swap2[0]>", line 1, in <module>
next('FBFFFBFFBF')
TypeError: 'str' object is not an iterator
**********************************************************************
File "C:\Users\manuel\Documents\Gent MaStat\programming and algorithms\workspace_python\homeworks\Week 5\looking_up.py", line 27, in __main__.swap2
Failed example:
next('BFFBFBFFFBFBBBFBBBBFF')
Exception raised:
Traceback (most recent call last):
File "C:\Users\manuel\Anaconda3\lib\doctest.py", line 1321, in __run
compileflags, 1), test.globs)
File "<doctest __main__.swap2[1]>", line 1, in <module>
next('BFFBFBFFFBFBBBFBBBBFF')
TypeError: 'str' object is not an iterator
**********************************************************************
File "C:\Users\manuel\Documents\Gent MaStat\programming and algorithms\workspace_python\homeworks\Week 5\looking_up.py", line 29, in __main__.swap2
Failed example:
next('FFBFBFBFBFBFBFBBFBFBFBFBBFBFBBFBF')
Exception raised:
Traceback (most recent call last):
File "C:\Users\manuel\Anaconda3\lib\doctest.py", line 1321, in __run
compileflags, 1), test.globs)
File "<doctest __main__.swap2[2]>", line 1, in <module>
next('FFBFBFBFBFBFBFBBFBFBFBFBBFBFBBFBF')
TypeError: 'str' object is not an iterator
def swap2 (cards):
"""
>>> next('FBFFFBFFBF')
'FFBBBFBBFF'
>>> next('BFFBFBFFFBFBBBFBBBBFF')
'FBBFBFBBBFBFFFBFFFFFF'
>>> next('FFBFBFBFBFBFBFBBFBFBFBFBBFBFBBFBF')
'FFFBFBFBFBFBFBFFBFBFBFBFFBFBFFBFF'
"""
# …
The function is called swap2 but within the doctests, you are using next which happens to be a built-in function that does something completely different. That’s why you are seeing that error.
At times like this, it’s really important to actually look at the error messages. It clearly told you what was called:
File "<doctest __main__.swap2[0]>", line 1, in <module>
next('FBFFFBFFBF')
So if you don’t know where that was supposed to come from, then check out the error message. Doctest will tell you what it is executing: swap2[0], swap2[1], etc. tells you the function name the docstring that is being executed is by doctest and which test case it is (0 is the first, 1 the second etc.). It even gives you the line number (within the doctest case) where the error appeared, and of course the line that was causing the error. So use that information to go to the problematic code, and figure out what the problem is.
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.