From random import choice issue with Pycharm - random

I get issues when trying to run the -
from random import choice
I am trying to get generate random questions when running the code. It simply does not run the code inside Pycharm, but works fine inside idle3.
from random import choice
questions = ["Why is the sky blue?: ", "Why is there a face on the moon?: ",
"Where are all the dinosaurs: "]
question = choice(questions)
answer = input(question).strip().lower()
while answer != "just because":
answer = input("why?: ").strip().lower()
print("Oh... Okay")
My aim is to generate random questions when answered correctly.

Related

Print best move with python_chess

Easy question, but I'm doing something wrong and don't know what :(
I'm using the python-chess libary and want to print the best move to the engine (Stockfish).
I'm able to print the score from the engine with
board = chess.Board(fen)
info = engine.analyse(board, chess.engine.Limit(time=0.1))
print(info["score"])
but I'm not able to print the move
best_move = chess.engine.PlayResult(chess.Move, chess.engine.Limit(time=0.1), draw_offered=False, resigned=False, )
I alway get something like this: PlayResult at 0x1ef108495e0
The documentation (https://python-chess.readthedocs.io/en/latest/_modules/chess/engine.html#Protocol search for "best move") didn't help, alway get some errrors.
If you use Stockfish, pip install stockfish, and you can get the best move by using :\
from stockfish import Stockfish
stockfish = Stockfish('the stockfish place in your computer')
stockfish.set_fen_position("your FEN")
stockfish.get_best_move()
See the page of the project here.

Python script for Pymol with user input

I have prepared a script for Pymol that works well in evaluating RMSD values for a list of residues of proteins of interest (targetted residues are generated by script embedded commands). However, I wished to implement the script to allow the user to select the analysed residues. I have tried to use the input function, but it fails to work. Since the code is a bit long, I simplified progressively the scripts. In that way, I ended up with the following two scripts:
"test.py":
import Bio.PDB
import numpy as np
from pymol import cmd
import os,glob
from LFGA_functions import user_entered
List_tot = user_entered()
print (List_tot)
which calls the simple "user_entered" function from inside the "My_function.py" script:
def user_entered():
List_res = []
List_tot = []
a = input("Please indicate the number of residues to analyze/per monomer:")
numberRes =int(a)
for i in range(numberRes):
Res = input("Please provide each residue NUMBER and hit ENTER:")
Res1 = int(Res)
Res2 = Res1+2000
Res3 = Res1+3000
Res4 = Res1+4000
Res5 = Res1+5000
Res6 = Res1+6000
List_res = (str(Res1),str(Res2),str(Res3),str(Res4),str(Res5),str(Res6))
List_tot.append(List_res)
return List_tot
The script "test.py" works well when executed by Python (3.7.5, which is installed with Pymol 2.3.4,under Windows 7 Prof) from a windows command line. An example of result:
[first input to indicate that 2 cases will be treated, followed by the identification number for each case][1]
However, when the script is run from Pymol GUI, I get the following error message: input():lost sys.stdin
Does anybody know what is the problem. Obviously, I am a very primitive Python user...
I profit also to ask something related to this problem... in the original script that works well in Pymol, before trying to implement the "input" option, I store transiently some data (residue name, type and chain) in the form of a "set". I need a set, and not a list, because it removes automatically data repeatitions. However, when I try to run it from PYthon (thinking of overcoming the abovementioned problem of input), it stops with a message: name 'close_to_A' not defined. However, it is as shown in the portion of code shown here below, and indeed works in Pymol.
...
# Step 3:
# listing of residues sufficiently close to chainA
# that will be considered in calculation of RMSD during trajectory
cmd.load("%s/%s" %(path3,"Average.pdb"), "Average", quiet=0)
cmd.select("around_A", "Average and chain B+C near_to 5 of chain A")
cmd.select("in_A", "Average and chain A near_to 5 of chain B+C")
close_to_A = set()
cmd.iterate("(around_A)","close_to_A.add((chain,resi,resn))")
cmd.iterate("(in_A)","close_to_A.add((chain,resi,resn))")
cmd.delete("around_A")
cmd.delete("in_A")
...
How shall I define a set in Python 3 ? Why does it work when run from Pymol ?
I would really appreciate if you could help me to solve these two problems. Thank you in advance,
Best regards,
Luis

Importing a Mathematica Matrix

I am trying to import a very large matrix file to a variable using the code below. The matrix is of the form {{A,B,C},{D,E,D},{G,F,A}}
inputseq2s = Import[ "C:\Users\jdd0758\Desktop\WaveformsOnly.txt","Data"]
However when I import it like this, it is not read as if it was entered as:
inputseq2s = {{A,B,C},{D,E,D},{G,F,A}}
Extra commas are added to the input and it will not work in my algorithm. How can I make this work properly?

What is the corret syntax for using max function

Still using bloody OpenOffice Writer to customize my sale_order.rml report.
In my sale order I have 6 order lines with 6 different lead time to delivery. I need to show the maximum out of the six values.
After many attempt I have abandoned using the reduce function as it works erratically or not at all most of the time. I have never seen anything like this.
So I thought I'd give a try using max encapsulating a loop such as:
[[ max(repeatIn(so.order_line.delay,'d')) ]]
My maximum lead time being 20, I would expect to see 20 (yes well that would be too easy, wouldn't it!).
It returns
{'d': 20.0}
At least it contains the value I am after.
But; if I try and manipulate this result, it disappears altogether.
I have tried:
int(re.findall(r'[0-9]+', max(repeatIn(so.order_line.delay,'d')))[0])
which works great from the python window, but returns absolutely nothing in OpenERP.
I import the re from my sale_order.py file, which I have recompiled into sale_order.pyo:
import time
import re
from datetime import datetime, timedelta
from report import report_sxw
class order(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context=None):
super(order, self).__init__(cr, uid, name, context=context)
self.localcontext.update({
'time': time,
'datetime': datetime,
'timedelta': timedelta,
're': re,
})
I have of course restarted the server many times. My test install sits on windows.
So can anyone tell me what I am doing wrong, because I can make it work from Python but not from OpenOffice Writer!
Thanks for your help!
EDIT 1:
The format
{'d': 20.0}
is, according to python, a dictionary. Still in Python, to extract the integer from a dictionary it is possible to do it like so:
>>> dict={'d': 20.0}
>>> print(dict['d'])
20.0
But how can I transpose this to OpenERP writer???
I have manage to get the result I wanted by importing functools and declaring the reduce function within the parameters of the sale_order.py file.
I then simply used a combination of reduce and max function and it works exactly as expected.
The correct syntax is as follow:
repeatIn(objects,'o')
reduce(lambda x, y: max(x, y.delay), o.order_line, 0)
Nothing else is required.
Enjoy!

Managing Setup code with TimeIt

As part of a pet project of mine, I need to test the performance of various different implementations of my code in Python. I anticipate this to be something I do alot of, and I want to try to make the code I write to serve this aim as easy to update and modify as possible.
It's still in its infancy at the moment, but I've taken to using strings to manage common setup or testing code, eg:
naiveSetup = 'from PerformanceTests.Vectors import NaiveVector\n' \
+ 'left = NaiveVector([1,0,0])\n' \
+ 'right = NaiveVector([0,1,0])'
This allows me to only write the code once, at the expense of making it harder to read and clunky to update.
Is there a better way?
Use triple quotes """
setup_code = """
from PerformanceTests.Vectors import NaiveVector
left = NaiveVector([1,0,0])
right = NaiveVector([0,1,0])
"""
Another interesting method is provided in the docs of timeit:
def test():
"Stupid test function"
L = []
for i in range(100):
L.append(i)
if __name__=='__main__':
from timeit import Timer
t = Timer("test()", "from __main__ import test")
print t.timeit()
Though this isn't suitable for all needs.
Timing code is fine, but it will still leave you guessing what's going on.
To find out what's actually going on, manually pause it a few random times in the debugger, and examine the call stack.
For example, in the code that is 30x slower in one implementation than in another, each sample of the stack has a 96.7% chance of falling in the extra time that it is spending, so you can see why.
No guesswork required.

Resources