indexerror in python with beaglebone black - python

y[i] = ADC.read("P9_40")
IndexError: list assignment index out of range
the code:
i = 1
x = []*1000
y = []*1000
for i in range(1000):
y[i] = ADC.read("P9_40") # adc input pin
x[i] = (int)(y*2147483648) # conversion of float to int
this code is read data from analogue pin of beaglebone black and store the result in array

In python you can't call a uncreated index of a list
x = []*1000 #creates only one empty list not 1000 list of list
y = []*1000 #like wise here
It should rather be like this
x = [[] for i in range(1000)]
y = [[] for i in range(1000)]

You don't create a 1000 element list by doing:
x = [] * 1000
y = [] * 1000
What you should do is create it with None values:
x = [None] * 1000
y = [None] * 1000
and then you can overwrite those None in your loop. None is better than
any integer value (like 0) that might come out of ADC.read(), as you can
check if the whole list is updated afterwards.

Related

Reverse a specific slice of a list in Python

I am trying to write a function that will receive a list and will return a list containing inverted elements between even and odd index. For example:
IP : [1,2,3,4]
OP : [2,1,4,3]
I don't understand why I get an IndexError: list index out of range error with the following code:
def mixed(list):
x = 0
y = 2
l = []
for element in list:
mod_list = list[x:y]
l.append(mod_list[1])
l.append(mod_list[0]
x += 2
y += 2
return l
The l.append(mod_liste[1]) seems to be the issue...
You can use built-in functions and slicing for that:
from itertools import chain
L = [1,2,3,4]
list(chain(*zip(L[1::2],L[::2]))) # [2,1,4,3]
If you don't want to use build-in function. Just make your loop stop when y is greater than list length. Make check for odd list.
def mixed(list):
x = 0
y = 2
l = []
for element in list:
mod_list = list[x:y]
l.append(mod_list[1])
l.append(mod_list[0])
x += 2
y += 2
if y > list.__len__() and list.__len__()%2 == 0:
break
elif y > list.__len__() and list.__len__()%2 != 0:
l.append(list[y-2])
break
return l

Find first non zero numbers in an array (zeroes can be anywhere)

Suppose we have an array: x = [10,0,30,40]. I would like to extract the first non zero element and store it in a different variable, say y. In this example, y = 10. We can also have many zeros, x = [0,0,30,40], which should give y = 30 as the extracted value.
I tried a Python snippet like this:
i = 0
while x[i] != 0:
y = arr[i]
if x[i] == 0:
break
This only works if the array is [10,0,30,40]. It does not work if I have 0,20,30,40. The loop would stop before that. What is an efficient way to implement this? I try not to use any special Numpy functions, just generic common loops because I might need to port it to other languages.
You can do this
x = [10,0,30,40]
for var in x:
if var != 0:
y = var
break
You could use list comprehension to get all the non-zero values, then provided there are some non-zero values extract the first one.
x = [10,0,30,40]
lst = [v for v in x if v != 0]
if lst:
y = lst[0]
print(y)
The problem with your code is that you don't increment i so it's stuck on the first element. So what you could do to keep the code portable is:
while x[i] != 0:
y = x[i]
if x[i] == 0:
break
i+=1
This code is still not clean, because if there is no 0 in your array then you will get an IndexError as soon as you reach the end.
I'm kind of new to this but i think this should work:
x = [0, 12, 24, 32, 0, 11]
y = []
for num in x:
if num != 0:
y.append(num)
break
print(y)
You can use the next function:
x = [10,0,30,40]
next(n for n in x if n) # 10
x = [0,0,30,40]
next(n for n in x if n) # 30
if you need to support the absence of zero in the list, you can use the second parameter of the next() function:
x = [0,0,0,0]
next((n for n in x if n),0) # 0

IndexError: list index out of range on python dynamic variable length

While I was creating a basic for-loop in Python within a function in order to work with a dynamic variable length (z) I've just come across the following error:
Rs = []
z = []
N = 120
m = 1
for i in range(1, N):
Rs[i] = z[m]
m = m + 1
Rs[i] = z[m]
IndexError: list index out of range
For the sake of clarity, I will explain better what I'm trying to do.
I would like to solve an equation system which is composed by a dynamical number of unknowns.
I've started to use the "static" method and It works perfectly. Basically, the code is more or less as follows:
from scipy.optimize import fsolve
def fixEqSyst(z):
v1 = z[0]
v2 = z[1]
v3 = z[2]
v4 = z[3]
f=np.zeros(4)
f[0] = 2*v1-3*v2+7*v3**2
f[1] = v1+3*v2**2-9*v3
f[2] = -3v1**2+12*v2+7*v3
f[3] = 4*v1+5*V2*v3
return f
z = fsolve(fixEqSyst, [0, 0, 0, 0])
Basing on the fact that now I will face with a dynamic number of unknowns and functions, is there any alternative solution than of what I've already put in place? (with a for-loop strategy)
Just in the first iteration of your loop you get
Rs[1] = z[1]
but z[1] don't exists, because z = [].
(The same for Rs[1].)
I haven't any idea how to fix it because I'm unable to guess what you wanted perform with you code.
Maybe you wanted to copy the contain of your - supposed nonempty - list z to Rs. Then they are 2 different simple solutions:
Rs = z
Attention! This is not a copy operation, this only associates other name to the same object, so every change in z will produce the same change in Rs and vice versa.
Rs = z[:]
This is the true (but shallow) copy. For simple lists this is the same as a deep copy.
When you assign a value to an array in python, the element must already exist. When you are assigning Rs[i] = z[m], you are assigning values out of the range of the list. You can use the += operator on a list in order to make it large enough, like this:
Rs = []
z = []
N = 120
m = 1
for i in range(m+N):
z += [m+i]
for i in range(N):
Rs += [z[m]]
m = m + 1
Note that += can only concatenate a list to another list. So this will work:
mylist = [1, 2, 3]
mylist += [4]
But this will not:
mylist = [1, 2, 3]
mylist += 4
Here is more on the += operator on lists.

Inserting values into list

I am trying to insert values in a list which is part of while loop, instead of inserting the last value is replacing the one before, so the list will always have only one value!, I am trying to add the values not replacing them, here is my code:
while X != 1:
resultList = [];
#extList = []
count += 1
if X % 2:
X = 3 * X + 1
elif not X % 2:
X = X // 2 #important to use double slash to have a integer division
print(X)
resultList.insert(count-1, X)
#print("the resultList is " + str(resultList))
#extList.extend(resultList)
print("The inputValue "+str(originalValue)+" took "+str(count)+" calculations to reach 1")
print (resultList)
any help is appreciated
On each iteration of while loop you creates new instance of resultList list.
while X != 1:
resultList = [];
...
should be replaced with
resultList = [];
while X != 1:
...
And to add new element to the end of list you could use append method. Like
resultList = [];
while X != 1:
if X % 2:
X = 3 * X + 1
else:
X = X // 2 #important to use double slash to have a integer division
print(X)
resultList.append(X)
The problem is here:
while X != 1:
resultList = [];
#etc
You are re-creating the list with every iteration of the loop. Hence, it will only have one value at the end, the one given by the only insert in the final iteration.
Taking the assignment out of the loop like so:
resultList = [];
while X != 1:
#etc
..fixes the problem.
An additional note, what you have done here is unnecessary:
elif not X % 2:
X = X // 2
You needn't repeat and invert your original condition. You can simply make it an else.
if X % 2:
X = 3 * X + 1
else:
X = X // 2

Efficiently insert numbers - NumPy / Python

Returns a new vector where every element is separated by 4 consecutive zeros. Trying to achieve [4,2,1] --> [4,0,0,0,0,2,0,0,0,0,1]
def zero_insert(x):
y = np.zeros((5*(len(x)-1))+1, dtype=np.int)
for i in range(len(x)):
y[5*i] = x[i]
return y
Initialize and assign -
x = np.asarray(x) # convert to array
n = 4 # number of zeros to be inserted
N = n+1
out = np.zeros((len(x)-1)*N+1,dtype=x.dtype)
out[::N] = x

Categories