BearofNH 104 Posting Whiz

Good suggestion rr, but I think that just capitalizes the first word of each line. Instead of readlines() you want readwords(), except that doesn't exist.

I think judicious use of split() is in order, and remember each line will end with \n so you'll want to be sure to delete that so it's not part of the word.

BearofNH 104 Posting Whiz

locals()['a' + str(x)] = x

BearofNH 104 Posting Whiz

An or operation is evaluated left-to-right. In this case, if self.getopt('-v') returns 1 then the user entered -v on the command line, in which case we set self.verbose to True and go on to the next statement. If there was no -v on the command line, we evaluate the second half of the or by checking environment variable VERBOSE. If VERBOSE is some sort of True (not 0, not null-string, not None) then again we set self.verbose. If both cases are some sort of False then so is self.verbose.

What you are seeing here is a funky use of or for control flow instead of a typical boolean operator. It relies on the fact that or is evaluated left-to-right and if operand 1 is True then Python doesn't even look at operand 2.

BearofNH 104 Posting Whiz

The integral rapidly becomes negligible if x is large so i understand you would simply use the limits of -5 to 5 to calculate this integral. However, i'm still unsure of how to do this.

Unless I'm mistaken, I think you can fix this by inserting between line 11 and 12:

# Assume a<b since it's our code
if a >  5: return 0
if a < -5: a = -5 
if b < -5: return 0
if b >  5: b =  5

LFTR: for completeness, you may also want to handle the case of a>b. See if you can do that in one line.

I don't see how your fabs() calls work. They should be math.fabs(), or you can include fabs with exp on the import line.

I notice you don't change inew inside the while loop. That doesn't look right, but maybe it's just the name. E.g., if it represents the "best" integral value it should be called ibest. Using names iold and inew sort of implies you are changing inew each time thru the while loop, and saving the prior value in iold, which isn't happening.

BearofNH 104 Posting Whiz

Interesting ...

E:\>python -m timeit (1,2,3,4)
10000000 loops, best of 3: 0.0173 usec per loop

E:\>python -m timeit [1,2,3,4]
10000000 loops, best of 3: 0.1710 usec per loop

~Same difference, factor of 10 here.

BearofNH 104 Posting Whiz

You didn't tell us what was in the DirViento column.
I sincerely hope you are not trying to convert a temperature value in degrees to a temperature value in radians...

BearofNH 104 Posting Whiz

After a while you get used to using tuples where feasible. For instance, I've just written a program to generate an image with alternating yellow and pink (!) stripes. First lines of code were:

yellow = (244, 244,   0, 255)
pink   = (255, 142, 200, 255)

(for R,G,B,Alpha). Why choose tuples over lists? Well, these are read-only constants and it just seems natural to me to do it this way. Practically speaking, lists would work just as well, but I have an ingrained preference for the more efficient tuples -- where possible.

BearofNH 104 Posting Whiz

WHAT'S THE UPPERCASE SITUATION?

TrustyTony commented: No sense -3
BearofNH 104 Posting Whiz

Of course, NumPy (www.numpy.org) has exactly the routine you need.

BearofNH 104 Posting Whiz

Oops, you're right. VideoCapture is Win32 only. For Linux, break out your favorite search engine. I had no trouble finding the command:

uvccapture -d /dev/video0 -o outfile.jpg

... although if you want something more Pythonic I suggest opencv. At least TRY the above command. If it works then you've probably got all the Linux infrastructure you need.

Gribouillis commented: very interesting +14
BearofNH 104 Posting Whiz

Saving a camera snapshot is fairly easy if you download VideoCapture (videocapture.sourceforge.net):

>> from VideoCapture import Device
>> cam = Device()
>> cam.saveSnapshot('Snap.jpg')
BearofNH 104 Posting Whiz

I've done this sort of stuff before. To answer your second question, here's a code sub-snippet:

import copy
import Image
import numpy as np
img  = Image.open('E:\\JCH\\Snap.jpg')
newx = img.size[0]
newy = img.size[1]      # Image is (newx,newy) pixels

imga = np.asarray(img)      # This is the secret; convert img to array
imgc = copy.copy(imga)      # Make a copy, lest you step on toes

# then the value of imgc[y,x] is the pixel [R,G,B] or [R,G,B,A]
# Note the order [y,x] for the pixel at (x,y). You're welcome :-)
BearofNH 104 Posting Whiz

You would want something like this:

for t in range(120,-1,-1):
    minutes = t / 60
    seconds = t % 60
    print "%d:%2d" % (minutes,seconds) # Python v2 only
    time.sleep(1.0)

... but that just prints out the time left. If you're supposed to put the time in a separate window, well, use the above as a start and replace the print with code to write to the window.

BearofNH 104 Posting Whiz

You need to add colons in your 'if' statements.

'if difficulty == easy:'
etc.

Gribouillis commented: good help +14
BearofNH 104 Posting Whiz

I have no idea what to do.

The underlying calculations are pretty simple but I myself am confused about what the other stuff means. You almost have to RTTM (Read The Teacher's Mind). For example:

... For your demo, calculate the GPA to 2 decimal places for these two course combinations: ...

Now does that mean you are supposed to use Python's Decimal module here? I rather doubt it, I think teacher wants you to print out the GPA to 2 decimal places. But you never can tell -- if you've been studying Decimal then maybe so.

Your program will have a while loop to calculate multiple GPAs and a while loop to collect individual grades (i.e. a nested while loop).

Does this mean you are supposed to hand-enter the raw data every time you run the program? What a pain that would be!

Personally I would store the data in the program, unless I had good reason to believe that was wrong. One possibility is a dictionary, viz:

all_grades = [   \
{'A':5, 'B':4, 'C':3, 'Case':'First'},   \
{'A':6, 'B':6, 'C':4, 'Case':'Second'}  ]

This may not be the best approach as there are other ways to go, e.g., named tuples, but dictionaries are probably learned earlier in the course.

Then one while loop would iterate over all_grades, processing them one dictionary at a time. It's the processing part that has the inner while loop. Frankly I'd use for loops, not while loops, …

BearofNH 104 Posting Whiz

not_lapped= True """used to test if there was no lapping"""

I don't see how this can work. You should be writing:

not_lapped= True # used to test if there was no lapping

"""this was the best i could come out with but didnt solve the problem"""

You should tell us what kind of output you got. "It didn't work" is not too helpful.

BearofNH 104 Posting Whiz

Wow, posting via Opera (instead of Firefox loaded with addons) seems to work. Is the output approximately what you were looking for? If not, perhaps you could clarify what you were after...

# Please do not use "max" as a variable name. Python lets you do it, 
#  but it's generally a bad idea to overload built-in functions.
#
# I would probably start off with something like this.
# Save the trivial user input stuff for later.

import random
rkmax   = 10000      # Random KEY   max value
rvmax   = 100000     # Random VALUE max value
maxent  = 12         # Number of dictionary entries to create
randkey =   lambda : random.randint(1,rkmax)   # KEY-generation function
randvalue = lambda : random.randint(1,rvmax) # VALUE-generation function
mydict  = {randkey(): randvalue() for i in xrange(maxent)} # Generate the dictionary

print mydict    # Have a look
{5857: 4324, 779: 32587, 8676: 83837, 331: 491, 3090: 64330, 6800: 90950, 6481: 87372, 4018: 68669, 9140: 61600, 665: 40635, 5882: 84652, 9532: 74981}
BearofNH 104 Posting Whiz

I don't know how others are faring here, but every time I try to post something I get an error message complaining my code is improperly formatted. Even if it's all comments! After which I'm often no longer able to type into the editing box.

Something is clearly hosed. Is it possible to disabe the nanny syntax checker, since it's not working? [OK, I think it's not working] Frankly I think it should be replaced with a check option.

[code=Python]

Please do not use "max" as a variable name. Python lets you do it,
but it's generally a bad idea to overload built-in functions.
#
I would probably start off with something like this.
Save the trivial user input stuff for later.

[/code]

BearofNH 104 Posting Whiz

Well, pickle.dump() should have no problem saving a variable, as in pickle.dump(variable,f). Now if pickle doesn't like that it will raise an exception, but I suspect if you just try it will work fine...based on pickle.dumps() working on a test case I just tried.

You will probably find your real problem comes later, when tryng to unpickle. But that's later...

BearofNH 104 Posting Whiz

PMJI, but is the problem one of finding the Taylor series for sin(x+1), instead of using the Taylor series for sin(x)?

Ask Wolfram Alpha for taylor series sin (x+1) and it will tell you roughly:

sin(x+1) = sin(1) + x*cos(1) - 1/2 * x^2 * sin(1) - 1/6 * x^3 * cos(1) + 1/24 * x^4 * sin(1) + ...

The pattern is obvious. What's not clear is if this answers the problem.

BearofNH 104 Posting Whiz

Maybe try something a little simpler. Limit yourself to things inside your house. Make a list of 100 or so items. Then figure out which questions lead to which objects. If every question has a 'y' or 'n' response, what you want is a sequence of y and n results that uniquely identify each object. Make up a dictionary of "Known Responses", keyed by the answer history (the previous responses). Here's a really simple example:

resp = {"",":Is it bigger than a breadbox", # First question, since no history
"y":"Can it be moved", # If bigger than a breadbox ...
"n":"Is it something normally kept in the kitchen", # Not big. Kitchen?
"ny":"Is it some kind of appliance", # Kitchen ... Appliance?
"nyy":"Is it the toaster", # Appliance. Toaster?
"nyn":"Is it a utensil of some sort", # Not appliance. Utensil?
... etc.)

So when the user answers y or n, you tack that on to your answer history and ask question resp[history]. The actual code is a pretty small loop since everything is encoded in the resp[] dictionary. Usually it is better to have "data-driven" programs like this, instead of exploding code.

You'll need to figure out when to stop, and how to handle sequences of answers not covered by the dictionary, but neither is that difficult.

If somebody comes up with an answer you didn't prepare for (say, a pencil) you'll want to ask them to name the item and save that away in a data …

BearofNH 104 Posting Whiz

Very nice.

Sadly, matplotlib doesn't have native support for ellipses, at least not that I'm aware of. I suppose you can search for the right keywords, but it may be a bit harder than what you've got so far.

If you include (say) pylab.savefig("MyFile") # Creates MyFile.png just before the pylab.show() line, matplotlib will save your plot as a .png file. I don't think any other formats are available, but there are a number of general utilities to convert file formats.

BearofNH 104 Posting Whiz

I checked out matplotlib, which is a bit complicated for me.

Hey, the first time is always complicated but in reality matplotlib is fairly easy to use. The problem is picking what to use. Herewith an example more or less like the chart you want, in under 50 lines of code.

Of course, you will need to calculate where to plot the rectangles but you should be able to riff off this. Just remember that axhspan() takes your axis units (20->0 in this case) for the Y-values but internal units (always 0->1) for the X-values, and you'll be OK.

import matplotlib
import pylab

if __name__ == '__main__':
    pylab.rcParams['figure.figsize']       = [12.0, 7.0]
    pylab.rcParams['figure.subplot.left']  = 0.12 # Left margin
    pylab.rcParams['figure.subplot.right'] = 1.0-0.08 # Right margin

    # Axes range from 0 to 1 for x-axis (simplifying calls to .axhspan()) and 
    # 20 down to 0 for Y-values because that's convenient for this example

    ax = [0, 1,   20, 0] # [xlo, xhi,   ylo, yhi]

    # First sentence:

    # Red rectangle for the full sentence ... from y=1 to y=2, all the way across

    matplotlib.pyplot.axhspan(1, 2, xmin=0, xmax=1, ec='k', fc='r')
    pylab.text(-0.12, 1.7, "Sentences")

    # Black rectangle for the caps

    matplotlib.pyplot.axhspan(3, 4, xmin=0.12, xmax=0.14, ec='k', fc='k')
    matplotlib.pyplot.axhspan(3, 4, xmin=0.16, xmax=0.19, ec='k', fc='k')
    matplotlib.pyplot.axhspan(3, 4, xmin=0.42, xmax=0.45, ec='k', fc='k')
    pylab.text(-0.12, 3.7, "Capital words")

    matplotlib.pyplot.axhspan(5, 6, xmin=0.13, xmax=0.14, ec='k', fc='#3355CC')
    matplotlib.pyplot.axhspan(5, 6, xmin=0.18, xmax=0.19, ec='k', fc='#3355CC')
    matplotlib.pyplot.axhspan(5, 6, xmin=0.40, xmax=0.41, ec='k', fc='#3355CC')
    matplotlib.pyplot.axhspan(5, 6, xmin=0.64, xmax=0.65, ec='k', fc='#3355CC')
    matplotlib.pyplot.axhspan(5, 6, xmin=0.77, xmax=0.78, ec='k', fc='#3355CC')
TrustyTony commented: Nice code to get to know this unknown to me module +1
BearofNH 104 Posting Whiz

elif 2 <= self.rank <= 10:
self.rank = str(self.rank)
self.value = self.rank

In LINE 20 you set self.rank to a string, then assigned that same string to self.value . Hence the error. You really are trying to add a string to an integer.

Incidentally, I suggest avoiding the use of sum as a variable name. It's also the name of a built-in function, but you won't be able to call sum() if you store a value therein.

vegaseat commented: good observation! +10
BearofNH 104 Posting Whiz

Reasonable people of good will can disagree on such matters, but it is pretty well recognized that parameters and return values are superior to global variables. I'd take out the global sock and pass the socket as a parameter as ff:

def bt_send_data1(sock): # Add the "sock" for all 4 send routines
    sock.send("1")
[...]

# Replace the standalone
bt_connect()
# with
bt_socket = bt_connect()
# When bt_connect() returns "sock", that value gets assigned to "bt_socket" here.
# You could call it "sock" instead of bt_socket, but let's not so as to
# demonstrate return value usage and (later) parameter usage.



# Why are there 4 calls in a row here? Shouldn't just one of them be executed depending on the user's choice? But let's leave that for later.
bt_send_data1(bt_socket)  # Pass in the socket to callee
bt_send_data2(bt_socket)
bt_send_data3(bt_socket)
bt_send_data4(bt_socket)

So the body of routine bt_send_data1() has its own variable called sock that takes on the value of bt_socket in the mainline, which itself came from the return sock in bt_connect(). You may not believe it, but this is actually better than having a single global variable sock. For example, you might have cause to connect to two or more bt devices. You could connect to the first device and call it bt_socket_1 and, while still connected to the first device, also connect to the second device and call that (different) socket bt_socket_2, or maybe use names like headset and microphone, both bt sockets returned from bt_connect(). Something like this:

BearofNH 104 Posting Whiz

You'd put the bt_connect() before you put up the app menu, so the user first sees a list of bt devices and chooses one. You connect to that, carefully checking that the connect() succeeded. I think it's best if bt_connect() were rewritten to separate the functions of (1) selecting a target and (2) connecting to the target, but that can wait until other problems are solved.

Then you enter a loop displaying the app menu and accepting commands. For function commands (everything except quit) you'd call the corresponding send_data() routine, which would send the command and then do a receive() appropriate to the command. You either need two different receive()s (just like you have four different send()s) or one receive() with a parameter that tells it what to look for. Theoreticians can tell you which option is preferable but right now just do the one that feels right to you.

Also take note of my comment on using exit_key_handler instead of exit_key_handler()

BearofNH 104 Posting Whiz

return count is indented too far.

BearofNH 104 Posting Whiz

I noticed you have defined receive() twice. This means the first definition is discarded and only the second one counts.

Do you need receive() at all? It depends on what you're doing. Normally you'd do a connect() then exchange many (possibly very many) messages via send() / recv(), then close() when all done, say upon exit. Your code doesn't work that way. It does a connect() for every send() and receive(). But it only does a close() when exiting. So if someone does say 100 LED-on/LED-off commands you're going to create a new socket for each of those commands, but not close() any of them except for the last. Do this enough times and one side or the other will run out of space for open (i.e., not close()d) connections. This is not right, there should be a close() for every connect().

You might get away with changing the calls to receive() to calls to close(), dropping the close() inside the quit(). That would make the sequence connect() / send() / close() which would discard any response data. Problem there is, since you're not doing a recv() you're not waiting for a response, so the close() might actually be invoked before the network has had a chance to finish the send(), so potentially an immediate close() might cancel the send()...it all depends on when your particular O/S decides the send() is done and returns control to you. A hacky way around this would be connect() / send() / …

BearofNH 104 Posting Whiz

... you should not use random as your variable name. Pick something different, say rand or rnum or whatever. Otherwise you overwrite your imported random module the first time you assign something to variable random. Things will work the first time and fail subsequently.

BearofNH 104 Posting Whiz

I don't know the answer but suggest two things to consider:

  1. Sending all four lines in one write() may burst data faster than the receiver can actually handle.
  2. You might check on the newlines in the string sent by the write(), they could be different from what you type manually to HyperTerm.

My first guess would be [1] based on the varying error pattern.