Generators are essentially dynamic sequences, making their official debut in Python 2.5.
That got me to thinking: can we make a circular list with them?
Why yes, we can...
Generators are essentially dynamic sequences, making their official debut in Python 2.5.
That got me to thinking: can we make a circular list with them?
Why yes, we can...
Inspired by Bumsfeld's color tester, and wanting to give my students some practice at interpreting color strings, I wrote a little Tkinter program that asks the user to chose one of six buttons whose color most closely matches the color string printed at top.
Comments welcome, and does anyone know of a named solid bitmap?
Jeff
Edit: rolled global into MyFrame class
Thanks for gently pointing out that I had an error in the x() method. :)
The test routine is not, unfortunately, a 'few lines' -- I'm finding that I can't do short unit tests. I'll try to check out the unittest module.
Thanks,
Jeff
So I needed a way to represent a line in Python. My first stab was to create a function dynamically. But classes are so much ... classier, so here's a simple implementation of a line object, with plenty of room for additional methods.
The line is created as
l = Line(slope,intercept) *or*
l = Line(slope,Q) *or*
l = Line(P,Q)
where P and Q are (x,y) pairs.
I like the middle one the best, in terms of flexibility and conceptual cleanness. The function version is nice, except that it would require a different function for each nested loop (unless your loops were similar enough that you could polymorph them...). The flag version is fastest, I would guess, but it's less human-readable. It also requires a check at each level, which would be ugly at 5+ levels of nesting.
OH ... and the middle version works more efficiently with recursion, also.
All opinions expressed here are highly subjective...
BTW, are there any other legitmate uses of 'goto'? I've only ever heard the "break out of nested loops" and "recover from errors in nested functions" cited.
Do you have a link for this particular algorithm?
Thanks,
Jeff
I think I understand what you're trying to do. It still can be done with instances like so:
class Cube(object):
def __init__(self, x, y):
self.x = x
self.y = y
self.image = pygame.image.load("Data\Cube_one.bmp")
...
def isColliding(self, player):
rect = self.get_rect()
player_rect = player.get_rect()
if ... # inequalities go here
That gives the idea. Basically what's happening is that each cube knows about itself where it is, so it can check itself for collision.
Also, unless there's a good reason not to, you should check out the Pygame Sprite class, which has collision detection built in.
Jeff
The phrase
for line in data:
...
assigns the variable "line" to each interated string terminated by '\n' within the data.
So if you inserted the statement
data = open ("files/" + data + ".txt", 'r')
for line in data:
print line
line = line[34:38]
file_list = line.readline()
you would get
01/27/2009,0840,80.13,80.17,79.81,79.99,16462,29701
AttributeError: 'Str' has no attribute 'readline'
Now the problem becomes clear: in Line 4, you're taking the string you already have, and then trying to readline it from the file again!
Just kill the readline() and print the results of the slice in line 3, and you'll be good.
Jeff
Hm. The only thing I can think of is that your LocalFileName is not valid ASCII.
Jeff
Search this forum for Vega's decimal to binary converter. Your code is reading the data correctly; now you just have to find the right way to display it.
Jeff
Interesting concept. Two potential problems:
(1) What if the images are not all the same size?
(2) How does the code decide what framerate to use?
Jeff
Mark as solved and give Bear of NH props. :)
Jeff
The standard way of repeating code is to use a while loop. There are two styles: the 'test first' and 'test last' methods.
# a test-first loop: set the sentinel and repeat until sentinel is false
repeat = True
while repeat:
print "You lose!"
if raw_input("Play again? (y/n) ") == "n":
repeat = False
# a test-last method: repeat until the test fails. This method makes more sense to me but is frowned on by some purists.
while True:
print "You lose!"
if raw_input("Play again? (y/n) ") == "n":
break
Jeff
OK, that makes sense. Here's what will happen:
In lines 9-10 of your current code, you read in an image from a file.
Instead, you will call your camera's "take a picture" method. It will return either (a) a bitmap, or (b) some kind of proprietary image, as an object.
If (a) then proceed directly to displaying the bitmap as in line 11.
If (b) then you'll need to poke around in the camera's module to find out how to convert the image into a bitmap. Then display as in line 11.
Hope it helps,
Jeff
That's cool. I didn't even know there was a PySerial module.
First, the error messages are confusing. Are those the result of the print motor.read(motor.InWaiting()) command?
Second, just to back up Bear's point:
Since the motor is known good, and since hyperterminal works, it therefore follows that PySerial isn't sending the data in the same manner as hyperterminal.
One possibility ("burst data") is that the motor needs to pause, even if a millisecond, after each line. In that case, manually entering into hyperterminal might provide that slight pause that the automated process in Python does not.
The solution there would be to read the motor after each line to make sure that you are getting a 'ready' status.
The other possibility is that the sequence of characters is different. A common culprit is the newline. On some systems, return is 0x0A ('\n'). On others, return is TWO characters 0x0A 0x0D ('\n\r')
So it could be that PySerial is sending a different kind of newline from hyperterminal.
Without knowing more about your motor (and PySerial), I couldn't say how to test for those problems exactly, but those are the problems I would test for.
Jeff
Well, here's the basic idea. You have a button in your GUI. The button has a callback function. That function can then call your program. Here's a typical instance:
def mycallback(self, event):
os.system("C:\Program Files\Myprog.exe")
Jeff
Hi, I found a code that displays multiple images but you have to supply its filename first before it can access it. Is there a way to display an image as soon as it is captured by the camera? The GUI that I am creating is going to be interfaced with a camera and I need to display the captured images as they arrive. Can someone please lend me a hand here? Big thanks and looking forward to learn from you. :)
Your question is a little confusing. When I display an image, I make it into a wx.Image() object or a wx.Bitmap() object. It doesn't really matter whether it came from a file or not.
So ... can you post your code to help clarify what the issue is?
Jeff
P.S. Also, check out the docs for the Image and Bitmap classes:
http://docs.wxwidgets.org/stable/wx_wximage.html#wximage
http://docs.wxwidgets.org/stable/wx_wxbitmap.html#wxbitmap
ermm... that should be tkFileDialog. Sorry. (and who disabled the "Edit" feature?!)
Jeff
Lists of lists work fine as container arrays (not mathematical arrays, but you don't seem to be wanting that). So:
nlat=10
mylist = []
for x in range(0,nlat):
tmp = []
for y in range(0,nlat):
disk=sphere(pos=(x*s,y*s), radius = r, color=(0,1,9))
tmp.append(disk)
mylist.append(tmp)
et voila! An array of spheres.
Jeff
As well he should :)
Here's what wooee means:
def SD():
b = []
for n in range(r-1):
if r[n] > a:
b.append((r[n] - a)**2)
if r[n] < m:
b.append((a - r[n])**2)
SD = (float(b)/r)**0.5 #float because the data includes decimal values
return SD
print "The standard deviation is", SD
Note that "SD" is a function. So when you print the function, you get, quite literally, the function: <function SD" at 0x020EB630>
Try this with a simpler example:
def MyFunc():
pass
print MyFunc
What you actually want to print is the result of calling the function. So that needs this:
def SD(...):
....
print SD()
The extra () mean "call the function and accept the result."
Mathematical aside: Your test 'if r[n] < a' is superfluous. For any values of r[n] and a, it will be true that
(r[n] - a) ** 2 == (a - r[n]) ** 2
which is why standard deviations are calculated using square residues in the first place (so that under- and over-values don't cancel each other out).
Jeff
For the file choosing, you should check out the filedialog module. Google for references on it.
For the endless looping, take a look at the code and think about how to remove the element of choice from it.
Jeff
You mean the center of mass?
Well, do it like the physicists do: Sum(moments) / Sum(masses):
>>> def findCOM(grid):
Mx = 0
My = 0
mass = 0
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j]:
Mx += j
My += i
mass += 1
COM = (float(Mx)/mass , float(My)/mass)
return COM
>>> grid = [[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 0 ,0, 0]]
>>> findCOM(grid)
(1.875, 2.0)
>>>
Jeff
Hm. What happens if you send it an object of the required class? And what is the required class, anyways?
Jeff
Pass in the appropriate "Nothing" value for that type.
So if the COM function header is
Private Function MyFunc(text as String) as String
then you would pass in
MyFunc("") ' "" is the equivalent to Nothing
But see also:
http://mail.python.org/pipermail/python-list/1999-April/000902.html
http://osdir.com/ml/python.ctypes/2003-06/msg00055.html
Jeff
Well, if you think about it, the problem does not have a unique solution.
x = Class()
x.name = 'the_name'
x.value = 10
y = Class()
y.name = 'the_name'
y.value = 20
So now ... do you want x.value or y.value?
Maybe both?
Jeff
It looks like Nothing is used to declare a variable for use at a later time.
Almost. In dynamically typed languages like Python, assigning a value and declaring the type occur in the same motion:
MyList = [1,2,3]
means
"Declare MyList as a reference to a list, and assign it to the list [1,2,3]."
But in statically typed languages -- C, VisualBasic -- variables have to be declared at compile time before being assigned. Thus:
Dim a as Integer 'declares a
a = Nothing 'assigns a
So modify your statement slightly ... "It looks like Nothing is used to assign values for use at a later time."
But put that way, it becomes clear that, even in Python, unassigned variables could throw errors later down in the code. For example:
Dim a as Integer
a = Nothing
GetPossibleNewValue(a) 'might change a, might not
print a
If the assignment is skipped in the corresponding Python code, an error will be thrown at print a.
Jeff
Well, start with a thought. How can you explain the process to someone else in English? Make it general: given data in rows of n, how would you rewrite it in rows of m?
Once you have that explanation in English, it will lead to the thought that gives the code.
Jeff
I really like the text we used for my high-school level class: Python Programming for the Absolute Beginner. Two caveats -- it's game-oriented, and it doesn't use Python 3.0.
That said, it contains clear explanations and models reasonably good programming practices.
Jeff
My question is what is the order in which instantiations and allocations occur in python when instantiating a class? The author's code below is under the assumption that 'DefaultDomainName' will exist when an instance of the class is created (e.g. __init__() is called), but this does not seem to be the case, at least in my testing in python 2.5 on OS X.
This I can explain, but the boto framework is completely unknown to me.
When a new object is created, __new__() is called. I don't know all the details, but it seems from the documentation that __new__() allocates the memory for the object and initializes pointers to the methods. Then, __init__() is called. If an object does not define code for __init__(), then a stub __init__() is created for it which (seems to) contains the code pass.
If the DefaultDomainName were not set in __init__(), then the code above would have thrown an error -- that is, a variable that is not set is not the same as None.
So it seems that the __init__() method really does set the DefaultDomainName to None. You can confirm this by inspecting the code and looking in the __init__ method.
Then the next question would be, "Why did the author write the code in this way?" Clearly, None was intended to be a signal value, so it would be wise to understand what the signal means and treat it accordingly. Else, you run the risk of breaking …
Yeah, that's interesting ... None in Python is a special type, whereas Nothing is equivalent to NULL of whatever datatype one is working with: Dim b as Integer: b = Nothing -- this makes b a Nothing value of type Integer (as opposed to a None type).
In short, Nothing is a value whereas None is a type.
What you may have to do is sacrifice the flexibility of "Nothing" and manually set the variables to the corresponding value. So for example:
Dim a as Integer
a = Nothing
is equivalent to
Dim a as Integer
a = 0
It's not ideal; perhaps there's a way for your Python script to detect the type of the variable and set it to the corresponding Nothing value using a dictionary:
NothingTypes = {"Integer": 0, "Boolean": False, ...}
...
MyValue = NothingTypes[TypeToString(MyVar)]
That's somewhat pseudo-cody, but I hope it's clear.
Jeff
I'm confused. Here's the help on shutil.copy:
>>> help(shutil.copy)
Help on function copy in module shutil:copy(src, dst)
Copy data and mode bits ("cp src dst").The destination may be a directory.
Can you be specific with your question?
Thanks,
Jeff
One more thought: lists of lists in Python function reasonably well as arrays:
mylist = [[1,2,3],[4,5,6],[7,8,9]]
print mylist[0][2]
3
I say "reasonably well" -- there aren't any linear algebra methods that can be used on lists of lists (like det(), inv(), or eigenvalues()), but the LinearAlgebra module covers that.
Jeff
I fully agree, Vega. The coding purists frown on while True loops, but I find them really useful. Glad to know someone else out there shares my guilty secret. :lol:
Jeff
Without contradicting the posters above, I would add that Python makes OOP really easy. And in the end, coding with objects is easier to wrap one's mind around than coding without objects -- once OOP is learned, of course.
So ... yes, you could ... but you probably shouldn't. ;)
Jeff
>>> class Thing(object):
pass
>>> t = Thing()
>>> dir(t)
['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__']
>>> print t.__class__
<class '__main__.Thing'>
>>> print t.__module__
__main__
Jeff
Just to add to scru's point: Being able to re-use code is an extremely important but sometimes overlooked feature of programming. Its main value is not saving time, but eliminating bugs.
That is, if the code for CD works provably correctly (or testably correct even), then a DVD class built on top of it will be solid so long as DVD doesn't muck with the internals.
Jeff
Can't speak to IPython, but a simple file copy will solve the first problem.
Two thoughts.
(1) You're writing code as if it were C or Pascal. A better way is to write a class:
class Bird(object):
def __init__(self, nID=0, ter=0, year=0, fled=0, age=0.0):
self.nID = nID
self.ter = ter
self.year = year
self.fled = fled
self.age = age
def from_line(self, string):
items = string.strip().split()
if len(items) != 9:
raise ValueError, "Cannot parse line: %s" % string
else:
self.nID = items[0]
self.ter = items[2]
self.year = items[3]
self.fled = items[9]
self.age = items[7]
... # etc.
The point is that you can then test your class and forget about its operation.
And, you won't need numpy arrays anymore, since you can just maintain a list of objects.
Second thought:
If you do create the Bird class, then you can create a __str__() method for it that will properly format the way you want. Like this:
...
def __str__(self):
s = "nID: %d ter: %d year: %d fled: %d age: %0.1f" % (self.nID, self.ter, self.year, self.fled, self.age)
return s
and then your main code would go:
for each in CLrcw:
if each.age > 0:
outfile.writelines(str(each))
Hope that helps,
Jeff
Yes, I actually do the latter.
ACTUALLY, what I often do is this:
class MyClass(object):
....
@staticmethod
def test():
## Unit testing goes here
if __name__ == "__main__":
MyClass.test()
and then the test method is responsible for spitting out diagnostics. But in the absence of full unit testing, I put the main code after the if __name__ clause.
I should note also that my main code is almost always short, because the heavy lifting is done by functions and class methods. The only reason, then, to not have a main() function is so that I can have one or more named instances of objects whose state can be examined if needed.
Jeff
The style is good too. In general, functions should do one thing and do it well. Yours pass that criterion.
Although ... I don't usually have a "main()" for the simple reason that I like to examine variables if the program crashes, and stuffing the main code into main() makes that more difficult.
Good work!
Jeff
I'm not getting your results:
class test(object):
a = 55
def dispmenu(self): print self.a
>>>
>>> instance = test()
>>>
>>> instance.dispmenu()
55
>>> action1 = instance.dispmenu()
55
>>> print action1
None
Here's what I think you want to do:
>>> action1 = instance.dispmenu
>>> action1()
55
So the way to read this is, action1 is assigned to instance.dispmenu, and then the () force calling action1.
Does that help?
Jeff
In Python < 3.0, print is a keyword and as such cannot be deleted or clobbered, as far as I can tell. So for example, it's not a part of __builtins__ because it isn't a function.
Interesting that on this point, Python is bowing to the wisdom of C.
Jeff
Now I want to take it a step further and make myself a small GUI library for python 3. What I'm interested in is how I could go about designing the object hierarchy among other things.
As a community of python users, this would be an ideal place to start asking questions. I welcome you to sound your ideas and suggestions!
First of all, cool project!
Second: are you nuts?!! :) Seriously, though ... it will take a team and a lot of effort.
Third: You might start by contacting Fred Lundh and Robin Dunn and asking them what did and did not work well with Tkinter and wxPython, respectively. And you could include also glade and gtk, though I haven't used those. And pygame.
My own thoughts:
(1) The learning curve for wxPython was rather steep. I feel comfortable now putting together apps, but it was not natural. (Ditto for the C API -- too many magic methods). The top priorities for a graphic toolkit, I would say, are stability, performance, and codability -- meaning clarity of overall structure, so that a coder can quickly and accurately write what (s)he wants.
(2) Tkinter had a shorter learning curve, but it suffers from a fatal flaw: it's not (to my knowledge) customizable. If possible, the clear overall structure I mentioned in (1) should float on top of a fully customizable layer so that users can get down to the metal if they so desire.
…
The newline character is '\n' (including the quotes), not \n\.
Hope it helps,
Jeff
If you have two genuinely separate programs, then they will have to signal each other. This would likely be accomplished with a pipe, and you'll need some kind of signal handling.
How badly do you want to pursue this solution? What are you trying to accomplish?
Jeff
This appears to work:
>>> im = Image.open("24bit test.bmp")
>>> im2 = im.convert("P")
>>> im2.save("256bit test.bmp")
The bit-depth of the output file is 8, so I assume that's what you were after?
Jeff
I would probably take a completely different approach:
class MyFloat(float):
def __new__(self, name, value):
return float.__new__(self, value)
def __init__(self, name, value):
self._name = name
name = property(lambda self: self._name)
x=MyFloat("name", 1.5)
print x
print x._name
print x.name
The call to __new__ is necessary when subclassing immutable types like float -- the call order is __new__, followed by __init__ on initialization, and all of the arguments are passed to both.
Jeff
The function "unpack" is not a built-in function. Does your code import some module at the top?
Jeff
Or this:
try:
val = int(item)
if val > 0:
do stuff for positive numbers
elif val < 0:
do stuff for negative numbers
else: # don't omit zero!
do stuff for zero
except:
pass
If you want to allow floating point numbers, you can change the int() to float()
Jeff
No, I don't.