Append result of iteration in python - python

I am pretty new to python, i am using python 3 and have some difficulties to append the result of the iteration to the array, following is my chunk of my code:
A = np.random.randn(len(meas),numx)
lengthA = np.linspace(0,len(A[0])-1,num=len(A[0]),dtype=int)
anorm = []
for j in range(0,len(lengthA)):
x_normed = A/A.max(axis=0)
anorm[:,j] = A[:,j]*x_normed[j]
Is it necessary to append the new result to empty anom ? somehow the code always tell me that the list of the indices must be integer and not tuple. Any help will be appreciated.

When assigning a value to an array at index n via the array[index] = value syntax, the argument within the square brackets must be an integer. In your situation, j is an integer but [:,j] attempts to reference multiple indices within the array.
for j in range(0,len(lengthA)):
x_normed = A/A.max(axis=0)
anorm[j] = A[:,j]*x_normed[j]
As an aside, if you want your for loop to run for as many iterations as there are elements within lengthA, then you can simply do:
for j in lengthA:
do stuff

Related

Python list first n entries in a custom base number system

I am sorry if the title is a misnomer and/or doesn't properly describe what this is all about, you are welcome to edit the title to make it clear once you understand what this is about.
The thing is very simple, but I find it hard to describe, this thing is sorta like a number system, except it is about lists of integers.
So we start with a list of integers with only zero, foreach iteration we add one to it, until a certain limit is reached, then we insert 1 at the start of the list, and set the second element to 0, then iterate over the second element until the limit is reached again, then we add 1 to the first element and set the second element 0, and when the first element reaches the limit, insert another element with value of 1 to the start of the list, and zero the two elements after it, et cetera.
And just like this, when a place reaches limit, zero the place and the places after it, increase the place before it by one, and when all available places reach limit, add 1 to the left, for example:
0
1
2
1, 0
1, 1
1, 2
2, 0
2, 1
2, 2
1, 0, 0
The limit doesn't have to be three.
This is what I currently have that does something similar to this:
array = []
for c in range(26):
for b in range(26):
for a in range(26):
array.append((c, b, a))
I don't want leading zeroes but I can remove them, but I can't figure out how to do this with a variable number of elements.
What I want is a function that takes two arguments, limit (or base) and number of tuples to be returned, and returns the first n such tuples in order.
This must be very simple, but I just can't figure it out, and Google returns completely irrelevant results, so I am asking for help here.
How can this be done? Any help will truly be appreciated!
Hmm, I was thinking about something like this, but very unfortunately I can't make it work, please help me figure out why it doesn't work and how to make it work:
array = []
numbers = [0]
for i in range(1000):
numbers[-1] += 1
while 26 in numbers:
index = numbers.index(26)
numbers[index:] = [0] * (len(numbers) - index)
if index != 0:
numbers[index - 1] += 1
else:
numbers.insert(0, 1)
array.append(numbers)
I don't quite understand it, my testing shows everything inside the loop work perfectly fine outside the loop, the results are correct, but it just simply magically will not work in a loop, I don't know the reason for this, it is very strange.
I discovered the fact that if I change the last line to print(numbers) then everything prints correctly, but if I use append only the last element will be added, how so?
from math import log
def number_to_base(n,base):
number=[]
for digit in range(int(log(n+0.500001,base)),-1,-1):
number.append(n//base**digit%base)
return number
def first_numbers_in_base(n,base):
numbers=[]
for i in range(n):
numbers.append(tuple(number_to_base(i,base)))
return numbers
#tests:
print(first_numbers_in_base(10,3))
print(number_to_base(1048,10))
print(number_to_base(int("10201122110212",3),3))
print(first_numbers_in_base(25,10))
I finally did it!
The logic is very simple, but the hard part is to figure out why it won't work in a loop, turns out I need to use .copy(), because for whatever reason, doing an in-place modification to a list directly modifies the data reside in its memory space, such behavior modifies the same memory space, and .append() method always appends the latest data in a memory space.
So here is the code:
def steps(base, num):
array = []
numbers = [0]
for i in range(num):
copy = numbers.copy()
copy[-1] += 1
while base in copy:
index = copy.index(base)
copy[index:] = [0] * (len(copy) - index)
if index != 0:
copy[index - 1] += 1
else:
copy.insert(0, 1)
array.append(copy)
numbers = copy
return array
Use it like this:
steps(26, 1000)
For the first 1000 lists in base 26.
Here is a a function, that will satisfy original requirements (returns list of tuples, first tuple represents 0) and is faster than other functions that have been posted to this thread:
def first_numbers_in_base(n,base):
if n<2:
if n:
return [(0,)]
return []
numbers=[(0,),(1,)]
base-=1
l=-1
num=[1]
for i in range(n-2):
if num[-1]==base:
num[-1]=0
for i in range(l,-1,-1):
if num[i]==base:
num[i]=0
else:
num[i]+=1
break
else:
num=[1]+num
l+=1
else:
num[-1]+=1
numbers.append(tuple(num))#replace tuple(num) with num.copy() if you want resutl to contain lists instead of tuples.
return numbers

Python: Altering list values from a loop

I am creating a simple Bin packing program in Python for a class and am having a scope issue that I cannot quite track down. I am attempting to alter the value in the ffBins list however the list the value is unaltered.
The print results show what I expect ("10 5 5") as i is subtracted from j but it is not altering the value in the actual list as I am expecting. I suspect I need to point at the list in a different way during the loop but the solution is eluding me. Is there a simple way to alter the values in the list instead of just the current j variable?
ffBins.append(10)
for i in ffItems:
itemPacked = 0
for j in ffBins:
#print(j)
if j >= i:
print(j),
print(i),
j = j-i
print(j)
itemPacked = 1
#break
if itemPacked == 0:
ffBins.append(10)
ffBins[-1] = ffBins[-1]-ffItems[i]
All you're doing in this code is rebinding j to a new value. You need to set the value back in the list by its index. You can use enumerate to get the index as well as the value.
for index, j in enumerate(ffBins):
...
ffbins[index] = j - i

python - how to reassign element in array with for loop

I have a numpy array of floats that I want to reassign with a different value using a for loop but PyCharm says the new variable assignment isn't being used.
If I have, say:
for i in array:
i = i * 5
It will say that i is an unused variable. What am I doing wrong?
You need to assign values to array elements. Otherwise you array will remain unchanged. There are a couple of ways.
Using your current attempt as a starting point, you can use enumerate. Given an input array:
for idx, val in enumerate(array):
array[idx] = val * 5
But this doesn't take advantage of NumPy vectorisation. You can simply use:
array *= 5
Should be:
for i in range(len(array)):
array[i] = array[i] * 5
What you did was creating a temporary variable "i", which exists only on each loop iteration, it is initialized with the value of an element from the list and then it's deleted.
A more pythonic way of doing this would be:
array = [i*5 for i in array]

Single Line Nested For Loops in Python

I'm having some trouble understanding how nested single line for loops work. Here's an example:
I have this code:
NewArray = np.array([ get_position(i, size-1, t) for i in range(0, size)])
and I'm trying to rewrite this to:
for i in range(0,size):
NewArray = np.array([ get_position(i, size-1, t)])
But I'm getting different outputs, so I'm guessing there's a logic error here.
Could you point out the issue?
Thank you
It's because the first one creates a numpy array containing all your values (you create all values because you're using a list comprehension) and the second one creates a new array containing the last value each iteration (and it discards the array created in the last iteration because you reuse the same name).
You could rewrite the second one as:
lst = []
for i in range(0,size):
lst.append(get_position(i, size-1, t))
NewArray = np.array(lst)
that should give the same result as your first operation.
In the first you create an array of length size.
In the second you repeatedly (size times) create an array of length 1.

Issues with printing in python a list of arrays

I'm new in the magic python world.
I have a problem: I save data from a file in a list of array (13 arrays of 130 element each) but when I try to print the values, only the same values with bracket are printed .
I defined the list and the array in this way:
List = []
v = np.ndarray(shape=(130,1),dtype=float)
After I fill my data structure from the file
f=open(filename, 'r').readlines()
k = 0
for i in range(0,13):
for j in range(0,130):
v[j] = float(f[k])
k += 1
List.append(v)
In the file I have for each line a float value and the total length is 13*130.
I don't even know if I feed correctly my data structure, what I only know is that the function that I would like to use expect a list of array instead of a matrix.
I tried different way for seeing if I saved in a correct way the data.
Do you have any suggestion?
You need to recreate v in every iteration of the outer loop:
for i in range(0,13):
v = np.ndarray(shape=(130,1),dtype=float)
for j in range(0,130):
v[j] = float(f[k])
k += 1
List.append(v)
Otherwise, you're just updating the same reference over and over again (list.append only appends the reference to the list, does not copy the list in question).
If your only problem is printing without the brackets, then I think what you want (see me comment on the post) is the following:
for row in list:
for item in row:
print item,
print "" # print a newline
You can try: for i in List: print(i)
If you do not want the brackets to be displayed : for i in a: print(' '.join(map(str,i)))
But if you want to have constant row widths, create a function that returns a string of the float of constant length :
def auxString(float, length):
s = str(float)
s+=(length-len(s))*' '
return s
string = lambda length: lambda float: auxString(float,length)
for i in List:
print(' '.join(map(string(5),i))) #if the maximum length of your string of float is 5

Categories

Resources