-1

I'm a beginner in python. I wrote a function as follows:

import numpy as np

def crossover(v1,v2):

    N=2
    v1n=np.zeros(shape=(1,N+1))
    v2n=np.zeros(shape=(1,N+1))
    beta=np.random.rand(1)

    v1n[0,0]=(1-beta)*v1[0]+beta*v2[0]
    v1n[0][1]=v1[1]
    v2n[0][0]=(1-beta)*v2[0]+beta*v1[0]
    v2n[0][1]=v2[1]

    return (v1n,v2n)

when I want to see crossover([3,4],[7,8]), the following error....:

Traceback (most recent call last):

  File "<pyshell#82>", line 1, in <module>

    crossover([4,5],[5,4])

  File "C:\Python27\crossover.py", line 11, in crossover

    v1n[0,0]=(1-beta)*v1[0]+beta*v2[0]

TypeError: 'int' object has no attribute '__getitem__'
Manuel Allenspach
  • 12,467
  • 14
  • 54
  • 76
Mehrian
  • 11
  • 3

1 Answers1

0

Your code is running fine on python 2.7.8 (on my computer). But i suggest your output is bad. if you run your code you get output:

(array([[ 4.91965332, 5. , 0. ]]), array([[ 4.08034668, 4. , 0. ]]))

This is actually a tuple with two arrays containing each a list. you are using numpy for small 'arrays' and that is actually slower than normal list. numpy is used for hundreds, even thousands of data.

check this link for more info about numpy speed

i would suggest you just use list instead.

let me give you an example on how i would have done it without numpy :D

import random

v1=[5,4]
v2=[4,5]

# basicly random number from 0 to 1
beta=random.random()

# let's initialize v1n and v2n (:
v1n = [0,0,0]
v2n = [0,0,0]

v1n[0] = (1-beta)*v1[0]+beta*v2[0]
v1n[1] = v1[1]

v2n[0] = (1-beta)*v2[0]+beta*v1[0]
v2n[1]=v2[1]

print("first 3d array:")
print(v1n)

print("second 3d array:")
print(v2n)

print("note that this really is 2d arrays because the 3rd dimension is always zero")
Community
  • 1
  • 1
  • Quick note if you ever need help with python. I am a member of "Python Programming Language" group on Facebook. We answer questions, have competitions and stuff. New members are especially welcome (: – Victor Loke Chapelle Hansen Oct 19 '14 at 13:29