0

I have learned not long time ago how to shift objects in an array, usually numbers. Now I attached it to my piece of code that should generate random objects in an array or list.

Question: How do I modify the second part so that I can get it to work with the first part?

This is the most confusing part of programming. I know it's a stupid question but i am still studying and i'm not very good but i really want to become better.

def randomArray(n_Elementi, my_vector):
    for i in range(0, n_Elementi):
        newElement=random.randint(1,500)
        my_Vector.append(newElement)

return 

def shift(seq, n):
    newElement = []
    for i in range(len(seq)):
    newElement.append(seq[(i-n) % len(seq)])
return newElement

randomArray(n_Elementi, my_vector)
shift (newElement)
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Aecrim
  • 18
  • 3
  • How does this differ from ["Efficient way to shift a list in python"](http://stackoverflow.com/questions/2150108/efficient-way-to-shift-a-list-in-python)? – Ignacio Vazquez-Abrams Nov 18 '14 at 17:40
  • nothing. I've learned alot of things on this website.. but it's hard for me to get things toghether, i study coding also at school but i find it easier online. That's why i actually asked it here. – Aecrim Nov 18 '14 at 17:53
  • i also found this other way , newElement.rotate(-1) but my program still gives me some errors – Aecrim Nov 18 '14 at 18:00
  • Also, they're called lists. In Python, the word "array" generally refers to a NumPy array. – Max Noel Nov 18 '14 at 18:08
  • oh i see thanks, my teacher calls them arrays, vectors.. so i followed his words but since it's a list i guess i'll call it just list now it sounds more simple haha :) – Aecrim Nov 19 '14 at 22:00

1 Answers1

0

There were some indent problems, capitals mismatch but on the whole your code works:

import random
def randomArray(n_Elementi, my_Vector):
    for i in range(0, n_Elementi):
        newElement=random.randint(1,500)
        my_Vector.append(newElement)
    return 

def shift(seq, n):
    newElement = []
    for i in range(len(seq)):
        newElement.append(seq[(i-n) % len(seq)])
    return newElement

n_Elementi = 10
my_vector=[]
randomArray(n_Elementi, my_vector)
print my_vector
print shift (my_vector, 3)

however, this can greatly simplified. Here is one way using numpy (Numeric Python, it's like the MAtlab of python)

import random
import numpy as np

#rand creates array between 0,1. multiple by 500 and recast to int to get the range you want
def randomArray(n_Elementi):    
    return np.array(np.random.rand(n_Elementi)*500,dtype=int) 

#seq[-n:] takes the elements n from the end to the end [-n:]. This is called splicing. similarly [:-n] ...
def npshift(seq, n):
    return np.concatenate((seq[-n:], seq[:-n]))

n_Elementi = 10
my_vector=randomArray(n_Elementi)
print my_vector
print shift (my_vector, 3)
aivision2020
  • 619
  • 6
  • 14