How to parse a matrix in Python? - python-2.7

I created a matrix of 0s using join(). Assignment works if I hotcode it. If I get as an input, it doesn't work.
theatre=[]
for i in range(5):
theatre.append(["0"]*5)
def print_screen(theatre):
for i in theatre:
print(" ".join(i))
print_screen(theatre)
theatre[int(raw_input("Enter row"))][int(raw_input("Enter col"))]=="x" ## this doesn't work
theatre[0][1]="x" ## This is working.

Oh Boy surely the problem you stated would exist in your code as it is NOT AT ALL A PROBLEM as far as python interpreter is considered.
See what you are doing
theatre[int(raw_input("Enter row"))][int(raw_input("Enter col"))]=="x" ## this doesn't work
is to compare if the value at a given point in the matrix is equal to x or not, so as far as your code goes python is comparing the given point and then just moving on to the next statement.
I would suggest that instead of asking here, it would be more helpful for you if you try to debug your code using print() statement or any debugger.

Related

How to use xlwings asynchronous mode with dynamic arrays?

When using async_mode='threading' I noticed the following behaviour:
#xw.func(async_mode='threading')
#xw.ret(expand='table')
def test_fun():
time.sleep(2)
return [[0], [1], [2]]
The above code will output correctly 0, 1, 2 but this will output an array (ie the excel formula will have the {} brackets) and it will overwrite anything below it, ie won't use that spill warning and you can't edit it without editing the entire array.
#xw.func(async_mode='threading')
def test_fun():
time.sleep(2)
return [[0], [1], [2]]
This however which seems more desirable as it outputs a dynamic array (were I to remove the async_mode) only outputs 0 and the formula turns into #test_fun() and thus only returns the first value.
Experiencing this behaviour on v0.15.8
Your second example is the correct way of doing it and works for me. The first version is only if you specifically want to work with the legacy CSE arrays which is normally only the case when your version of Excel is not supporting dynamic arrays.
Just make sure to delete the CSE version of your formula completely, then re-import the function and simply call =test_fun() from a cell in Excel.
This should work from version v0.19.0 onwards - this was the issue that was being experienced. OP had v0.15.8.
https://github.com/xlwings/xlwings/issues/1277

Extract output from scipy optimise

After minimising a two parameter function in Python using the Powell algorithm, I am left with the following output:
fun: -3.5839582049322310
maxcv: 0.0
message: 'Optimization terminated successfully.'
nfev: 98
status: 1
success: True
x: array([ 1.9116445888705806, 3.7094985019795996])
I wish to extract the two optimised parameters in x to then be carried through to another part of the script. Is there a way to automate the extraction of these numbers without having to manually enter them in the script? I have looked in the scipy documentation but have not found anything on how to access the output.
It would be helpful to see the code you use to calculate your result, now I can only guess what you did.
I assume your code looks like:
res = scipy.optimize.minimize(fun, f0, method='Powell')
This function returns an optimizeResult object. To get the actual result of your optimization you need to call
print(res.x)
The type of res.x is a numpy.ndarray. If you want to proceed only if your calculation was successful, then you can do something like
if res.success:
print('success, the results are')
print(res.x)

Apply a function to a range of cells in a spreadsheet

The answers in topics with similar titles haven't given me much of a resolution to my particular problem, but possibly I am not asking the right question. It might help knowing I'm an absolute noob when it comes to spreadsheets, so finding my way around is next to nil.
Currently I can set a basic function in the first cell A1 =ROW()
Simple right? Well now here comes the complication. If I click on the bottom right of the cell and start dragging I can then apply that very same function to a whole range of cells. Let's say I apply it from A1:A10. Every cell within this group now has the same function.
Hooray! We did it, right? I applied a function to a range of cells each with their own output. But wait, if I then go back to the original cell and change its formula none of the other cells change with it. GRRRRR!!!!
There are a couple of fixes I've come up with but don't necessarily know how to implement. The first is to have every cell link back to the original cell and reference its function. This would be useful if I wanted to randomly scatter dependent cells about the document. The other would be much more useful in an orderly group where you know the exact dimensions by specifying in the original cell the size of the array you want to apply the function to.
With that said, let me hear your thoughts.
The closest I've come to an answer is to use FORMULA() which returns the formula used by a cell as text. Unfortunately all answers on evaluating the text resort to scripting. How strange! I thought something like this would be common. Might as well get to scripting.
Hold on, I may have spoke too soon. An array can be made with =MUNIT(), but it's only square. Drats!
Ok... I'm hoping the zebra stripes will eventually become its own answer unless someone else beats me to it. So a simple array can be made with ={1,2;3,4} where commas separate values by column and semicolons for values by row except to generate it you have to press Control+Shift+Enter (because reasons?). I'm thinking now that I'll need to have functions that can generate lists of values based on a single function for each row, and pray that it'll work. So, back to looking. (Wow this is taking forever)
The way I was hypothesizing can't even generate a 1x1, e.g., ={ROW()} returns Err:512 which is a formula overflow.
Alright, in summary so far I've narrowed down the two options,
1) link every cell to the original formula
2) populate an array with a single formula
each with their own incomplete answer,
a) use FORMULA() to return the formula of a cell as text
b) create a hypothetical array like so ={LIST_OF_VALUES()}
These both require a strange form of the nonexistent EVALUATE() function to 'function' correctly. Isn't that fun?
Google Sheets handles case b by allowing ={ROW()}Control+Shift+Enter to generate =ArrayFormula({ROW()}). Working with the general case of any sized array being filled with a single function doesn't exist in the world of spreadsheets it seems. That's very saddening because I can't think of a much better tool for what I want to do. Copy paste it is until I need to use macros.
Depending on your specific use case, creating a user-defined function may help:
use the Basic IDE to create your function;
apply it to any cells on any sheet;
modifying the Basic code will affect all cells where the function is used.
I've elaborated the steps in an answer on superuser.
Sure, you could write some complex code to update functions, but wouldn't the easy way be just to drag it to the same range of cells the same way you did before? It should properly overwrite the existing code in there, and if it doesn't, you can just as easily delete the outdated code and drag the new code in.
Probably the best approach is to simply drag the amended formula over the range of cells (as advised by OldBunny2800). This is less error prone and easier to maintain than a custom macro.
Another option would be to use an array function. Then you only have to edit the function once, and the same edit will be automatically applied to the whole range of cells in that array function.

How to print content of a list of pointers in gdb?

I have the following list of pointers:
(here is a simple example, but in reality, my list could be componed by hundreds of entries)
{0xae5c4e8, 0xa09d4e8, 0xa753458, 0xae554e8}
I successfully print pointers content, one by one, by using :
p *(const Point *) 0xae5c4e8
How can I print contents of the preceding list in one command ?
There is no canned way to do this. It would be cool if you could type print *(*p # 23) -- using the # extension inside another expression, resulting in an implicit loop -- but you can't.
However, there are two decent ways to do this.
One way to do it is to use Python. Something like:
(gdb) python x = gdb.parse_and_eval('my_array')
(gdb) python
> for i in range(nnn):
> print x[i].dereference()
> end
You can wrap this in a new gdb command, written in Python, pretty easily.
Another way is to use define to make your own command using the gdb command language. This is a bit uglier, and has some (minor) limitations compared to the Python approach, but it is still doable.
Finally, once upon a time there was a gdb extension called "duel" that provided this feature. Unfortunately it was never merged in.
I don't think there is a simple way to show all the list elements at once. You could try to iterate through the items using:
set $it=mylist.begin()._M_node
print *(*(std::_List_node<const Point *>*)$it)._M_data
set $it=(*$it)._M_next
...
In the batch way. The problem is that the list items do not need to be located near to each other in the memory. To have better preview option in debug you could switch to the std::vector.
Hope this will help.
I have the following list of pointers:
You don't appear to have a list, you appear to have an array. Let's assume that it looks something like:
void *array[10] = {0xae5c4e8, 0xa09d4e8, 0xa753458, 0xae554e8};
You can print the first 4 dereferenced elements of that array like so:
(gdb) print ((Point**)array)[0]#4

Xlrd list index out of range

I'm just starting to explore Xlrd, and to be honest am pretty new to programming altogether, and have been working through some of their simple examples, and can't get this simple code to work:
import xlrd
book=open_workbook('C:\\Users\\M\\Documents\\trial.xlsx')
sheet=book.sheet_by_index(1)
cell=sheet.cell(0,0)
print cell
I get an error: list index out of range (referring to the 2nd to last bit of code)
I cut and pasted most of the code from the pdf...any help?
You say:
I get an error: list index out of range (referring to the 2nd to last
bit of code)
I doubt it. How many sheets are there in the file? I suspect that there is only one sheet. Indexing in Python starts from 0, not 1. Please edit your question to show the full traceback and the full error message. I suspect that it will show that the IndexError occurs in the 3rd-last line:
sheet=book.sheet_by_index(1)
I would play around with it in the console.
Execute each statement one at a time and then view the result of each. The sheet indexes count from 0, so if you only have one worksheet then you're asking for the second one, and that will give you a list index out of range error.
Another thing that you might be missing is that not all cells exist if they don't have data in them. Some do, but some don't. Basically, the cells that exist from xlrd's standpoint are the ones in the matrix nrows x ncols.
Another thing is that if you actually want the values out of the cells, use the cell_value method. That will return you either a string or a float.
Side note, you could write your path like so: 'C:/Users/M/Documents/trial.xlsx'. Python will handle the / vs \ on the backend perfectly and you won't have to screw around with escape characters.