Python's math module & "Think Python" - python

I'm stucked on the chapter 3.3 "Math functions" of "Think Python".
It tells me to import math (through the interpreter).
Then print math and that I should get something like this:
<module 'math' from '/usr/lib/python2.5/lib-dynload/math.so'>
Instead I get <module 'math' <built-in>>
Anyway that's not the problem. Though I wasn't able to find a 'math.so' file in my python folder. The most similar file is named test_math.
The problem is that I'm supposed to write this:
>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)
>>> radians = 0.7
>>> height = math.sin(radians)
When I write the first line it tells me this:
Traceback <most recent call last>:
File "<stdin>", line 1, in <module>
NameError: name 'signal_power' is not defined
On the book says "The first example uses log10 to compute a signal-to-noise ratio in decibels (assuming that signal_power and noise_power are defined)."
So I assume that the problem might be that I didn't defined 'signal_power', but I don't know how to do it and what to assign to it...
This is the first time that I feel that this book is not holding my hand and I'm already lost. To be honest I don't understand this whole chapter.
By the way, I'm using Python2.7 and Windows XP. I may copy and paste the whole chapter if anyone feels that I should do it.
Python is my first language and I already tried to learn it using "Learn Python the hard way" but got stucked on chapter 16. So I decided to use "Think Python" and then go back to "Learn Python the hard way".

You've figured it out - you have to set signal_power's value before using it. As to what you have to set it to - it's not really a Python related question, but 1 is always a safe choice :) While you are at it, don't forget to define noise_power.

You indeed need to assign a value to both signal_power and noise_power. The author likely left them out because the values are arbitrary. Even when supplied with exact values in a text, you should also play around with the values. After all, there's not much point in having you type anything in if the results on the screen are the same as on the page.
signal_power = 100
noise_power = 17
This particular example defines the mathematical relationship between variables. If it were presented as such, it wouldn't be such a mystery that exact values were left out, as they would be supplied by someone when using the formula. The same holds for the code sample.

The book is for an older version of python apparently. But that is unrelated to your actual question.
Try defining signal_power. For example
signal_power = 0

You can't use a variable without defining/declaring it first. When you say ratio = signal_power / noise_power,
you're trying to access two variables that the interpreter has never heard about.
Before telling the machine what to do with the variables, you have to introduce them to it first.
You do this by declaring them:
signal_power = 123
noise_power = 321
You can define them as any number you want, not only 123 and 321, but you must define them before using them.

Related

What does 'arg1 must be a string, bytes or code object' mean? exec()

an image of the error message for anyone interested
trying to make a simple version of a language translator to a language I made that is similar to one from Outer wilds. but when I try to execute one of the letters for turtle to draw it says as the image above or
arg1 must be a string, bytes or code object
As I am not an amazing coder, I have no clue what that means.
This is the code that I have written and I want to exec()
There is another image containing the code I want to exec()
if anyone can tell me how to solve this thanks! and if you are able to use more simple python and dumb the answer down an little bit so I can understand then that would also be massively helpful!
if you can't dumb it down for me, no problem!
a = T.fd(20)
b = T.fd(20); T.rt(60); T.fd(20)
Neither of those statements does what you think they do. The first statement calls the fd function immediately (presumably moving the turtle forward by 20), and returns None, so None will be stored in a.
The second line also does a forward 20 and stores that return value in b. It then does a right 60 and a forward 20, but nothing about those will be stored in b. Those are completely separate statements.
The bottom line is, if you want to store up a macro to be executed later with exec, then those lines MUST BE STRINGS. You don't have any strings. So, change your code to:
a = "T.fd(20)"
b = "T.fd(20); T.rt(60); T.fd(20)"
...etc...
Then it will do what you want. This is not the BEST way to do this, because exec is a bad habit, but it will do what you want. The better way would be to do something like:
a = "F20"
b = "F20,R60,F20"
and then write a little interpreter to convert those to turtle movements.

Getting a selection in 3ds Max into a list in Python

I am writing in Python, sometimes calling certain aspects of maxscript and I have gotten most of the basics to work. However, I still don't understand FPValues. I don't even understand while looking through the examples and the max help site how to get anything meaningful out of them. For example:
import MaxPlus as MP
import pymxs
MPEval = MP.Core.EvalMAXScript
objectList = []
def addBtnCheck():
select = MPEval('''GetCurrentSelection()''')
objectList.append(select)
print(objectList)
MPEval('''
try (destroyDialog unnamedRollout) catch()
rollout unnamedRollout "Centered" width:262 height:350
(
button 'addBtn' "Add Selection to List" pos:[16,24] width:88 height:38
align:#left
on 'addBtn' pressed do
(
python.Execute "addBtnCheck()"
)
)
''')
MP.Core.EvalMAXScript('''createDialog unnamedRollout''')
(I hope I got the indentation right, pretty new at this)
In the above code I successfully spawned my rollout, and used a button press to call a python function and then I try to put the selection of a group of objects in a variable that I can control through python.
The objectList print gives me this:
[<MaxPlus.FPValue; proxy of <Swig Object of type 'Autodesk::Max::FPValue *' at 0x00000000846E5F00> >]
When used on a selection of two objects. While I would like the object names, their positions, etc!
If anybody can point me in the right direction, or explain FPValues and how to use them like I am an actual five year old, I would be eternally grateful!
Where to start, to me the main issue seems to be the way you're approaching it:
why use MaxPlus at all, that's an low-level SDK wrapper as unpythonic (and incomplete) as it gets
why call maxscript from python for things that can be done in python (getCurrentSelection)
why use maxscript to create UI, you're in python, use pySide
if you can do it in maxscript, why would you do it in python in the first place? Aside from faster math ops, most of the scene operations will be orders of magnitude slower in python. And if you want, you can import and use python modules in maxscript, too.
import MaxPlus as MP
import pymxs
mySel = mp.SelectionManager.Nodes
objectList = []
for each in mySel:
x = each.Name
objectList.append(x)
print objectList
The easiest way I know is with the
my_selection = rt.selection
command...
However, I've found it works a little better for me to throw it into a list() function as well so I can get it as a Python list instead of a MAXscript array. This isn't required but some things get weird when using the default return from rt.selection.
my_selection = list(rt.selection)
Once you have the objects in a list you can just access its attributes by looking up what its called for MAXscript.
for obj in my_selection:
print(obj.name)

Python arrays issue

I tried writing the code for a problem, but the module won't run. It says invalid syntax, but it's not highlighting anything.
The code: http://pastebin.com/cJVNBcYE
The problem: http://pastebin.com/p8E0E0Nj
I don't understand why it's not working.
I have numDealers set as a variable so that info can be entered in the program. The arrays are all defined. I have index=0 and x=1 to set up the loop for the numDealer arrays for sales and commission. I have another array=index section to calculate commissions. And then I have the prints set up.
Why isn't the program working? I don't understand.
Please post code in future, with a full traceback of the error. However:
else print(sales[index]) and print(comm[index])
should be:
else:
print(sales[index]) and print(comm[index])
i.e. you are missing a colon
I'm a bit puzzled by the and. It means that the second print will only be executed if the first fails (unlikely). Did you mean:
else:
print(sales[index])
print(comm[index])
?
By the way, it appears you are not using arrays but lists. The Python standard library includes a module called array https://docs.python.org/3/library/array.html which you do not appear to be using. So don't have a list called array, that collides with the standard library module name, and can cause no end of confusion.

python: Chess moves validation

Does anybody know if there is a free python chess moves validation function available somewhere?
What I need. I have a diagram stored as a string, and move candidate. What I need is to see if move candidate is valid for the diagram.
Would be really interested to see examples, if possible.
The string looks this way:
ememememememememememememememememememembbememwpemememememememwpemembkememememememememememememememememwbembrememememwkemememememem
I understand it may seem stupid, but I find it the easiest to encode position this way. Move candidate for me is just another such position (which happened after next move, can change this behavior I think)
You are missing information e.g. whose turn to move, whether each king has ever moved (means castling is not allowed), the "en passant" status of each pawn. That aside, it would be a very instructive exercise for you to write your own, using a not-very-complicated board representation like the 10x12-element array described here (except that you'd linearise it to a 120-element array).
I know this is a rather old question, but my brother and me were looking for the same thing and we came across this awesome little python module called Chessnut.
Here is an example of its use:
#!/usr/bin/python
from Chessnut import Game
chessgame = Game(fen="rnbq1rk1/ppppp1bp/5np1/5p2/2PP4/2NBPN2/PP3PPP/R1BQK2R b KQ - 4 6")
print chessgame
print chessgame.get_moves()
# apply a move
chessgame.apply_move(chessgame.get_moves()[1])
print chessgame
and here the generated output:
rnbq1rk1/ppppp1bp/5np1/5p2/2PP4/2NBPN2/PP3PPP/R1BQK2R b KQ - 4 6
['b8a6', 'b8c6', 'd8e8', 'f8e8', 'f8f7', 'g8h8', 'g8f7', 'a7a6', 'a7a5', 'b7b6', 'b7b5', 'c7c6', 'c7c5', 'd7d6', 'd7d5', 'e7e6', 'e7e5', 'g7h8', 'g7h6', 'h7h6', 'h7h5', 'f6e8', 'f6d5', 'f6e4', 'f6g4', 'f6h5', 'g6g5', 'f5f4']
r1bq1rk1/ppppp1bp/2n2np1/5p2/2PP4/2NBPN2/PP3PPP/R1BQK2R w KQ - 5 7
Awesome! :)
Thanks cgearhart!
Just use the source of one of the Python Chess programs like PyChess or Python Chess
Specifically, the valid moves for pychess: https://code.google.com/p/pychess/source/browse/lib/pychess/Utils/lutils/validator.py
Wouldn't hurt to look at some of the related answers on the side: Chess move validation library and https://stackoverflow.com/questions/1239913/smallest-chess-playing-program stand out to me.
Though personally I'm in favor of building your own.
Check out ChessBoard.
Unfortunately it has some drawbacks:
it seems to be abandoned, because the bugs reported more than one year ago in the comments don't seem to be fixed
the code is not really PEP-8 compliant
some methods are very ugly and big, not all methods have docstrings
there are no unit tests, so digging into that code might be a challenge (I've already tried it at least twice and failed)
The good thing is that the code is GPL so you can play with it as long as you stick to that license.
I've made a simple chess implementation with move validation here: https://github.com/akulakov/pychess
Validation logic is in each piece's "moves()" method, and you can validate your own move by generating full list of moves and checking if your move is there.

Python c_types .dll functions (pari library)

Alright, so a couple days ago I decided to try and write a primitive wrapper for the PARI library. Ever since then I've been playing with ctypes library in loading the dll and accessing the functions contained using code similar to the following:
from ctypes import *
libcyg=CDLL("<path/cygwin1.dll") #It needs cygwin to be loaded. Not sure why.
pari=CDLL("<path>/libpari-gmp-2.4.dll")
print pari.fibo #fibonacci function
#prints something like "<_FuncPtr object at 0x00BA5828>"
So the functions are there and they can potentially be accessed, but I always receive an access violation no matter what I try. For example:
pari.fibo(5) #access violation
pari.fibo(c_int(5)) #access violation
pari.fibo.argtypes = [c_long] #setting arguments manually
pari.fibo.restype = long #set the return type
pari.fibo(byref(c_int(5))) #access violation reading 0x04 consistently
and any variation on that, including setting argtypes to receive pointers.
The Pari .dll is written in C and the fibonacci function's syntax within the library is GEN fibo(long x).
Could it be the return type that's causing these errors, as it is not a standard int or long but a GEN type, which is unique to the PARI library? Any help would be appreciated. If anyone is able to successfully load the library and use ANY function from within python, please tell; I've been at this for hours now.
EDIT: Seems as though I was simply forgetting to initialize the library. After a quick pari.pari_init(4000000,500000) it stopped erroring. Now my problem lies in the in the fact that it returns a GEN object; which is fine, but whenever I try to reference the address to which it points, it's always 33554435, which I presume is still an address. I'm trying further commands and I'll update if I succeed in getting the correct value of something.
You have two problems here, one give fibo the correct return type and two convert the GEN return type to the value you are looking for.
Poking around the source code a bit, you'll find that GEN is defined as a pointer to a long. Also, at looks like the library provides some converting/printing GENs. I focused in on GENtostr since it would probably be safer for all the pari functions.
import cytpes
pari = ctypes.CDLL("./libpari.so.2.3.5") #I did this under linux
pari.fibo.restype = ctypes.POINTER(ctypes.c_long)
pari.GENtostr.restype = ctypes.POINTER(ctypes.c_char)
pari.pari_init(4000000,500000)
x = pari.fibo(100)
y = pari.GENtostr(x)
ctypes.string_at(y)
Results in:
'354224848179261915075'

Categories

Resources