Assign numpy ndarray to list - python

Can someone help me with my question. I have created a loop which in every execution produce a numpy.ndarray of size (5,) but when the loop terminates and I want to print the results of my code it only print the last ndarry of size 5, I tried to assigned the results in a list but I get "too many indices for array"
k=0;
for i in range(M):
for j in range(N):
if table[i, j] != 0:
k=k+1;
inv=np.linalg.inv(np.dot(X.T,X));
theta[k,:] = np.dot(inv,X.T).dot(HSI[i,j,:])
I want to assign the results on theta[] so if I want to print the result from the second execution I will write theta[1] and so on.
Most likely my false is on the last line

A quick sketch, you can amend as necessary
import random
a=[] #start with an empty set
k=0
while k< 5:
b=random.sample(range(1,100), 5) #get a random sample of length 5 within range of 1-100
a.append(b) # add/'append' b to your currently empty set of 'a'
print a #print current contents of 'a'
k=k+1
I've not run this but it seems intuitive.
Good luck!

Related

Python Find the mean school assignment - What is a loop?

I have been working on this assignment for about 2 weeks and have nothing done. I am a starter at coding and my teacher is really not helping me with it. She redirects me to her videos that I have to learn from every time and will not directly tell or help me on how I can do it. Here are the instructions to the assignment (said in a video, but made it into text.
Find the mean
Create a program that finds the mean of a list of numbers.
Iterate through it, and instead of printing each item, you want to add them together.
Create a new variable inside of that, that takes the grand total when you add things together,
And then you have to divide it by the length of your array, for python/java script you’ll need to use the method that lets you know the length of your list.
Bonus point for kids who can find the median, to do that you need to sort your list and then you need to remove items from the right and the left until you only have one left
All you’re doing is you need to create a variable that is your list
Create another variable that is a empty one at the moment and be a number
Iterate through your list and add each of the numbers to the variable you created
Then divide the number by the number of items that you had in the list.
Here's what I've done so far.
num = [1, 2, 3, 4, 5, 6];
total = 0;
total = (num[0] + total)
total = (num[1] + total)
total = (num[2] + total)
total = (num[3] + total)
total = (num[4] + total)
total = (num[5] + total)
print(total)
However, she tells me I need to shorten down the total = (num[_] + total) parts into a loop. Here is how she is telling me to do a loop in one of her videos.
for x in ____: print(x)
or
for x in range(len(___)): print (x+1, ____[x])
there is also
while i < len(___):
print(___[i])
i = i + 1
I really don't understand how to do this so explain it like I'm a total noob.
First of all, loops in python are of two types.
while: a while loop executes the code in a body until a condition is true. For example:
i = 0
while(i < 5):
i = i + 1
executes i = i + 1 until i < 5 is true, meaning that when i will be equal to 5 the loop will terminate because its condition becomes false.
for: a for loop in python iterates over the items of any sequence, from the first to the last, and execute its body at each iteration.
Note: in both cases, by loop body I mean the indented code, in the example above the body is i = i + 5.
Iterating over a list. You can iterate over a list:
Using an index
As each position of the array is indexed with a positive number from 0 to the length of the array minus 1, you can access the positions of the array with an incremental index. So, for example:
i = 0
while i < len(arr):
print(arr[i])
i = i + 1
will access arr[0] in the first iteration, arr[1] in the second iteration and so on, up to arr[len(arr)-1] in the last iteration. Then, when i is further incremented, i = len(arr) and so the condition in the while loop (i < arr[i]) becomes false. So the loop is broken.
Using an iterator
I won't go in the details of how an iterator works under the surface since it may be too much to absorb for a beginner. However, what matters to you is the following. In Python you can use an iterator to write the condition of a for loop, as your teacher showed you in the example:
for x in arr:
print(x)
An iterator is intuitively an object that iterates over something that has the characteristic of being "iterable". Lists are not the only iterable elements in python, however they are probably the most important to know. Using an iterator on a list allows you to access in order all the elements of the list. The value of the element of the list is stored in the variable x at each iteration. Therefore:
iter 1: x = arr[0]
iter 2: x = arr[1]
...
iter len(arr)-1: x = arr[len(arr)-1]
Once all the elements of the list are accessed, the loop terminates.
Note: in python, the function range(n) creates an "iterable" from 0 to n-1, so the for loop
for i in range(len(arr)):
print(arr[i])
uses an iterator to create the sequence of values stored in i and then i is in turn used on the array arr to access its elements positionally.
Summing the elements. If you understand what I explained to you, it should be straightforward to write a loop to sum all the elements of a list. You initialize a variable sum=0 before the loop. Then, you add the element accessed as we saw above at each iteration to the variable sum. It will be something like:
sum = 0
for x in arr:
sum = sum + x
I will let you write an equivalent code with the other two methods I showed you and do the other points of the assignment by yourself. I am sure that once you'll understand how it works you'll be fine. I hope to have answered your question.
She wants you to loop through the list.
Python is really nice makes this easier than other languages.
I have an example below that is close to what you need but I do not want to do your homework for you.
listName = [4,8,4,7,84]
for currentListValue in listName:
#Do your calculating here...
#Example: tempVar = tempVar + (currentListValue * 2)
as mentioned in the comments w3schools is a good reference for python.

How can I get this nested for loop skip the first and the last list in the 2D array in order to print out a board surrounded with +'s?

The goal of my Python program is printing out a user-specified N^N board surrounded with +'s using a 2D array. To do that I first created a 2D list with N+2 lines and rows of +'s. Then using a nested for loop, I tried to replace the +'s with " " on indices 1 to N+1(not including) on each row except the first and the last rows, so that my code would print out a N^N board on the inside, surrounded with +'s. However I could not get my program to skip the first and last lines when erasing the +'s, despite excluding their indices in the 2D List in the nested for loop.
Thank you for your help in beforehand!
Here is my code.
This is the desired output (for N=5)
And this is the output of my code.
In your code, you do:
board =[['+'] * (N+2)] * (N+2)
This makes a list with N+2 references to the same list.
So everytime you change a 'middle square' to a white space inside your code(board[x][y] = " ") for a particular row x, you're infact actually changing all the tiles in the column y in your board to the white space simultaneously, since all the rows refer to but one list.
Instead, you should use something like this which actually creates (N+2) separate lists:
board =[['+'] * (N+2) for _ in range(N+2)]
This has also been explained in greater detail in this stackoverflow answer
Making the above change in the code results in the output you desire.
Although, it is a good practice to think of your own approaches & code it out when you're learning, but reading other people's code along with that will give you some hints towards multiple better approaches that you should eventually try to come up with. Here, are my two cents. Keeping it simple!
# board dimension
N = 5
# print board
def print_board(board):
for i in range(N):
for j in range(N):
print(board[i][j], end='')
print()
# declare & populate the board
board = []
for i in range(N):
row = []
for j in range(N):
row.append('+')
board.append(row)
# state of board initially
print_board(board)
print()
# Your logic of removing the plus sign, simply don't include the first & last
# row and column for converting into space
for i in range(1,N-1):
for j in range(1,N-1):
board[i][j] = ' '
print_board(board)
to make this pattern you can simply use for loops.
N = int(input())
for i in range(N+2):
for j in range(N+2):
if(i == 0 or i == N+1 or j == 0 or j == N+1):
print('+', end = '')
else:
print(' ', end = '')
print()

How to update a variable inside the while loop and see the results?

I want to use a for loop to define a range and I would like to use a while loop to check a condition for every value inside this for loop and give me the results for different values of c, but unfortunately, my algorithm doesn't work and I don't know what my mistake is.
j=0
jl=[]
c=np.linspace(0,20,num=20)
for a in range(0,len(c)):
while j<5:
j=c[a]+2
jl.append(j)
The result I am looking for is it puts different values of c inside the while loop and calculate j and check if it is bigger than 5 or not. if yes, it appends it to jl. Totally, I want to define a range with for loop with index and also check each value of this range inside while loop and get the results for j.
so expected results are j with values smaller than 5 (c[a]+2<5) and store the values of j in jl
There is one problem in your code:
j=0
"While loop" never runs because his condition is j>5. Correct that and tell us if it works.
Please double check if the following suggested solution covers all of your requirements. In any case I think List Comprehensions (e.g. compare section 5.1.3.) can help you.
c=np.linspace(0,20,num=20)
ls = [x+2 for x in c if((x+2)<5)]
print(ls)
Will result in the following output:
[2.0, 3.052631578947368, 4.105263157894736]
If you want to do more complex data manipulation, you can also do this with the help of functions, e.g. like:
def someManipulation(x):
return x+2
ls = [someManipulation(x) for x in c if(someManipulation(x)<5)]
Your algorithm doesn't work because
while j<5:
j=c[a]+2
is an infinite loop for j = 0, a = 0.
What you probably wanted to write was:
for x in c:
j = x + 2
if j < 5:
jl.append(j)
Still, the list comprehension version in the other answer does exactly the same, but better.

How do I check every element in an appended text in python

I am doing the Euler project questions and the question I am on right now is least common multiple. Now I can go the simple route and get the factors and then find the number that way, but I want to make my life hard.
This is the code I have so far in Python:
i = 0
j = 0
count = []
for i in range (1,10):
for j in range(1,11):
k = i%j
count.append(k)
print(count)
Now when I print this out I get an array and every time I goes through the loop, the previous information is appended on with it. How can I make it so that the previous information is not appended?
Second once I get that information how can I look at each value in the array and only print out those elements that are equal to 0? I feel like I have to use the all() function but for some reason I just dont get how to use it.
Any and all help is appreciated.
For your first question, you should know the scope of variable. Just define the variable count inside the outer loop and before the inner loop starts.
You can try this if you want nothing but zero elements.
print [element for element in count if element == 0]
If I understand your question right the answer for your question is like this.
i = 0
j = 0
for i in range (1,10):
# Resetting so that count will not have previous values
count = []
for j in range(1,11):
k = i%j
count.append(k)
# printing all the indexes where the value is '0'
print([index for index, item in enumerate(count) if item == 0])
You know your range of extern loop so you can just write your code in this way :
count = []
for i in range (1,10):
for j in range(1,11):
k = i%j
if(i == 9):
count.append(k)
print(count)
print("Without 0:")
print([x for x in count if x is not 0])

2d Array Python :list index out of range

I am new to Python programming and I am trying to write code to check if a DFA( Deterministic Finite Automata) has empty language or not.
I am using 2-d array to store state of the DFA.
On executing the code I keep getting list index out of range. How can I fix this?
Below is the code
top=-1
count=0
n=int(input("\nEnter the no of states"))
mat=[[]]
b=[]
print("\nEnter the transition table")
for i in range(0,n):
for j in range(0,n):
mat.append(input())
finalState=input("\nEnter the final state:")
startState=input("\nEnter the start state:")
for i in range(0,n):
for j in range(0,n):
if mat[i][j]:
b[++top]=j
for k in range(top):
if b[k]==finalState:
count+=1
if count>0:
print("\nLanguage is not empty")
else:
print("\nLanguage is empty")
when you make a 2x2 table, you want mat to be [[1,2],[3,4]], but you're getting [[],1,2,3,4] right now.
Instead, try:
mat = []
for i in range(n):
row = []
for j in range(n):
row.append(input())
mat.append(row)
Also, Python does not have a "++" operator, so b[++top]=j is the same as b[top] = j. If you want to increment top, you have to do that on its own line before you use it to index the list.
On top of that, b has zero elements, so indexing it in any way will cause a crash. If you're trying to increase the size of b by adding new items to it, use append. Then you don't need a top variable at all.
b.append(j)

Categories