Re: [Tutor] Problem with data storage

2004-12-02 Thread Jacob S.
Hello,

The way I do it is as follows.

def open():
a = open('myfile.txt','r')
di = a.read()
a.close()
di = eval(di)
return di

def save(di):
a = open('myfile.txt','w')
a.write(str(di))
a.close()

def dosomethingwithdi(di):
'''You can put whatever you want in here
for example...'''
open()
print di
di['key'] = 'value'
save(di)
print 'Done'

HTH,
Jacob Schmidt


> Hello,
> 
> I'm building an app that needs to get input from the user and compare
> it to data that should be in some kind of data storage file.
> The problem is that I dont know what data storage file/module to use...
> I need it to be easy for the user to edit by himself (I don't want to
> make an UI to edit the file), organized as list of pairs (or a table)
> and multy platform (if no such thing then WIN only).
> 
> Thanks!!
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Pythonw.exe doesn't work in the python2.4 distribution?

2004-12-02 Thread Jacob S.
> > execute the scripts using python24. However, the "Edit with IDLE"
> command in
> > the shorcut menu (right-click pull down menu) no longer worked. So I
> went to
> > the registry (I know the risks involved)
>
> BUt entirely unnecesary here!
> The way to check/fix the context(right-click) menu options is via
> Explorer. Its much easier and much safer.
>
> Go to Tools->Folder Optoions->File Types
>
> Select the file type you areinterested inn- .PYW in this case
>
> Hit the Change button, from the dialog you can select the
> associated executable. Using the Advanced button you can
> edit the existing entries, changing startup flags etc.
>
> You can also add new contrext actions there too - such as
> Edit with SCite or whatever.

Thank you! I knew there was a way I did it last time, I just couldn't
remember!
for i in range(100):
print 'Thank you'

> > "C:\python23\pythonw.exe" "C:\python24\lib\idlelib\idle.pyw -n -e
> %1"
> >
> > A few things...
> >
> > 1) Can anyone explain why pythonw.exe doesn't do what it is supposed
> to do
> > in python24?
>
> That I can't help with not having loaded 2.4 yet.
>
> > 3) Can anyone off-hand tell me what the arguments -n and -e mean in
> the
> > above string? Does anybody know of a list of these? (Not urgent, if
> no one
> > knows, I won't bother extensively searching for one.)
>
> According to the usage message in PyShell.py
>
> -n  => start with no subprocess
>
> -e file => edit 

That makes perfect sense. Thanks!
Jacob Schmidt

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] programming newbie question

2004-12-02 Thread Jacob S.
> I am fairly new to programming and I have started to learn programming
> then stopped out of frustration several times in the past.  I guess my
> frustration stems from not being able to understand when to use certain
> aspects of programming such as functions or classes.

Use functions when you will execute a certain code block many, many times
during a script. Or if you want to make a code block simpler and more
generic. For example...

def rfill(stri,length,sep=" "):  # stri is short for string, and sep
(seperator) is defaulted to a space
stri = str(stri) # This is to help make sure that what the user gives us
is a string
if stri < length:
stri = stri + sep*(length-len(stri)) # This fills the string to the
length with seperators
return stri # This returns the string so we can assign it, print it etc.

Usage is as follows:

a = 'The'
b = 'Many'
c = 'Two'
e = 'Forty'
f = [a,b,c,e]
for i in range(4):
print "%s%d" % (rfill(f[i],15),i)

yields

The0
Many   1
Two2
Forty  3

This is just one example. You can use functions over and over from anywhere
in your script.
Classes are just like defining new types. You have the usual types like
dictionary, list, tuple, integer, float, etc.  but with classes you can
define your own. Methods are just attributes of classes, or so I understand.
For example...

class MyClass:
def __init__(self,pos=[0,1,0]):
self.pos = pos
def printpos(self):
print self.pos

Which in turn can be used like this.

>>> a = MyClass()  ## pos defaults to [0,1,0] so I don't have to specify
explicitly
>>> print a.pos
[1,0,1]
>>> a.pos = [1,2,1]
>>> a.printpos()
[1,2,1]
>>>

The most interesting use of classes that I have seen is the VPython package
where they define new classes (again I think of them as types) as shapes
with attributes (or methods - like L.append() which refers to appending to
lists) like position, color, radius, axis, etc.
But I digress.

HTH,
Jacob Schmidt

> I have read enough
> books and tutorials to know the syntax of python and I understand most
> everything related to the concepts of programming, but I have never been
> able to put it all together and learn how and when to use specific
> features.  Can anyone suggest a method or some reading to help out with
> this?  I also struggle with finding projects to work on does anyone know
> of projects that a novice could contribute to?
>
>
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
>

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] new function and a 3 line program not working

2004-12-02 Thread Jacob S.
I thought that the '.py ' in this import statement would make the
interpreter think that newline was a package and therefore try to recognize
py as a module in the newline package.

from newline.py import newline

Perhaps you said this to help explain what's going on?
Jacob Schmidt

>
> If so that is the problem. You cannot call newLine() in a separate
> file from the one where you defined it - python doesn't know about it.
> You need to *import* the file where you defined the function, like
> this:
>
> from newline.py import newline
>
> Ah, but reading further in your post and looking at the tutorial text
> you posted, the author does NOT say create a new file. Rather
> he (she?) says (or implies) to just keep on typing the program
> after the function definition in the same file. That way Python
> can read the file including the newline() definition.
>
> HTH,
>
> Alan G.
>
>
> ==
>
> The first couple of functions we are going to write have no
> parameters, so the syntax looks like this:
>
> def newLine():
> print
>
> This function is named newLine. The empty parentheses indicate that it
> has no parameters. It contains only a single statement, which outputs
> a newline character. (That's what happens when you use a printcommand
> without any arguments.)
>
> The syntax for calling the new function is the same as the syntax for
> built-in functions:
>
> print "First Line."
> newLine()
> print "Second Line."
>
>  definition>
>
>
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
>
>

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] comapring lists

2004-12-02 Thread Jacob S.
If you or anybody else is interested, I've written a script for codes like
kids in junior high use to write notes to each other with... It will cipher
and decipher mixed letters (encryption), turn words inside out (try it and
see), date code (mixed letters that changes with the date), morse code,
piglatin (primitive)...  See for yourself.

import time

lowercase = 'abcdefghijklmnopqrstuvwxyz'
whitespace = '\t\n\x0b\x0c\r '
punctuation = '!"#$%&\'()*+,-./:;<=>[EMAIL PROTECTED]|}~'

print """\
Types of codes are:
mixed letters
insideout
date code
morse ode
piglatin
"""

while 1:
unordo = raw_input('Are we going to decipher or cipher? ')
if unordo == 'quit':
break
type = raw_input('Which type of code would you like? ').lower()
if type == 'mixed letters':
if unordo == 'cipher':
ask = raw_input('Please type the code text using regular
language. ')
returnlist = []
copyofask = ask  ## For use when checking the capitalization
later...
ask = ask.lower()
ref = lowercase
increment = raw_input('What letter would you like "a" paired
with? ')
added = increment
increment = ref.index(increment)
ask = list(ask)
for x in ask:
if x in whitespace or x in punctuation:
returnlist.append(x)
else:
ind = ref.index(x)
ind = ind+increment
while ind >= 26:
ind = ind - 26
returnlist.append(ref[ind])
returnlist.append(added)
inde = 0
for x in copyofask:
if x == x.upper():
returnlist[inde] = returnlist[inde].upper()
inde = inde+1
returnlist = "".join(returnlist)
print
print returnlist
print
if unordo == 'decipher':
ask = raw_input('Please type in the coded message. ')
returnlist = []
copyofask = ask  ## For use when checking the capitalization
later...
ask = ask.lower()
ref = lowercase
ask = list(ask)
del copyofask[-1]
added = ask.pop()
increment = ref.index(added)
for x in ask:
if x in whitespace or x in punctuation:
returnlist.append(x)
else:
ind = ref.index(x)
ind = ind-increment
while ind < 0:
ind = ind+26
returnlist.append(ref[ind])
inde = 0
for x in copyofask:
if x == x.upper():
returnlist[inde] = returnlist[inde].upper()
inde = inde+1
returnlist = "".join(returnlist)
print
print returnlist
print
if type == 'insideout':
if unordo == 'cipher':
returnlist = []
ask = list(raw_input('Please type in the message. '))
while len(ask) > 0:
returnlist.append(ask.pop(0))
ask.reverse()
returnlist.reverse()
returnlist = "".join(returnlist)
print
print returnlist
print
if unordo == 'decipher':
returnlist = []
ask = list(raw_input('Please type in the message. '))
returnlist.append(ask.pop(0))
while len(ask) > 0:
returnlist.append(ask.pop(0))
returnlist.reverse()
returnlist = "".join(returnlist)
print
print returnlist
print
if type == 'date code':
if unordo == 'cipher':
ask = raw_input('Please type in the message. ')
copyofask = ask
returnlist = []
ask = list(ask.lower())
datesmall = raw_input('What is the date you want to use? ')
if datesmall == '':
datesmall = time.strftime('%m%d%y')
dateexpanded = time.strftime('%B %d, %Y')
else:
dateexpanded = datesmall
datesmall = time.strptime(datesmall,'%B %d, %Y')
datesmall = time.strftime('%m %d %y',datesmall).split(" ")
datesmall = [str(int(x)) for x in datesmall]
datesmall = list("".join(datesmall))
datesmall = [int(x) for x in datesmall]
print
print dateexpanded
t = 0
for x in ask:
if x in punctuation or x in whitespace:
returnlist.append(x)
t = t - 1
else:
m = t
while m >= len(datesmall):
m = m - len(datesmall)
start = lowercase.index(x)+datesmall[m]
if start >= 26:

Re: [Tutor] comapring lists

2004-12-05 Thread Jacob S.
Wow! I never thought of using dictionaries to store function objects like
that! The "table-driven" approach is much better than my own! Thanks a lot!

Jacob Schmidt

>
>
> On Thu, 2 Dec 2004, Jacob S. wrote:
>
> > If you or anybody else is interested, I've written a script for codes
like
> > kids in junior high use to write notes to each other with...
>
> Hi Jacob,
>
> Cool!  Do you mind if I make some comments on the code?  If you do mind...
> um... skip this message.  *grin*
>
>
> The main body of the program feels a bit too long: it screams to be broken
> into a few helper functions.  I see that there are two critical variables
> that are used to figure out which part of the program comes next:
>
>
> ###
> unordo = raw_input('Are we going to decipher or cipher? ')
> type = raw_input('Which type of code would you like? ').lower()
>
> if type == 'mixed letters':
> if unordo == 'cipher':
> # ... do mixed letter ciphering
> if unordo == 'decipher':
> # ... do mixed letter deciphering
> if type == 'insideout':
> if unordo == 'cipher':
> # ... do insideout ciphering
> if unordo == 'decipher':
> # ... do mixed letter decipering
> # ... rest of the program follows similar structure
> ###
>
>
>
> In a case like this, we can break the program into separate functions,
> like this:
>
> ###
> def dispatchOnTypeAndUnordo(type, unordo):
> if type == 'mixed letters':
> if unordo == 'cipher':
> mixedLetterCipher()
> if unordo == 'decipher':
> mixedLetterDecipher()
> if type == 'insideout':
> if unordo == 'cipher':
> insideoutCipher()
> if unordo == 'decipher':
> insideoutDecipher()
> # ... rest of the program follows similar structure
> ###
>
> We make each 'body' of the inner "if"'s into their own functions, like
> 'mixedLetterCipher()'.  This restructuring doesn't improve the program's
> performance at all, but it does help readability: the main improvement is
> to make the overall shape of the program all visible at once.
>
>
> This structural change also paves the way for a "table-driven" way to
> implement a decision tree.  Experienced programmers really try to avoid
> code that looks like "if/if/if/if/if..." because that's probably some kind
> of repeating structure that we can take advantage of.
>
>
> The logic on the function dispatchOnTypeAndUnordo() has an internal rhythm
> that we can capture as a data structure.  Here's a dictionary that tries
> to capture the essentials of the beat:
>
> ###
> dispatchTable = { 'mixed letters': (mixedLetterCipher,
> mixedLetterDecipher),
>   'insideout': (insideOutCipher,
> insideOutDecipher),
>## ... rest of the dictionary follows similar structure
> }
> ###
>
> [Note: the values in this dictionary --- the function names --- are
> intentionally without parentheses.  We don't want to "call" the functions
> just yet, but just want to store them off.]
>
>
> If we have a dispatch table like this, then the dispatchOnTypeandUnordo()
> magically dissolves:
>
> ###
> def dispatchOnTypeAndUnordo(type, unordo):
> (cipherFunction, decipherFunction) = dispatchTable[type]
> if unordo == 'cipher':
> cipherFunction()
> elif unordo == 'decipher':
> decipherFunction()
> ###
>
>
> This is a "table-driven" or "data-driven" approach.  The choices available
> to the program have been migrated away from the explicit, separate 'if'
> statements, and now really live as part of the 'dispatchTable' dictionary.
>
>
> Does this make sense so far?  Please feel free to ask questions.
>
>
>

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Accuracy of time.sleep()

2004-12-05 Thread Jacob S.
You know, since time.sleep() builds up errors, this is what I do to keep it
purely pythonic... (not tested)

from time import gmtime

alarmhr = 8
alarmmin = 5
alarmsec = 0

while 1:
t = gmtime()
hour = t[3]
min = t[4]
sec = t[5]
if (alarmhr,alarmmin,alarmsec) == (hour,min,sec):
print "It is 8:05 AM. Please do whatever you are supposed to at this
time.
raw_input()
break

> OK I may be pushing it,  ;-)
>
> I need a script to sleep from any point to 8:05AM when in needs to
> re-start.
>
> So I calculate the number of seconds with the following 
>
>
>
>
> def secs_till_805():
> # Returns the number of seconds till 8:05AM
>
> secs_5min=5*60
> secs_24hr=24*60*60
> secs_8hr=(8*60*60)+secs_5min
> secs_8hr_24hr=secs_24hr-secs_8hr
>
> hours=int(strftime('%H'))
> mins=int(strftime('%M'))
> secs=int(strftime('%S'))
>
> sec_left=secs_24hr-((hours*60*60)+(mins*60)+secs)
>
> # If we are before 8:05, then ...
> if sec_left>secs_8hr_24hr:
> return sec_left-secs_8hr_24hr
>
> # If we are after 8:05, then ...
> return sec_left+secs_8hr
>
>
>
> Then I ...
>
> sleep(secs_till_805())
>
> I expected the script to re-start 2-3 seconds after 8:05, python
> reloading after a long sleep etc, what I get is the script restarting at
> 08:04.55, earlier ???
>
> OK this is not a world stopping problem, more of a curiosity.
>
> Any suggestions
>
> Dave
>
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
>
>

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Address book sort of

2004-12-05 Thread Jacob S.
I did something like this about three or four months ago...
This is what I did. Notice the use of the built-in str() and eval()
functions to write and receive data to and from Telephone.cfg...

from __future__ import division
tel = {}
try:
file = open('Telephone.cfg', 'r')
except:
file = open('Telephone.cfg','w')
file.close()
file = open('Telephone.cfg','r')
try:
tel = eval(file.read())
a = 0
except:
a = 1
print "No entries on file."
pass
print """\
Commands are:
add
get
save
delete
quit
all is a wildcard
"""

while 1:
ask = raw_input('Tell me what you wish to do. ')
if ask == "quit":
break
ask = ask.split(" ")
command = ask[0]
entity = ask[1:]
entity = " ".join(entity)
if entity == '':
entity = raw_input("Who do you want to %s? " % command)
if command == 'add':
person = entity
if tel.has_key(person):
print "That person is already in there. If you wish to edit the
file, please delete the record first."
else:
tel[person] = raw_input("What is their phone number? ")
if command == 'get':
if a == 1:
print "Sorry, there are no entries available."
else:
person = entity
if person == 'all':
key = tel.keys()
key.sort()
print
for x in key:
print "%s\n%s\n" % (x,tel[x])
elif tel.has_key(person):
print "\n%s\n%s\n" % (person,tel[person])
else:
print "%s is not in your records." % person
if command == 'save':
file=open('Telephone.cfg', 'w')
file.write(str(tel))
file.close()
print 'Saved in Telephone.cfg'
if command == 'delete':
if a == 1:
print "Sorry, there are no entries available."
else:
person = entity
if person == 'all':
tel={}
newfile=open('Telephone.cfg', 'w')
newfile.close()
else:
if tel.has_key(person):
del tel[person]
else:
print "%s is not in your records." % person
file.close()
file = open('Telephone.cfg', 'w')
file.write(str(tel))
file.close()


As always, feel free to modify, use, and otherwise tear apart my code and
give me suggests on how to improve it.
Jacob Schmidt

> Dear Tutor,
>
> I like to know what is the proper procedure (is algorithmn the right
> term?) in creating data in a program, write it to file, close the app
> then retrieve the data when run again. Basically, I'm trying to simulate
> a simple address book (well not really for the datas are just names for
> now) and so far have created the basic menu interface. It is console
> base so forget gui. I ask user input and store it in a list. There are
> menus to change, delete the data, and to save the data list in file. I
> use cPickle for this and have verified the file is created by checking
> in my $PWD. I want to retrieve that data when program is run again. What
> to add in my code? I thought not to post the code but explain it as
> above.
>
> What i want: when program is run again, the saved data is loaded when user
> selects option 1 below. Of course the first time it is run, the list is
> empty.
>
> def print_options():
>print '''
>Options:
>[1] - Print content of list
>[2] - Add name to list
>[3] - Delete name from list
>[4] - Change name in list
>[5] - Save list to file
>[P] - Print this menu
>[Q] - Quit
>'''
>
>
>
> -- 
> Regards,
> Eri Mendz
> Using PC-Pine 4.61
>
>
> -- 
> Using PC-Pine 4.61
>
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
>
>

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] CGI Video collection application File I/O troubles

2004-12-05 Thread Jacob S.
Your error message says that you are getting an empty string from your cgi
variable. I IMHO would suggest printing videodb['title'] before writing it
to a file to see what the variable contains. Or you might print out videodb
to see what the dictionary looks like. My off the wall guess is that 1) Your
cgi variables are not returning the value from the actual object that you
want 2) The script is running and assigning values to title, etc. before the
afore mentioned object is given a value. IOW, maybe you haven't assigned
values to the form before you try to read them.
Another suggestion. Comment out the file writing part and print everything
to the screen to verify that the output is what you want. "When in doubt,
print it out." - Jacob Schmidt

HTH,
Jacob

> Quoting "Jacob S." <[EMAIL PROTECTED]>:
>
> > Hi!
> >
> > Can I ask a few questions? (Other than this one...)
> > What output did you expect? A string, tuple, or what?
>
> A string output. When I create a dictionary variable from
> the python shell like this:
> videodb={'title':'Crash','year':'1996','director':'David Cronenberg'}
>
> and type in videodb['title'] afterwards python spits out the
> value 'Crash'. That's fine I get a string as expected.
> But when I try to write the value of videodb['title'] to
> a file nothing gets written.
> I hope I clarified the issue somewhat.
>
> > I'm not strong with
> > cgi stuff.
> > Also, you don't need the string module 1) because you don't use it 2)
> > because you can use string methods.
> >
> > Jacob Schmidt
>
> ok. I'll remove it. thanx.
>
> [snip]
>
> --
> The lady on the call box in Monkey Island 2
> Guybrush: I'm lost in the Inky Island Jungle in Monkey 2
> Lady: Just walk off the edge of the screen
>
>

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] CGI Video collection application File I/O troubles

2004-12-05 Thread Jacob S.
Hi!

Can I ask a few questions? (Other than this one...)
What output did you expect? A string, tuple, or what? I'm not strong with
cgi stuff.
Also, you don't need the string module 1) because you don't use it 2)
because you can use string methods.

Jacob Schmidt

> Hello!
>
> I am having some problems with a simple CGi application I am
> coding for my gf. It is supposed to be a video collection
> program. I can't manage to write the value of a dictionary
> key to a file. Like thisL
> f.write(videodb['title'])
>
> It just creates a blank file. When i try to access the
> videodb['title'] key from the python shell it prints
> out the correct value respecitvely. Even when I use the
> print command to write to a HTML file it outputs the
> correct value of videodb['title'] for example.
> When I run the script in python shell it says:
> TypeError: argument 1 must be string or read-only character buffer, not
None
>
> Why doesn't it write the value to the file?
>
> Here's the complete source code:
>
> #!/usr/bin/python
> import cgi,string
>
> filename='/var/www/cgi-bin/videodb'
> print "Content-type: text/html\n"
>
> #extract variable s
> form=cgi.FieldStorage()
> title=form.getvalue("title")
> year=form.getvalue("year")
> director=form.getvalue("director")
>
> videodb={'title':title,'year':year,'director':director}
>
> #save to database
> f=open(filename,'w')
> f.write(videodb['title'])
> f.close()
>
> --
> The lady on the call box in Monkey Island 2
> Guybrush: I'm lost in the Inky Island Jungle in Monkey 2
> Lady: Just walk off the edge of the screen
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
>
>

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Problem with python2.4.

2004-12-09 Thread Jacob S.
Hi all.

Nothing I can do can fix my problem. It appears as though pythonw.exe is
not working properly in the python 2.4 distribution. I have tried numerous
things to try and fix it. The only way I can run Tk scripts and the like is
to use the pythonw.exe from the 2.3 distribution. This includes idle. I am
running Windows XP and I still can't figure out what's wrong. Nothing has
changed with it since the release version of python2.4 to the final version.
Can anyone help me with my predicament? The symptoms: I click on edit with
idle--which runs the command "C:\python24\pythonw.exe"
"C:\python24\lib\idlelib\idle.pyw" -n -e "%1" --then the computer thinks for
a bit and is silent. I hit Ctrl-Alt-Del and the task manager pops up. I look
in processes, and nothing about pythonw.exe is in there like it should be.
What should I do?

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "TypeError: 'int' object is not callable"??

2004-12-16 Thread Jacob S.
Ha! That's what I was looking for! The builtin apply function! The only way
I could send the *args to the function was through a list, and function
calls see a list as one argument. The apply argument doesn't! Thanks Bob.

Jacob Schmidt

> At 12:39 PM 12/8/2004, Bob Gailer wrote:
> >At 11:27 AM 12/8/2004, Dick Moores wrote:
> >>My thanks to both Max and Kent. So Python tries, and fails, to see 2()
as
> >>a function!
> >>
> >>I also got some help from 
> >
> >Note that SOME languages use () for call. There are other call
constructs,
> >such as:
> >
> >DO function WITH parameters (FoxPro, similar in COBOL)
> >
> >function parameter   or   parameter1 function parameter2 (APL)
>
> I should add the Python builtin function apply: apply(function,
parameters...)
>
> Bob Gailer
> [EMAIL PROTECTED]
> 303 442 2625 home
> 720 938 2625 cell
>
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
>
>

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Address book sort of

2004-12-16 Thread Jacob S.
Hey, I made some changes to my address book, with help from Oh darn,
well whoever you are, I haven't forgotten the help you gave me in changing
my if/if/if/if/if/else things into mapping objects Anyway, if anybody
wants a look, here it is.
P.S. I made some changes to the file reading part too. Got rid of some
unnecessary code.


[start]
from os.path import exists as ex

tel = {}
tempname = "Telephone.cfg"
if not ex(tempname):
open(tempname,"w").close()
file = open(tempname,"r")
stuff = file.read()
file.close()
if stuff == '':
a = 1
print "No entries on file."
else:
tel = eval(stuff)
a = 0

print """\
Commands are:
add
get
save
delete
quit
all is a wildcard
"""

def dispatch(command,entity,tel):
tfunct = functs[command]
tfunct(entity,tel)

def add(person,tel):
if tel.has_key(person):
print "That person is already in there. If you wish to edit the
file, please delete the record first."
else:
tel[person] = raw_input("What is their phone number? ")

def get(person,tel):
if a == 1:
print "Sorry, there are no entries available."
else:
if person == 'all':
key = tel.keys()
key.sort()
print
for x in key:
print "%s\n%s\n" % (x,tel[x])
elif tel.has_key(person):
print "\n%s\n%s\n" % (person,tel[person])
else:
print "%s is not in your records." % person

def delete(person,tel):
if not a:
if person == 'all':
tel={}
open('Telephone.cfg', 'w').close()
else:
if tel.has_key(person):
del tel[person]
else:
print "%s is not in your records." % person
else:
print "There is no one to delete."

def save(entitynotneeded,tel):
file=open('Telephone.cfg', 'w')
file.write(str(tel))
file.close()
print 'Saved in Telephone.cfg'

functs = {'add':add,'get':get,'save':save,'delete':delete}

while 1:
ask = raw_input('Tell me what you wish to do. ')
if ask == "quit":
break
ask = ask.split(" ")
command = ask[0]
entity = " ".join(ask[1:])
if entity == '' and command != 'save':
entity = raw_input("Who do you want to %s? " % command)
dispatch(command,entity,tel)

file = open('Telephone.cfg', 'w')
file.write(str(tel))
file.close()
[end]

Jacob Schmidt

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Complex roots

2004-12-16 Thread Jacob S.
Finding the all the roots of a complex number shouldn't be too difficult. I
tend to do it on paper sometimes. Maybe I can write a script to do it for me
instead.  I stongly caution you though. The methods that I show below are
unstable and should be verified by a math web site as it has been quite a
few months since I last used the equations. In fact, I'll almost bet they're
wrong. If you want me to check them, I'll gladly google for the right
equations if you want.

where i == sqrt(-1)

[pseudo-code]
p = (a+bi)**n
n = polar(p)  ## polar is a function that converts rectangular coordinates
to polar coordinates.
radius = n[0]
angle = n[1]

1st rootradius**n cis (angle/(180*n))  ## Where cis is short for
(cos(angle) + i*sin(angle))
2nd rootradius**n cis (angle/(360*n))
...
qth rootradius**n cis (angle/(180*q*n))
[/pseudo-code]

So saying, I would set a for i in range loop for n times to run these root
finders through. Note unless you call some sort of polar to rectangular
function on the roots, they will still be in polar.

HTH as always,
Jacob Schmidt

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Address book sort of

2004-12-16 Thread Jacob S.
You know, instead of that long or thing you've set up, you could do this.

if select in [ 'l', 'v', 'V' ]:

> [quote]
> if select == '1' or select == 'v' or select == 'V':
> if file_in_disk in os.listdir('/home/jerimed'): #
change???
> fhandle = open(file_in_disk, 'r')   # read mode
> cPickle.load(fhandle)   # restore saved
data
> fhandle.close()
> show_contacts()
> elif len(data_holder) > 0:
> show_contacts()
> else:
> is_empty()
> [/quote]


I'd swear that your standard disclaimer changes weekly. : )

Happy Holidays,
Jacob

> Standard disclaimer -
>
> There's probably an easier way to do it, and a more elegant way. Which
> someone will post shortly.
>
> Cheers,
>
> Liam Clarke

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problem with python2.4.

2004-12-16 Thread Jacob S.
If you mean the "Internet Connection Firewall" thingy that you access from
the network connection options, then Nope, that's not the problem, because
it's disabled.

Thanks for your help,
Jacob

>
> Seeing this comment reminded me of some conversations I've seen in
> comp.lang.python recently.  Apparently newer versions of IDLE create a
> subprocess to run user-code in (so that IDLE runs in a different
> interpreter than the code you type into IDLE), and communicates with
> that subprocess through sockets on the loopback interface (that is,
> the 'network connection' that connects only to itself).  Overly
> aggressive firewall programs may block those socket operations.
>
> I'd check whether XP's built-in firewall is enabled, and if so, check
> whether it might be blocking connections to loopback / localhost /
> 127.0.0.1 (all of these indicate the same thing).
>
> Jeff Shannon
> Technician/Programmer
> Credit International
>
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
>

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "TypeError: 'int' object is not callable"??

2004-12-17 Thread Jacob S.
Hey, could you give an example?
Thanks,
Jacob

>
> apply() is deprecated; it has been replaced by 'extended call syntax'.
Instead of
>apply(fn, args, kwds)
> you can now write
>fn(*args, **kwds)
>
> Kent
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
>
>

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "TypeError: 'int' object is not callable"??

2004-12-17 Thread Jacob S.
Thank you!

Wait, though.

How do I do this?

def differentnoofvars(*args,**kwargs):  ## By the way, is it **kwargs or
**kwds?
print kwargs
another(kwargs)

def another(**kwargs):
for x,y in kwagrs.items():
print "%s = %s" % (x,y)

a = ['a=2','f=3','t=[1,2,3]']  ## A list of kwargs that I want to send
individually to differentnoofvars
differentnoofvars(a)


> > Hey, could you give an example?
> > Thanks,
> > Jacob
> >
> > >
> > > apply() is deprecated; it has been replaced by 'extended
> > call syntax'.
> > Instead of
> > >apply(fn, args, kwds)
> > > you can now write
> > >fn(*args, **kwds)
> > >
> > > Kent
>
> Here is a quick example I came up with:
>
> >>> def spam(*args, **kwargs):
> ... print "Here are the args you supplied:"
> ... for item in args:
> ... print item
> ... print
> ... print "Here are the kwargs you supplied:"
> ... for key,value in kwargs.items():
> ... print key, '=', value
> ...
> >>> spam(1,'a','eggs',s=0, p=1, a=2, m=3)
> Here are the args you supplied:
> 1
> a
> eggs
>
> Here are the kwargs you supplied:
> a = 2
> p = 1
> s = 0
> m = 3
>
> In the case of the spam() function, 1, 'a', and 'eggs' are all put into
> the sequence args (not sure if it is a list or tuple).  The key/value
> pairs are bundled into the dictionary kwargs.  The arguments have to be
> given in the right order though:
>
> >>> spam(t=1, b=1, 'this', 'will', 'fail')
> Traceback (SyntaxError: non-keyword arg after keyword arg
>
> HTH!
>
> Christian
> http://www.dowski.com
>
>
>
>

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "TypeError: 'int' object is not callable"??

2004-12-17 Thread Jacob S.
Sorry about that last message. Kent just posted and answered my question
with his example.
Thank you all!

Jacob

> > -Original Message-
> > From: [EMAIL PROTECTED]
> > [mailto:[EMAIL PROTECTED] On Behalf Of Jacob S.
> > Sent: Friday, December 17, 2004 3:54 PM
> > To: Kent Johnson
> > Cc: [EMAIL PROTECTED]
> > Subject: Re: [Tutor] "TypeError: 'int' object is not callable"??
> >
> > Hey, could you give an example?
> > Thanks,
> > Jacob
> >
> > >
> > > apply() is deprecated; it has been replaced by 'extended
> > call syntax'.
> > Instead of
> > >apply(fn, args, kwds)
> > > you can now write
> > >fn(*args, **kwds)
> > >
> > > Kent
>
> Here is a quick example I came up with:
>
> >>> def spam(*args, **kwargs):
> ... print "Here are the args you supplied:"
> ... for item in args:
> ... print item
> ... print
> ... print "Here are the kwargs you supplied:"
> ... for key,value in kwargs.items():
> ... print key, '=', value
> ...
> >>> spam(1,'a','eggs',s=0, p=1, a=2, m=3)
> Here are the args you supplied:
> 1
> a
> eggs
>
> Here are the kwargs you supplied:
> a = 2
> p = 1
> s = 0
> m = 3
>
> In the case of the spam() function, 1, 'a', and 'eggs' are all put into
> the sequence args (not sure if it is a list or tuple).  The key/value
> pairs are bundled into the dictionary kwargs.  The arguments have to be
> given in the right order though:
>
> >>> spam(t=1, b=1, 'this', 'will', 'fail')
> Traceback (SyntaxError: non-keyword arg after keyword arg
>
> HTH!
>
> Christian
> http://www.dowski.com
>
>
>
>

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] gzip (fwd)

2004-12-05 Thread Jacob S.
Hello!

> >target_dir = 'D:\\backup'
> >target = target_dir +"Zipnametoreplacestrftimeformatstring"+ '.zip'
>
> Just noticed this -
>
> target_dir("D:\\backup") + "Zipnametoreplacestrftimeformatstring"+ '.zip'
>
> = D:\\backupZipnametoreplacestrftimeformatstring.zip
>
> No wonder it doesn't work.
>
> Try
>
> target=target_dir+'\\'+time.strftime('%Y%m%d%H%M%S') + '.zip'

Instead of doing this, use os.path.join to make it more platform
independent.

target = os.path.join(target_dir,time.strftime('%Y%m%d%H%M%S')+'.zip')

>
> Regards,
>
> Liam Clarke
>
> PS Yes, do use reply to all
>
>
>
>
> On Fri, 3 Dec 2004 15:16:27 +0600, Ramkumar Parimal Alagan
> <[EMAIL PROTECTED]> wrote:
> > I have only 2 word documents in both the directories, i tried removing
> > '-qr' too, but no change, no zip files formed. i'm using windows XP.
> >
> > On Thu, 2 Dec 2004 23:54:11 -0800 (PST), Danny Yoo
> >
> >
> > <[EMAIL PROTECTED]> wrote:
> > > Hi Ramkumar,
> > >
> > > I'm forwarding your message to Python-tutor; in your replies, please
make
> > > sure that you are using the "reply-to-all" feature in your email
client.
> > > This will allow your response to reach the others on the tutor list.
> > > Don't rely on me alone: give the community the chance to help you.
> > >
> > > I don't have enough information to pinpoint what the problem is yet.
I'll
> > > have to ask more questions, and others on the Tutor list will probably
> > > also ask a few questions.  Please try to answer them, because that
will
> > > help us give a better idea of what the problem is.
> > >
> > > It looks like you are trying to zip up whole directories.  Does the
> > > program work if you zip up single files?
> > >
> > > It also appears that you're using the '-q' and '-r' options of the
'zip'
> > > command line utility.  '-q' stands for 'quiet' mode, and although
that's
> > > nice when the command is working properly, it's not helpful when
you're
> > > debugging a situation.  Try turning quiet mode off, so that you have a
> > > better chance of getting good error output from the zip command.  Even
> > > better, try enabling verbose mode, so you can see better what 'zip' is
> > > attempting to do.
> > >
> > > Do you see anything else when you execute the program?  Does anything
else
> > > come out of standard error?
> > >
> > > Good luck to you.
> > >
> > > -- Forwarded message --
> > > Date: Fri, 3 Dec 2004 10:24:15 +0600
> > > From: Ramkumar Parimal Alagan <[EMAIL PROTECTED]>
> > > To: Danny Yoo <[EMAIL PROTECTED]>
> > > Subject: Re: [Tutor] gzip
> > >
> > > This is what i intend to do:
> > >
> > > 1. The files and directories to be backed up are given in a list.
> > > 2. The backup must be stored in a main backup directory.
> > > 3. The files are backed up into a zip file.
> > > 4. The name of the zip archive is the current date and time.
> > >
> > > the coding:
> > >
> > > __
> > >
> > > import os
> > > import time
> > >
> > > source = ['D:\\down', 'D:\\Pics']
> > >
> > > target_dir = 'D:\\backup'
> > >
> > > target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip'
> > >
> > > zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
> > >
> > > if os.system(zip_command) == 0:
> > > print 'Successful backup to', target
> > > else:
> > > print 'Backup FAILED'
> > >
> > > _
> > >
> > > result : Backup FAILED
> > >
> > > whats wrong ?
> > >
> > >
> >
> >
> > --
> >
> >  <<  The end depends upon the beginning. >>
> >
> >
> > ___
> > Tutor maillist  -  [EMAIL PROTECTED]
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
>
> -- 
> 'There is only one basic human right, and that is to do as you damn well
please.
> And with it comes the only basic human duty, to take the consequences.
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
>
>

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Difference between for i in range(len(object)) andfor iin object

2004-12-18 Thread Jacob S.
> Thing is, for people like me, you generally either don't know that a
> question is a dumb one until someone tells you the answer, (the 'of
> course'  moment), or until 5 minutes after you emailed
> your query, you find the answer you were looking for...

Amen! My life's story!

Also, to Kumar.

This is what you want.

test_cor = []
for line in cor:
test_cor.append(line.split('\t',1)[1])  ## This only works if there are
only 3 columns

Or, even simpler:

test_cor = [line.split('\t',1)[1] for line in cor]

HTH,
Jacob

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python 2.4 IDLE Windows 2000

2004-12-18 Thread Jacob S.
Gee,
I think I'm going to burst out in tears.
Mike Hansen gave the solution to the very problem I'm having, yet, when I
used the console version and deleted the custom color theme, it stopped
giving me error messages, but it still won't start up without the console.

I'm am still stunted of my python 2.4 experience.
Help, please!!!

Desperate,
Jacob

> Mike Hansen <[EMAIL PROTECTED]> wrote of an idle IDLE:
>
> > That rooted out the problem. A while ago, I changed the colors to kind
> > of match my VIM color theme(ps_color). When I did
> > idlelib.PyShell.main(), IDLE came up with my custom color theme.
> > However, there was a bunch of warnings about my theme. From IDLE, I
> > deleted the theme. Now IDLE will launch normally. I'll set up the color
> >
> > theme later. Maybe older color themes aren't compatible with the newer
> > IDLE? The color theme must have been laying around. I didn't brute
> > force
> > it in or anything like that.
> >
>
> > >IDLE is a
> > >part of the Standard Library, so it's actually possible to try turning
> > on
> > >individual pieces of it, one after the other.  Maybe that will help us
> > >debug what's going on.
> > >
> > >Start up your console version of Python, and try:
> > >
> > >
> > import idlelib.PyShell
> > idlelib.PyShell.main()
> > 
>
>
> Just a +1 to Mike's problem (and the solution).  For sake of Googlers
searching on error output (which I've done before), here are the errors I
was getting on my machine when trying to launch IDLE.  Note, when I tried to
open a .py file with IDLE the file would not open at all (and there were no
error messages) - interesting that the whole process failed - is the missing
error handling on the win or python side (no reason for these to have been
fatal errors...)
>
> Ah, now I can enjoy 2.4.  Thanks!
>
> my error output (win32):
>
>
> >>> import idlelib.PyShell
> >>> idlelib.PyShell.main()
>
>  Warning: configHandler.py - IdleConf.GetThemeDict -
>  problem retrieving theme element 'builtin-background'
>  from theme 'sagecomments'.
>  returning default value: '#ff'
>
>  Warning: configHandler.py - IdleConf.GetThemeDict -
>  problem retrieving theme element 'builtin-foreground'
>  from theme 'sagecomments'.
>  returning default value: '#00'
>
>  Warning: configHandler.py - IdleConf.GetThemeDict -
>  problem retrieving theme element 'builtin-background'
>  from theme 'sagecomments'.
>  returning default value: '#ff'
>
>  Warning: configHandler.py - IdleConf.GetThemeDict -
>  problem retrieving theme element 'builtin-foreground'
>  from theme 'sagecomments'.
>  returning default value: '#00'
>
>  Warning: configHandler.py - IdleConf.GetThemeDict -
>  problem retrieving theme element 'builtin-background'
>  from theme 'sagecomments'.
>  returning default value: '#ff'
>
>  Warning: configHandler.py - IdleConf.GetThemeDict -
>  problem retrieving theme element 'builtin-foreground'
>  from theme 'sagecomments'.
>  returning default value: '#00'
>
>  Warning: configHandler.py - IdleConf.GetThemeDict -
>  problem retrieving theme element 'builtin-background'
>  from theme 'sagecomments'.
>  returning default value: '#ff'
>
>  Warning: configHandler.py - IdleConf.GetThemeDict -
>  problem retrieving theme element 'builtin-foreground'
>  from theme 'sagecomments'.
>  returning default value: '#00'
>
>  Warning: configHandler.py - IdleConf.GetThemeDict -
>  problem retrieving theme element 'builtin-background'
>  from theme 'sagecomments'.
>  returning default value: '#ff'
>
>  Warning: configHandler.py - IdleConf.GetThemeDict -
>  problem retrieving theme element 'builtin-foreground'
>  from theme 'sagecomments'.
>  returning default value: '#00'
>
>  Warning: configHandler.py - IdleConf.GetThemeDict -
>  problem retrieving theme element 'builtin-background'
>  from theme 'sagecomments'.
>  returning default value: '#ff'
>
>  Warning: configHandler.py - IdleConf.GetThemeDict -
>  problem retrieving theme element 'builtin-foreground'
>  from theme 'sagecomments'.
>  returning default value: '#00'
>
>  Warning: configHandler.py - IdleConf.GetThemeDict -
>  problem retrieving theme element 'builtin-background'
>  from theme 'sagecomments'.
>  returning default value: '#ff'
>
>  Warning: configHandler.py - IdleConf.GetThemeDict -
>  problem retrieving theme element 'builtin-foreground'
>  from theme 'sagecomments'.
>  returning default value: '#00'
>
>  Warning: configHandler.py - IdleConf.GetThemeDict -
>  problem retrieving theme element 'builtin-background'
>  from theme 'sagecomments'.
>  returning default value: '#ff'
>
>  Warning: configHandler.py - IdleConf.GetThemeDict -
>  problem retrieving theme element 'builtin-foreground'
>  from theme 'sagecomments'.
>  returning default value: '#00'
>
>  Warning: configHandler.py - IdleConf.GetThemeDict -
>  problem retrieving theme element 'builtin-background'
>  from theme 'sagecomments'.
>  returning default value: '#ff'
>

Re: [Tutor] "TypeError: 'int' object is not callable"??

2004-12-18 Thread Jacob S.
Thanks for the explanation!
Jacob Schmidt


> Jacob S. wrote:
> > Thank you!
> >
> > Wait, though.
> >
> > How do I do this?
> >
> > def differentnoofvars(*args,**kwargs):  ## By the way, is it **kwargs or
> > **kwds?
>
> Call it what you like, it's an ordinary function parameter. kwds is
commonly used but you can use
> kwargs.
> > print kwargs
> > another(kwargs)
>
> Should be another(**kwargs). If you call another(kwargs) then kwargs will
be an ordinary parameter
> of another and another would be defined as
> def another(kwargs):
>...
>
> >
> > def another(**kwargs):
> > for x,y in kwagrs.items():
> > print "%s = %s" % (x,y)
> >
> > a = ['a=2','f=3','t=[1,2,3]']  ## A list of kwargs that I want to send
>
> Should be a dict, the **kwds parameter is a dict mapping keywords to
values
> a = {'a':2, 'f':3, 't':[1,2,3]}
>
> There really are two different and complementary things going on here, at
the point of call and at
> the point of function definition.
>
> At the point of call, you can pass a dictionary instead of using explicit,
named parameters. For
> example, given a function test() defined like this:
>   >>> def test(a, b):
>   ...  print a, b
>
> you can call it with ordinary named arguments:
>   >>> test(a='foo', b='bar')
> foo bar
>
> Or you can pass it a dictionary with the named arguments, using extended
calling syntax:
>   >>> d= {'a':'foo', 'b':'bar'}
>   >>> test(**d)
> foo bar
>
>
> Inside the function, if you have a **kwds parameter, it will receive a
dict containing any keyword
> arguments not explicitly declared. This allows you to pass keyword
parameters that you don't
> anticipate when the function is defined. For example,
>
>   >>> def test2(a, **kwds):
>   ...   print a
>   ...   for k,v in kwds.items():
>   ... print k,v
>
>   >>> test2(1) # No keywords
> 1
>   >>> test2(a=1) # a is a declared parameter so kwds is empty
> 1
>   >>> test2(1, b=2, c=3) # b and c are passed in kwds
> 1
> c 3
> b 2
>
> Kent
>
> > individually to differentnoofvars
> > differentnoofvars(a)
> >
> >
> >
> >>>Hey, could you give an example?
> >>>Thanks,
> >>>Jacob
> >>>
> >>>
> >>>>apply() is deprecated; it has been replaced by 'extended
> >>>
> >>>call syntax'.
> >>>Instead of
> >>>
> >>>>   apply(fn, args, kwds)
> >>>>you can now write
> >>>>   fn(*args, **kwds)
> >>>>
> >>>>Kent
> >>
> >>Here is a quick example I came up with:
> >>
> >>
> >>>>>def spam(*args, **kwargs):
> >>
> >>... print "Here are the args you supplied:"
> >>... for item in args:
> >>... print item
> >>... print
> >>... print "Here are the kwargs you supplied:"
> >>... for key,value in kwargs.items():
> >>... print key, '=', value
> >>...
> >>
> >>>>>spam(1,'a','eggs',s=0, p=1, a=2, m=3)
> >>
> >>Here are the args you supplied:
> >>1
> >>a
> >>eggs
> >>
> >>Here are the kwargs you supplied:
> >>a = 2
> >>p = 1
> >>s = 0
> >>m = 3
> >>
> >>In the case of the spam() function, 1, 'a', and 'eggs' are all put into
> >>the sequence args (not sure if it is a list or tuple).  The key/value
> >>pairs are bundled into the dictionary kwargs.  The arguments have to be
> >>given in the right order though:
> >>
> >>
> >>>>>spam(t=1, b=1, 'this', 'will', 'fail')
> >>
> >>Traceback (SyntaxError: non-keyword arg after keyword arg
> >>
> >>HTH!
> >>
> >>Christian
> >>http://www.dowski.com
> >>
> >>
> >>
> >>
> >
> >
> > ___
> > Tutor maillist  -  [EMAIL PROTECTED]
> > http://mail.python.org/mailman/listinfo/tutor
> >
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
>

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: A simpler mousetrap

2004-12-18 Thread Jacob S.
Also, just as interesting, yet probably less reliable:

a = list(a)
a[-3:] = 'bak'
a = "".join(a)

OR

a = a.rstrip('pct')
a = a+'bak'

OR

a = a.rstrip('pct')+'bak'  ## Which is essentially the same thing

OR

a = a[:-3]+'bak'

ETC.

HTH,
Jacob

> x=os.path.splitext(a)[0]+'.bak'
>
> Ah, jolly good, looks a bit simpler. Thanks!
>
> Regards,
>
> Liam Clarke
>
> On Thu, 16 Dec 2004 09:44:03 +0100, Wolfram Kraus
> <[EMAIL PROTECTED]> wrote:
> > Liam Clarke wrote:
> > > Hi all,
> > >
> > > I'm writing some code, and I want to take a given path + filename, and
> > > change the file extension to *.bak.
> > >
> > > In doing so, (entirely internal this function), I am assuming -
> > >
> > > That the file will always have an extension
> > > Thathe extension will vary
> > > But, it will follow the general DOS format of name.ext
> > >
> > > So, I came up with this -
> > >
> > > a="./tc/arc/gab.pct"
> > >
> > > x=a.replace(a[a.rfind('.'):len(a)],'.bak')
> > >
> > > x="./tc/arc/gab.bak"
> > >
> > > So, it works, but it feels a bit, well, hacky to me. Not nearly hacky
> > > as using an regex though ; )
> > >
> > > I thought about
> > >
> > > a="./tc/arc/gab.pct"
> > >
> > > aList=a.split('.')
> > > aList[-1]='bak'
> > > a=".".join(aList)
> > >
> > > but I'm wondering if there's a simpler way, as there usually seems to
> > > be, and it's always so obvious once I'm shown it, like 6 down - Six on
> > > vehicle live in the manse (VI + car). Obvious once you know.
> > >
> > > Regards,
> > >
> > > Liam Clarke
> >
> > Hey Liam!
> >
> > The os.path module is your friend, especially split and splitext:
> > http://docs.python.org/lib/module-os.path.html
> >
> > HTH,
> > Wolfram
> >
> > ___
> > Tutor maillist  -  [EMAIL PROTECTED]
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
>
> -- 
> 'There is only one basic human right, and that is to do as you damn well
please.
> And with it comes the only basic human duty, to take the consequences.
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
>
>

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Vpython

2004-12-18 Thread Jacob S.
> > I was wondering were can I find some Vpython graphics program codes that
are readily available.

I have 2 that I am proud of.

A simple function grapher
Usage:
>0.125*x**2

Graphs y = 1/8*x**2

>y = 1/x

Graphs y = 1/x

>clear

Clears display window

>r = t**2

Graphs polar function r = t**2

>remove lines

Removes all axes, including polar axes, should a polar function be graphed
after

>return lines

Returns all lines, so that they appear when appropriate.

>x = sin(x**2)+log(x**2)

Graphs the function...


--

from __future__ import division
from visual import *
import os
from math import *
ja = 0

def start():
for objects in scene.objects:
objects.visible = 0
scene.title = "Function Grapher by Jacob, Inc."
tem = raw_input('Are you on a desktop, or a notebook? ')
if tem == 'desktop':
scene.x = 365
if tem == 'notebook':
scene.x = 574
scene.visible=1
scene.exit=0
scene.userspin = 0
scene.range=(10,10,1)
scene.background=(1,1,1)
global xaxis
global yaxis
xaxis = curve(color=color.black)
xaxis.append(pos=(100,0,0))
xaxis.append(pos=(-100,0,0))
yaxis = curve(color=color.black)
yaxis.append(pos=(0,100,0))
yaxis.append(pos=(0,-100,0))
global radiusaxis
global radiusaxis2
radiusaxis = curve(pos=[(-100,-100),(100,100)],color=color.black)
radiusaxis2 = curve(pos=[(-100,100),(100,-100)],color=color.black)
radiusaxis.visible = 0
radiusaxis2.visible = 0

start()
y = 3
m = 0
t = 0
d = 1
print """\
List of Commands:
clear
quit
remove lines
return lines

Function Syntax:
var = funct a,b
where var = what
and funct = f(what)
and a,b = range
"""

print 'Please type in functions in below. '
while y != "":
lists=[]
y = raw_input('>')
if y == 'clear':
scene.visible=0
start()
print "-"*36
continue
elif y == 'quit':
scene.visible = 0
del scene
break
elif y == 'remove lines':
a = [radiusaxis,radiusaxis2,xaxis,yaxis]
for x in a:
x.visible = 0
d = 0
continue
elif y == 'return lines':
a = [radiusaxis,radiusaxis2,xaxis,yaxis]
for x in a:
x.visible = 1
d = 1
continue
if y.count('=') == 1:
y = y.split(' = ')
type = y[0].lower()
y = y[1]
y = y.replace("y","x")
if type == 'r':
y = y.replace('x','t')
if d == 1:
radiusaxis.visible = 1
radiusaxis2.visible = 1
else:
type = 'y'
y = y.split(" ")
if len(y) > 1:
pass
else:
if type == 'r':
y.append('0,5*pi')
else:
y.append('-10,10')
range = y[1]
y = y[0]
range = range.split(",")
min = float(eval(range[0]))
max = float(eval(range[1]))
lists.append(curve(color=(1,0,1)))
x = min
if type == 'y' or type == 'x':
radiusaxis.visible = 0
radiusaxis2.visible = 0
while x >= min and x <= max:
x = x+0.005
try:
if eval(y) <= 15 and eval(y) >= -15:
if type == 'y':
lists[-1].append(pos=(x,eval(y),0))
elif type == 'x':
lists[-1].append(pos=(eval(y),x,0))
else:
lists.append(curve(color=(1,0,1)))
except:
pass
elif type == 'r':
m = 'eval(y)*cos(t)'
n = 'eval(y)*sin(t)'
t = min
while t >= min and t <= max:
try:
lists[-1].append(pos=(eval(m),eval(n),0))
except:
lists.append(curve(color=(1,0,1)))
t = t+0.005


___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Nifty

2004-12-18 Thread Jacob S.
I probably wouldn't be any help on projects, but I would probably learn
stuff from it.
I'm okay with it.
Jacob Schmidt

> >> I just got in contact with Nick Parlante of the Nifty
> >> Assignments project; he's been collecting material on fun
> >> projects:
> >>
> >> http://nifty.stanford.edu/
>
> > What do others think?
> Private channel or not, I'm in. (at least until classes spike up again in
> early February) Sounds like a good way to burn through a winter.
>
> Heck I don't even know if I CAN convert C++ to Python but I've never let a
> problem like language stop me from playing Chinese chess on boats in china
> ... So even if I lack the ability, I'm for the idea of having running
> 'projects' for the tutor list to do. That way it's driven a bit less by
> homework problems.
>
> --
>
> Programmer's mantra; Observe, Brainstorm, Prototype, Repeat
>
> David Broadwell
>
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
>
>

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] least squares

2004-12-18 Thread Jacob S.
Hey, now.

I know that some of us are newbies to python, but that doesn't mean that
we're all newbies to math concepts. (Even advanced ones.) Having said that,
I will shut my fat mouth now because it will be my luck that the math is
beyond what I can handle. I wouldn't mind seeing the code. Even if it is
long, I wouldn't mind seeing it. A private message is acceptable for
something too lengthy for the tutor list.

Jacob


> Hi Matt,
>
>
> Ok.  I have to admit that my mathematical maturity is actually a little
> low, but I'll try to follow along.  But this really doesn't sounds like a
> problem specific to Python though, but more of a math problem.
>
> So you may actually want to talk with folks with a real math background; I
> would not be mathematically mature enough to know if your code is correct.
> I'd strongly recommend talking to folks on the 'sci.math' or
> 'sci.math.num-analysis' newsgroups.
>
>
> I haven't seen your code, so I'm still in the dark about how it works or
> what its capabilities are.  I'll make a few assumptions that might not be
> right, but I have to start somewhere.  *grin*
>
> Does your code provide a way at getting at all possible solutions, or only
> one particular solution?  If so, then you can just filter out for
> solutions that satisfy the property you want.
>
> For example, we can produce a function that generates all squares in the
> world:
>
> ###
> >>> import itertools
> >>> def allSquares():
> ... for i in itertools.count():
> ... yield i*i
> ...
> >>> squares = allSquares()
> >>> squares.next()
> 0
> >>> squares.next()
> 1
> >>> squares.next()
> 4
> >>> squares.next()
> 9
> >>> squares.next()
> 16
> >>> squares.next()
> 25
> ###
>
>
> I can keep calling 'next()' on my 'squares' iteration, and keep getting
> squares.  Even though this can produce an infinite sequence of answers, we
> can still apply a filter on this sequence, and pick out the ones that are
> "palindromic" in terms of their digits:
>
> ###
> >>> def palindromic(n):
> ..."Returns true if n is 'palindromic'."
> ...return str(n) == str(n)[::-1]
> ...
> >>> filteredSquares = itertools.ifilter(palindromic, allSquares())
> >>> filteredSquares.next()
> 0
> >>> filteredSquares.next()
> 1
> >>> filteredSquares.next()
> 4
> >>> filteredSquares.next()
> 9
> >>> filteredSquares.next()
> 121
> >>> filteredSquares.next()
> 484
> >>> filteredSquares.next()
> 676
> ###
>
>
> This sequence-filtering approach takes advantage of Python's ability to
> work on a iteration of answers.  If your program can be written to produce
> an infinite stream of answers, and if a solution set with all positive
> coefficients is inevitable in that stream, then you can take this
> filtering approach, and just capture the first solution that matches your
> constraints.
>
>
>
> Similarly, if your program only produces a single solution, does it do so
> through an "iterative" algorithm?  By iterative, I mean: does it start off
> with an initial guess and apply a process to improve that guess until the
> solution is satisfactory?
>
> For others on the Tutor list, here is an "iterative" way to produce the
> square root of a number:
>
> ###
> def mysqrt(x):
> guess = 1.0  ## initial guess
> while not goodEnough(guess, x):
> guess = improve(guess, x)
> return guess
>
> def improve(guess, x):
> """Improves the guess of the square root of x."""
> return average(guess, x / guess)
>
> def average(x, y):
> return (x + y) / 2.0
>
> def goodEnough(guess, x):
> """Returns true if guess is close enough to the square root of x."""
> return abs(guess**2 - x) < 0.1
> ###
>
> (adapted/ripped off from material in SICP:
> http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-10.html#%_sec_1.1.7)
>
>
>
> If your program tries to solve the problem through an iterative process,
> then, again, does it inevitably produce a solution where all the constant
> coefficients 'Cn' are positive?  If so, maybe you can just continue to
> produce better and better solutions until its satisfactory, until all the
> coefficients are positive.
>
>
> Otherwise, without looking at your code, I'm stuck.  *grin* And even if I
> do see your code, I might be stuck still.  If your code is short, feel
> free to post it up, and we'll see how far we can get.  But you really may
> want to talk with someone who has a stronger math background.
>
> Good luck to you!
>
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
>

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] listing all combinations of elements of a list

2004-12-18 Thread Jacob S.
Am I wrong, or is that what the module sets is for? I don't remember if
python 2.3 has it, but python2.4 has it available.

>>> import sets
>>> s = sets.Set
>>> a = s([1,2,3])
>>> a
Set([1, 2, 3])
>>> a.update([1,1,2,2,3,3,4,4,5,5])
>>> a
Set([1, 2, 3, 4, 5])
>>>

HTH,
Jacob Schmidt

> > def combination(items)
> > list = []
> > for i in range(0,len(items)):
> >for j in range(0,len(items)):
>
>  for i in items:
>  for j in items:
>
> Is both shorter and faster - no len() function calls.
>
> Or if you want to use indices:
>
> size = len(items)  # only calculate once, it won't change!
> lst = []# don't use builtin function names for
> variables
> for i in range(0,size)
>  for j in range(i+1,size)
>lst.append()
> return lst
>
> That saves a lot of len() calls and a comparison.
> Also it avoids iterating over the whole list each time.
>
>
> > My problems with this code being that a) code I write is usually
> pretty
> > inefficient, b) it doesn't extend to subsets of size > 2, and c) it
> uses
> > nested loops, which I have gathered from some previous discussions
> on
> > this list to be less than ideal.
>
> I've tidied up a little but I think nested loops are a necessary evil
> in
> this case - although somebody is sure to prove me wrong! :-)
>
> HTH,
>
> Alan G.
>
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
>
>

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing two elements in a list

2004-12-19 Thread Jacob S.
Would this work for you?

a = ['Name = stuff','CGTATAGCTAGCTA','Name = stuff','CGATATGCCGGCTA']
for index,thing in enumerate(a):
if "Name=" in thing:
del a[index]

I know, that it might be slow, but I thought that maybe it would hold its
own because it doesn't have to import the re module, everything's builtin,
etc.

HTH,
Jacob

 Hello group,
>  Thank you very much for your kind replies. In fact I
> survived to pull out what I needed by going with
> Kent's tip by enumerating on iterator.
>
> The problem with me is suddenly I embarked on
> something big problem and I am surviving it in pieces
> by writing pieces of code.
>
>
> I have another question:
> To be brief:
>
> My list contains some elements that I do not want and
> I want to remove unwanted elements in my list:
>
> My TEXT file looks like this:
>
> Name=32972_at
> Cell1=xxx xxx N control 32972_at
> Cell1=xxx xxx N control 32972_at
> Cell1=xxx xxx N control 32972_at
> Cell1=xxx xxx N control 32972_at
> Name=3456_at
> Cell1=xxx xxx N control 3456_at
> Cell1=xxx xxx N control 3456_at
> Cell1=xxx xxx N control 3456_at
> Cell1=xxx xxx N control 3456_at
> .   ... x   xxx
> (34K lines)
>
> I want to remove Name=Xxxx_at identifiers.
>
>
> My List:
> ['Name=32972_at',
>
'Cell1=432\t118\tN\tcontrol\t32972_at\t0\t13\tA\tA\tA\t0\t75952\t-1\t-1\t99\
t',
>
'Cell2=432\t117\tN\tcontrol\t32972_at\t0\t13\tA\tT\tA\t0\t75312\t-1\t-1\t99\
t',
>
'Cell3=499\t632\tN\tcontrol\t32972_at\t1\t13\tC\tC\tC\t1\t404979\t-1\t-1\t99
\t']
>
>
> I tried to resolve in this way:
>
> >>>pat = re.compile('Name')
> >>> for i in range(len(cord)):
> x = pat.search(cord[i])
> cord.remove(x)
>
> I know I am wrong here because I do not know how to
> search and remove an element in a list. Can any one
> please help me.
>
> on Page 98, chapter Lists and dictionaries of mark
> lutz's learning python. It is mentioned in table 6-1 :
> L2.append(4)  Methods: grow,sort,search,reverse etc.
>
>
> Although not much is covered on this aspect in this
> book, I failed to do more operations on list.
>
> Looking forward for help from tutors.
>
> Thank you.
> Kumar.
>
>
>
>
>
>
> --- Kent Johnson <[EMAIL PROTECTED]> wrote:
>
> > kumar,
> >
> > Looking at the quantity and structure of your data I
> > think the search you are doing is going to be
> > pretty slow - you will be doing 4504 * 398169 =
> > 1,793,353,176 string searches.
> >
> > Where does the seq data come from? Could you
> > consolidate the pairs of lines into a single record?
> > If
> > you do that and extract the '399:559' portion, you
> > could build a dict that maps '399:559' to the
> > full record. Looking up '399:559' in the dictionary
> > would be much, much faster than searching the
> > entire list.
> >
> > If you have multiple entries for '399:559' you could
> > have the dict map to a list.
> >
> > Kent
> >
> > kumar s wrote:
> > >
> > len(x)
> > >
> > > 4504
> > >
> > x[1:10]
> > >
> > > ['454:494', '319:607', '319:608', '322:289',
> > > '322:290', '183:330', '183:329', '364:95',
> > '364:96']
> > >
> > len(seq)
> > >
> > > 398169
> > >
> > seq[0:4]
> > >
> > > ['>probe:HG-U95Av2:1000_at:399:559;
> > > Interrogation_Position=1367; Antisense;',
> > > 'TCTCCTTTGCTGAGGCCTCCAGCTT',
> > > '>probe:HG-U95Av2:1000_at:544:185;
> > > Interrogation_Position=1379; Antisense;',
> > > 'AGGCCTCCAGCTTCAGGCAGGCCAA']
> > >
> > >
> > >
> > for ele1 in x:
> > >
> > > for ele2 in seq:
> > > if ele1 in ele2:
> > > print ele2
> > >
> > >
> > >
> > >>probe:HG-U95Av2:31358_at:454:493;
> > >
> > > Interrogation_Position=132; Antisense;
> > >
> > >>probe:HG-U95Av2:31358_at:319:607;
> > >
> > > Interrogation_Position=144; Antisense;
> > >
> > >
> > >
> > >
> > >
> > >
> > > How Do I WANT:
> > >
> > > I want to print get an output like this:
> > >
> > >
> > >
> > >>probe:HG-U95Av2:1000_at:399:559;
> > >
> > > Interrogation_Position=1367; Antisense;'
> > > TCTCCTTTGCTGAGGCCTCCAGCTT
> > >
> > >
> > >>probe:HG-U95Av2:1000_at:544:185;
> > >
> > > Interrogation_Position=1379; Antisense;
> > > AGGCCTCCAGCTTCAGGCAGGCCAA
> > >
> > >
> > > can any one please suggest what is going wrong in
> > my
> > > statements and how can I get it.
> > >
> > > Thank you.
> > > Kumar
> > >
> > >
> > >
> > > __
> > > Do you Yahoo!?
> > > Yahoo! Mail - 250MB free storage. Do more. Manage
> > less.
> > > http://info.mail.yahoo.com/mail_250
> > > ___
> > > Tutor maillist  -  [EMAIL PROTECTED]
> > > http://mail.python.org/mailman/listinfo/tutor
> > >
> > ___
> > Tutor maillist  -  [EMAIL PROTECTED]
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
>
>
>
> __
> Do you Yahoo!?
> Yahoo! Mail - now with 250MB free storage. Learn more.
> http://info.mail.yahoo.com/mail_250
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.o

[Tutor] A better way to do it.

2004-12-20 Thread Jacob S.
Okay, here's the code.

I am completely open to suggestions as this is my first dabbling in Tk.
Please look over it when you have time.

I have a couple of questions.
1) How do I change the title of the window?
2) Why does a window pop up saying something like error, the memory could
not be "read". I'm running
Windows XP, the script window disappears, and everything, just this message
pops up.


Jacob Schmidt


-
from Tkinter import *
import tkMessageBox
import os
from filecmp import cmpfiles

class Copying:
def __init__(self,action,var,err):
self.action = action
self.pri = var
self.err = err

self.j = os.path.join
self.r = os.path.isdir
self.e = os.path.isfile


#  These are the default values for the directories. To make it
simpler you could... ##
## pseudo
##  self.usbdrive = remote folder
## self.desktop = localer folder

dirlist = os.listdir("c:\\")
if 'Jacob Laptop' in dirlist:
self.usbdrive = 'E:\\Working Python Programs'
self.desktop = 'C:\\documents and
settings\\jacob\\desktop\\Working Python Programs'
elif 'Home Computer' in dirlist:
self.usbdrive = 'F:\\Working Python Programs'
self.desktop = 'C:\\documents and
settings\\owner\\desktop\\Working Python Programs'
elif 'Sissy Computer' in dirlist:
self.usbdrive = '' ## Need to fill in
self.desktop = ''  ## Need to fill in
elif 'Michael Laptop' in dirlist:
self.usbdrive = 'E:\\Working Python Programs'
self.desktop = 'C:\\documents and
settings\\michael\\desktop\\Working Python Programs'
elif 'Office Computer' in dirlist:
self.usbdrive = 'D:\\Working Python Programs'
self.desktop = 'C:\\windows\\desktop\\Working Python Programs'
elif 'School Auction Laptop' in dirlist:
self.usbdrive = '' ## Need to fill in
self.desktop = 'C:\\windows\\desktop\\Working Python Programs'
else:
print 'Hey you need to put a folder in this computer!. '
print '''Folders include:
Jacob Laptop
Home Computer
Sissy Computer
Michael Laptop
Office Computer
School Auction Laptop
'''
folder = raw_input('Which computer is this? ')
folder = "C:\\"+folder
os.mkdir(folder)
self.usbdrive = raw_input('What is the usb drive on this
computer? ')
self.desktop = raw_input('What is the desktop on this computer?
')

# # #
if not os.path.exists(self.desktop):
os.mkdir(self.desktop)
m = {'receiving':self.receiving,'sending':self.sending}
m[self.action]()


def copyfile(self,src,des):
x = open(src,'rb').read()
y = open(des,'wb')
y.write(x)
y.close()


def receiving(self):
chiplist = os.listdir(self.usbdrive)
pclist = os.listdir(self.desktop)
filechange = cmpfiles(self.usbdrive,self.desktop,chiplist)[1]
tot = 0
for x in chiplist:
if x not in pclist:
filechange.append(x)
for x in filechange:
fullname = self.j(self.usbdrive,x)
if self.e(fullname):
self.copyfile(fullname,self.j(self.desktop, x))
self.pri.set("Copying %s." % x)
self.err.insert(END,"%s copied from chip to computer.\n" %
x)
tot = tot + 1
elif self.r(fullname):
self.err.insert(END,"%s is a directory. It has not been
copied.\n" % fullname)
self.err.insert(END,"%s file(s) copied.\n"%tot)
self.pri.set("")
pclist.sort()
chiplist.sort()
newlist = [x for x in pclist if x not in chiplist]
for x in newlist:
if tkMessageBox.askokcancel('Delete?',"Do you wish to delete %s?
" % x):
filename = self.j(self.desktop, x)
if self.e(filename):
os.remove(filename)
self.err.insert(END,"%s has been removed from your
chip.\n"%x)
elif self.r(filename):
os.rmdir(filename)
self.err.insert(END,"%s has been removed from your
chip.\n"%x)
else:
self.err.insert(END,"Did not remove %s\n"%x)

def sending(self):
pclist = os.listdir(self.desktop)
chiplist = os.listdir(self.usbdrive)
filechange = cmpfiles(self.desktop,self.usbdrive,pclist)[1]
tot = 0
for x in pclist:
if x not in chiplist:
filecha

Re: [Tutor] Printing two elements in a list

2004-12-20 Thread Jacob S.
Duh, whack myself on the head a few times.
Thanks,
Jacob

> Max Noel wrote:
> > 
> > On Dec 19, 2004, at 06:16, Jacob S. wrote:
> > 
> >> Would this work for you?
> >>
> >> a = ['Name = stuff','CGTATAGCTAGCTA','Name = stuff','CGATATGCCGGCTA']
> >> for index,thing in enumerate(a):
> >> if "Name=" in thing:
> >> del a[index]
> >>
> > 
> > A faster way to do this would be to use something like:
> > 
> > if thing.beginswith("Name"): del a[index]
> 
> Like, maybe,
>if thing.startswith('Name')...
> 
> ;)
> 
> Kent
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Printing two elements in a list

2004-12-20 Thread Jacob S.
That's interesting, I hadn't thought of that!
Jacob

> Jacob S. wrote:
> 
> > Would this work for you?
> >
> > a = ['Name = stuff','CGTATAGCTAGCTA','Name = stuff','CGATATGCCGGCTA']
> > for index,thing in enumerate(a):
> > if "Name=" in thing:
> > del a[index]
> >
> > I know, that it might be slow, but I thought that maybe it would hold 
> > its
> > own because it doesn't have to import the re module, everything's 
> > builtin,
> > etc.
> >
> Be careful here, the above code will miss deleting an element 
> containing "Name=" if there are two in a row.  Look at this simple 
> example where we attempt to delete elements equal to 2:
> 
> ###
> 
>  >>> a=[1,2,1,2]
>  >>> for i,x in enumerate(a):
> ..  if x==2:del a[i]
> ..
>  >>> a
> [1, 1]
>  >>> #
>  >>> # ok that looks right, but watch this
>  >>> #
>  >>> b=[2,2,1,1]
>  >>> for i,x in enumerate(b):
> ..   if x==2: del b[i]
> ..
>  >>> b
> [2, 1, 1]
> 
> ###
> 
> After deleting element 0 in b, all the elements "slid down" one place 
> and the 2nd 2 that was in b is now in position 0...but you are moving 
> on to index 1 with the enumerate loop:
> 
> [2, 2, 1, 1]
>   ^
>   enumerate is at index 0
> 
> we delete element 0
> 
> [2, 1, 1]
>  ^
>  enumerate is at index 1 and the 2 that was at position 1 is now at 
> position 0
> 
> An alternative is to use a list comprehension, keeping only the 
> elements that are not 2. As is shown, you can replace the list you are 
> filtering with the filtered result:
> 
> ###
> 
>  >>> b=[2,2,1,1]
>  >>> b=[x for x in b if not(x==2)]
>  >>> b
> [1, 1]
> 
> ###
> 
> /c
> 
> 
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python 2.4 IDLE Windows 2000

2004-12-20 Thread Jacob S.
Ah, hah!

Okay, everyone! It took two things.

1) Delete .idlerc directory
2) Uninstall and reinstall python2.4

Why I had to do step two is beyond me, but I've got it settled now!
Thank you,
Jacob Schmidt

>
> "Jacob S." <[EMAIL PROTECTED]>
>
> > Gee,
> > I think I'm going to burst out in tears.
> > Mike Hansen gave the solution to the very problem I'm having, yet, when
> > I
> > used the console version and deleted the custom color theme, it stopped
> > giving me error messages, but it still won't start up without the
> > console.
> >
> > I'm am still stunted of my python 2.4 experience.
> > Help, please!!!
> >
> > Desperate,
> > Jacob
>
>
> Can you open IDLE and reset the color options to the defaults?  I believe
that's how I solved it.
>
> If not, there should be some configuration files, plain text files with
names like "*.def" in your idlelib directory.  Here's the path to one of
several on my machine:
> C:\Python23\Lib\idlelib\config-highlight.def
>
> I am not sure if you can safely delete these, but reverting them to the
default configuration should work (I think).
>
> Caution: I am not an expert in IDLE, Python, or... even life.
>
> EJP
>
>
>

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Registry Stuff

2004-12-21 Thread Jacob S.
Hi,

A little while ago, someone posted a message about an error and
something about modifying the windows registry key HKEY_CURRENT_USER\Control
Panel\Desktop so that the value Wallpaper was changed periodically. I wonder
if anyone could tell me how to do that? I tried something, and it didn't
work, and the documentation on _winreg is not very helpful to me. Any help
is appreciated. : )

Jacob Schmidt

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Popen? or something else

2004-12-22 Thread Jacob S.
Hi!

I just wondered why you included the time.localtime(time.time()) in the
defining of today.
Doesn't the default time.gmtime() work okay?

def gettoday():
import time
today = time.strftime('%Y%m%d%H')
return today

Jacob Schmidt

> Rumor has it that Ertl, John may have mentioned these words:
> >All,
> >
> >I hate to ask this but I have just installed 2.4 and I need to get some
info
> >from a subprocess (I think that is correct term).
> >
> >At the Linux command line if I input dtg I get back a string representing
a
> >date time group.  How do I do this in Python?  I would think Popen but I
> >just don't see it.
>
> It could, but there's also a better (IMHO), 'pythonic' way, something like
> this:
>
> def gettoday():
>
>   import time
>   today = time.strftime('%Y%m%d%H',time.localtime(time.time()))
>   return (today)
>
> >$ dtg
> >2004122212
>
> If you wanted to use popen, it would look rather like this:
>
> import os
> dtg_s = os.popen("/path/to/dtg").readlines()[0]
>
> But this may use more system resources (spawning child shells & whatnot)
> than doing everything internally with the time module in Python.
>
> HTH,
> Roger "Merch" Merchberger
>
> --
> Roger "Merch" Merchberger   | A new truth in advertising slogan
> SysAdmin, Iceberg Computers | for MicroSoft: "We're not the oxy...
> [EMAIL PROTECTED]  | ...in oxymoron!"
>
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
>
>

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Comments appreciated

2004-12-26 Thread Jacob S.
> The only thing that's missing is that this script can't handle paths
> like ~/dir/junkthis

I believe you're looking for os.path.expanduser("~/dir/junkthis")

BTW, trashcan IS a module level variable because it's defined at the module
level. Why it says it's local is beyond me.

HTH,
Jacob Schmidt

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] re.compile and objects - what am doing wrong?

2004-12-27 Thread Jacob S.
Hi,

[Blah,blah,blah,text cut]

>
> #! /usr/bin/python
> import string, re
First, I like to use string methods instead of importing the string module,
so let's get rid of that.

> dict1={}
> dict2={}
> inputFile1 = open("rough.txt", "rb")
> inputFile2 = open("polished.txt", "rb")
> for row in inputFile1.readlines():

Next, in some recent python version, they have made files iterators,
so you don't have to call the method readlines() on the file--you can just
use  for row in inputFile1:

> words = string.split(row,"\t")

We change this to use string methods--  words = row.split("\t")

> dict1[words[0]]=words[1]
>
> for row in inputFile2.readlines():
> words = string.split(row,"\t")
> dict2[words[0]]=words[1]

Do all of the same stuff we just did to the above section.

> outFile1 = open ("rough.out", "w")
> outFile2 = open ("polish.out", "w")
> polishKeys=dict2.keys()
> roughKeys=dict1.keys()
> for key in polishKeys:
> searchPat=re.compile("%s") % key # Doesn't work

Now, what you seem to be using here is % formatting.
The first thing I see wrong -- you should put the % key inside the
parenthesis
with the string so it reads re.compile("%s" % key)

The next thing, I'm not so sure of because of the lost indentation,
but I think that you are looking through all of roughKeys for each polishKey
and seeing if a particular string is in the roughKeys and print it. Right?

Having said that, I suggest we get rid of the re module and again use string
methods.
So, we use this.

# I get rid of % formatting because key is already a string!
for searchPat in polishKeys:
for  rKey in roughKeys:
if searchPat in rKey:
print searchPat+""+rKey

> outFile1.close()
> outFile2.close()
> inputFile1.close()
> inputFile2.close()

Having said all of that, I see one more thing--Why on earth use dictionaries
if all you're using is the list of keys?
Why not just use lists?
So, the script as I see it is:

 #! /usr/bin/python

roughkeys = []
polishkeys = []
inputFile1 = open("rough.txt", "rb")
inputFile2 = open("polished.txt", "rb")

for row in inputFile1:
roughkeys.append(row.split("\t")[0])
for row in inputFile2:
polishkeys.append(row.split("\t")[0])


outFile1 = open ("rough.out", "w")
outFile2 = open ("polish.out", "w")

for key in polishkeys:
for rkey in roughkeys:
if key in rkey:
print key+""+rkey

outFile1.close()
outFile2.close()
inputFile1.close()
inputFile2.close()


But Even better. As I ramble on, I see that list comprhensions can make
things easier!

 #! /usr/bin/python

inputFile1 = open("rough.txt", "rb")
inputFile2 = open("polished.txt", "rb")

roughkeys = [row.split("\t")[0] for row in inputFile1]
polishkeys = [row.split("\t")[0] for row in inputFile2]

outFile1 = open ("rough.out", "w")
outFile2 = open ("polish.out", "w")

for key in polishkeys:
for rkey in roughkeys:
if key in rkey:
print key+""+rkey

outFile1.close()
outFile2.close()
inputFile1.close()
inputFile2.close()

Does this work? Does it help? It was fun!

Jacob Schmidt

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] O.T.

2004-12-27 Thread Jacob S.
I hate to sound weird...

But who are you all, what are you're ages, what do you do, marriage status,
etc?
You obviously don't have to answer, I'm just curious who I'm boldly sending
emails to.

Jacob Schmidt

P.S.
I'm a student. 14 years. Play the piano better than I write scripts. Single.
etc.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] O.T.

2004-12-27 Thread Jacob S.
> Btw I'm single as well so if your sister looks like Salma Hayek please
> send her my gorgeous picture.

giggle,giggle,giggle...

I don't know who Salma Hayek is or what she looks like, but I can almost
assure you that my sister doesn't look like her.
My sister is 29 as well, but I think she's had enough of men and has decided
to stay single for the rest of her life. She now lives in my mother's house
with rent money over due, several credit cards that have more on them than
they should, and 3 dogs and 3 cats. Somehow, I don't think that would
work... :)

Thanks,
Jacob Schmidt

PS - Gorgeous? No offense, but.  I'll have to show her your picture
anyway

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: O.T.

2004-12-28 Thread Jacob S.
> Season's Greetings Jacob and all the circus.
> Not to be nosy, Jacob, but is that 14 years old (or 14 yrs a student)?
>  Married at 14 might be a little wierd!

14 years old. I should have put " single (obviously) ", or something like
that.
However, where I live--Portland, IN--the high school kids are already
engaged.
As for me, I couldn't get a girl if she even liked me. ; )

Jacob Schmidt


> I'm 60, been 25 years a-programming from 6502 asm through COBOL via
> Java ... now doing Windows Installer packages and perl scripting, from
> which i hope Python will be an escape or at least a diversion.
> Alan

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter packing confusion

2004-12-28 Thread Jacob S.
And this, right here, is why I like the grid method. ; )
I can easily place everything into a grid that I lay out before hand. I'm
used to coordinate systems.
I just don't have a firm grasp on the way pack works.

Jacob Schmidt


> First, thanks for the responses on my questions on using Tkinter for data
> entry from last week. Alan's and Harm's responses were very helpful.
>
> I'm now playing with a tiny application that does nothing except allow the
> user to enter a variable for processing.  It provides a default value, and
> three buttons: if the user hits CANCEL, the app terminates; if he hits OK,
> it prints out the entered variable; if he hts RESET, the data entered is
> reset to the default it had to start.
>
> The program logic works, but I'm totally lost on the pakcer layout
> manager.  What I want to see is a window with something like this (bear
> with my ascii art):
>
>   URL: [ http://www.somewhere.com/default ]
>
>   ++   +---+  ++
>   | Cancel |   | Reset |  | OK |
>   ++   +---+  ++
>
> What I'm getting is:
>
>URL:
> ++
> | Cancel |
> ++   [ http://www.somewhere.co ]
>   +---+++
>   | Reset || OK +
>   +---+++
>
>
> I'm sure my error lies in the packing, but I don't get it.
>
> I'm probably thinking abou it wrong, but my logic is this:
>
> I create a master frame, with two sub-frames, fBaseURL for the URL label
> and entry, and fButtons for the three buttons.
>
> In the fBaseURL frame, I pack the label widget to the top, and then the
> entry widget right (i.e., the entry widget to the right of the label
> widget).  Then I pack in the fBaseURL frame.
>
> In the fButtons frame, I pack in the "Cancel" button as the top of
> fButtons; then "Reset" to its right, and "OK" to its right.  Then I pack
> in the fButtons frame.
>
> Finally, I pack the parent frame.
>
> Well, I'm lost.  I'm trying dozens of variations, but just don't get it.
> Can someone explain to me how to pack in more simple terms?
>
> Here's my code:
>
> import Tkinter as tk
>
> class DEApp:
> def __init__(self):
>
> top=tk.Tk()
>
> self.DefaultBaseURL = "http://www.somewhere.com/default/";
> self.tvDefaultBaseURL=tk.StringVar()
> self.tvDefaultBaseURL.set(self.DefaultBaseURL)
>
> self.F=tk.Frame(top)
>
> fBaseURL=tk.Frame(self.F)
> lBaseURL=tk.Label(self.F, text="URL:")
> eBaseURL=tk.Entry(textvariable=self.tvDefaultBaseURL)
> lBaseURL.pack(side="top")
> eBaseURL.pack(side="right")
> fBaseURL.pack(side="top")
>
> fButtons=tk.Frame(self.F)
> bCancel=tk.Button(fButtons, text="Cancel", command=self.evCancel)
> bReset=tk.Button(fButtons, text="Reset", command=self.evReset)
> bOK=tk.Button(fButtons, text="OK", command=self.evOK)
> bCancel.pack(side="top")
> bReset.pack(side="right")
> bOK.pack(side="right")
> fButtons.pack(side="left")
>
> self.F.pack(side="top")
>
> def evCancel(self):
> print "Cancel hit"
> self.F.quit()
> return
>
> def evReset(self):
> print "Reset hit"
> self.tvDefaultBaseURL.set(self.DefaultBaseURL)
> return
>
> def evOK(self):
> print "OK hit"
> print "BaseURL is now", self.tvDefaultBaseURL.get()
> self.F.quit()
> return
>
> app = DEApp()
> app.F.mainloop()
>
>
>
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Output to a printer

2004-12-28 Thread Jacob S.
I'm definitely interested.

Jacob S.

> On 06.05.2004 21:06, Alan Gauld wrote:
> > THis is a problem in all programming languages on Windows because
> > basically Windows treats documents to be printed as graphics, so
> > you have to convert your document into something windows can print.
> > Its possible but painful (unless you find a module somewhere,
> > in which case let me know!)
> 
> I wrote a module that permits something like:
> 
>d = Win32PrinterDocument(printerName,spoolFile)
>f = file(inputfile)
>for line in f.readlines():
>   d.PrintLine(line.rstrip())
>d.endDoc()
> 
> Output will go to the specified Windows printer. Unfortunately I'll need 
> some time to make it ready for the public. Tell me if you are interested.
> 
> Luc
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] O.T.

2005-01-01 Thread Jacob S.
> In love with computers and programming since forever (well, maybe only
since 1968 or so...)
> Working as a professional programmer mostly since 1977. Languages I have
actually been paid to
> program in include
It seems like forever to someone who hasn't seen before 1990. : )

> Python is a lot of fun. The downside of that is that it makes Java and C++
(both of which I used to
> like a lot) look like a lot of work for little result.
I seem to hear that a lot on the list...

> I taught an Introduction to Programming with Python course for a local
adult ed program last fall
> and I will be teaching Python for Programmers in the spring.
I might need that...

> I like answering questions on the Tutor list because
> - They are like little puzzles to solve, and I like puzzles
> - I learn a lot - many times a question will be about a part of Python
that I don't know, so I learn
> enough to answer the questions
> - OK I admit it, it makes me feel smart :-)
That describes my experience on the tutor list exactly!

> If you really want to know more about me see my web site
> http://www.kentsjohnson.com
>
> Kent
>
> Jacob S. wrote:
> > I hate to sound weird...
> >
> > But who are you all, what are you're ages, what do you do, marriage
status,
> > etc?
> > You obviously don't have to answer, I'm just curious who I'm boldly
sending
> > emails to.
> >
> > Jacob Schmidt
> >
> > P.S.
> > I'm a student. 14 years. Play the piano better than I write scripts.
Single.
> > etc.
> >
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Help with testing.

2005-01-01 Thread Jacob S.
Hi,

A little while back somebody suggested doctesting, I think it was. Well,
anyway, it was the testing that took testing material from the doc strings
of functions in the format of an interpreter and the desired result (example
below). Could anyone help by pointing me to structured documentation on how
to use this, or even the name of the testing module(s)?
Even nicer, a way to put the testing code in a seperate module so all I have
to do is something like...

pseudocode

def test(obj):
## Testing particulars -- parameter is a module.function that has a
docstring with testing material

m = raw_input('What is the module? ')
n = raw_input('What is the function? ')
obj = eval(m+'.'+n)  ## Given that I'm the only one who will be using it and
I will not try to crack my computer...
test(obj)

Oh..
and the doc string example...


def function(a,b):
"""A function to do what you want it to.

>>> function('3','a')
'3a'
>>> function('ask','too')
'asktoo'
"""
return a+b




___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to put my functions in an array

2005-01-01 Thread Jacob S.
Hello.

I believe it was Danny Yoo who told me about mapping functions a while
back on the list...
It goes along these lines...

funct = {'Add Virt':addvirt,'Remove Virt':remvirt,'More
Stuff':more,"Extras":extra}
def addvirt():
pass
def remvirt():
pass
def more():
pass
def extra():
pass
def dispatch(name):
if name:
funct['name']()
else:
pass

print """\
Actions include:
Add Virt
Remove Virt
More Stuff
Extras
quit
"""
while 1:
command = raw_input("What do you want to do? ")
if command == 'quit':
break
dispatch(command)


HTH,
Jacob Schmidt

> def addvirt():
> pass
> def remvirt():
> pass
>
> PROVISION_ACTIONS=[('addvirt','Add Virt'),('remvirt','Remove Virt'),]
> formhandlers={}
>
> # this works
> formhandlers["addvirt"]=addvirt
> formhandlers["remvirt"]=remvirt
>
> # this does not work:
> for verb,verb_desc in PROVISION_ACTIONS:
> if callable(verb):
> formhandlers[verb]=verb
>
> I tried a few different syntaxes but to no avail... do I need things
> like: getattr()?
>
> Thanks alot
> Mohamed~
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to substitute an element of a list as a pattern forre.compile()

2005-01-01 Thread Jacob S.
Nobody explicitly mentioned that you're trying to make a pattern from an
integer and not a string, which, I believe is required. Also, Rich needs to
make the % formatting "%d"%x   instead of  "%s"%x  because he showed that x
is an integer not a string.

There's my two bits.
Jacob Schmidt


> Hi Group:
>
> I have Question:
> How can I substitute an object as a pattern in making
> a pattern.
>
> >>> x = 30
> >>> pattern = re.compile(x)
>
>
>
>
> My situation:
>
> I have a list of numbers that I have to match in
> another list and write them to a new file:
>
> List 1: range_cors
> >>> range_cors[1:5]
> ['161:378', '334:3', '334:4', '65:436']
>
> List 2: seq
> >>> seq[0:2]
> ['>probe:HG-U133A_2:1007_s_at:416:177;
> Interrogation_Position=3330; Antisense;',
> 'CACCCAGCTGGTCCTGTGGATGGGA']
>
>
> A slow method:
> >>> sequences = []
> >>> for elem1 in range_cors:
> for index,elem2 in enumerate(seq):
> if elem1 in elem2:
> sequences.append(elem2)
> sequences.append(seq[index+1])
>
> This process is very slow and it is taking a lot of
> time. I am not happy.
>
>
>
> A faster method (probably):
>
> >>> for i in range(len(range_cors)):
> for index,m in enumerate(seq):
> pat = re.compile(i)
> if re.search(pat,seq[m]):
> p.append(seq[m])
> p.append(seq[index+1])
>
>
> I am getting errors, because I am trying to create an
> element as a pattern in re.compile().
>
>
> Questions:
>
> 1. Is it possible to do this. If so, how can I do
> this.
>
> Can any one help correcting my piece of code and
> suggesting where I went wrong.
>
> Thank you in advance.
>
>
> -K
>
>
> __
> Do You Yahoo!?
> Tired of spam?  Yahoo! Mail has the best spam protection around
> http://mail.yahoo.com
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to substitute an element of a list as apattern forre.compile()

2005-01-01 Thread Jacob S.


> Actually %s formatting is very flexible and forgiving, it outputs str(x)
whatever x is. For example:
>   >>> for x in ['string', 10, True, [1,2,3] ]:
>   ...   print '%s' %x
>   ...
> string
> 10
> True
> [1, 2, 3]
>
> Kent

That's cool! I didn't know that. I guess I'm crazy... : )
(We already knew that here.)

Jacob

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] doctest

2005-01-01 Thread Jacob S.
Hi.

Okay, so I look at the documentation at it says (in my words):

"First Class - DocTest -- Make a test object with such and such attributes
that you can test.
Second Class - i don't remember the name - Make Jacob look stupid with big
words
Third Class - DocTestSuite - Convert a doctest object to a unittest object -
Okay... so how does that help?
Fourth Class - DocTestFinder - Find the docstrings that contain test code
and extract them."

So, my question, I guess, is How did the documentation help, and, How do I
have doctest test all of my module's function's docstrings?

Thanks in advance,
Jacob Schmidt

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] doctest

2005-01-01 Thread Jacob S.
I think I'm losing my mind...

Maybe it's because I go back to school the day after tomorrow?
The thing that helped the most was the -v parameter...

Even so, doctest doesn't seem to recognize the module level docstring.
It will run the test inside the functions, but it says there isn't a test on
the module level.
I put the docstring just like in the example at the link you provided...

Also, anything I can do... Presently, since I'm running windows xp, I would
have to hunt for the command prompt and type in the command

'"C:\python24\python.exe" "C:\documents and settings\jacob\desktop\working
python programs\testmodules.py" -v'

...or make a batch file to do it for me...
How can I make testmodules.py (shown below) append the -v to itself? Is
there a self.results or something in testmod?

## testmodules.py ###
import doctest

modtotest = 'FractionReducer2'

exec "import %s" % modtotest
doctest.testmod(eval(modtotest))
raw_input()
#


Thanks,
Jacob Schmidt


> What docs are you looking at?? The module docs at
http://docs.python.org/lib/module-doctest.html
> have a complete example of testing a module with a main function. Or you
can use the code in my last
> post.
>
> Kent
>
> Jacob S. wrote:
> > Hi.
> >
> > Okay, so I look at the documentation at it says (in my words):
> >
> > "First Class - DocTest -- Make a test object with such and such
attributes
> > that you can test.
> > Second Class - i don't remember the name - Make Jacob look stupid with
big
> > words
> > Third Class - DocTestSuite - Convert a doctest object to a unittest
object -
> > Okay... so how does that help?
> > Fourth Class - DocTestFinder - Find the docstrings that contain test
code
> > and extract them."
> >
> > So, my question, I guess, is How did the documentation help, and, How do
I
> > have doctest test all of my module's function's docstrings?
> >
> > Thanks in advance,
> > Jacob Schmidt
> >
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] doctest

2005-01-01 Thread Jacob S.
I forgot to mention...

When I explicitly define the variable __doc__ at the module level, it *does*
recognize the module level docstring.

> I think I'm losing my mind...
>
> Maybe it's because I go back to school the day after tomorrow?
> The thing that helped the most was the -v parameter...
>
> Even so, doctest doesn't seem to recognize the module level docstring.
> It will run the test inside the functions, but it says there isn't a test
on
> the module level.
> I put the docstring just like in the example at the link you provided...
>
> Also, anything I can do... Presently, since I'm running windows xp, I
would
> have to hunt for the command prompt and type in the command
>
> '"C:\python24\python.exe" "C:\documents and settings\jacob\desktop\working
> python programs\testmodules.py" -v'
>
> ...or make a batch file to do it for me...
> How can I make testmodules.py (shown below) append the -v to itself? Is
> there a self.results or something in testmod?
>
> ## testmodules.py ###
> import doctest
>
> modtotest = 'FractionReducer2'
>
> exec "import %s" % modtotest
> doctest.testmod(eval(modtotest))
> raw_input()
> #
>
>
> Thanks,
> Jacob Schmidt
>
>
> > What docs are you looking at?? The module docs at
> http://docs.python.org/lib/module-doctest.html
> > have a complete example of testing a module with a main function. Or you
> can use the code in my last
> > post.
> >
> > Kent
> >
> > Jacob S. wrote:
> > > Hi.
> > >
> > > Okay, so I look at the documentation at it says (in my words):
> > >
> > > "First Class - DocTest -- Make a test object with such and such
> attributes
> > > that you can test.
> > > Second Class - i don't remember the name - Make Jacob look stupid with
> big
> > > words
> > > Third Class - DocTestSuite - Convert a doctest object to a unittest
> object -
> > > Okay... so how does that help?
> > > Fourth Class - DocTestFinder - Find the docstrings that contain test
> code
> > > and extract them."
> > >
> > > So, my question, I guess, is How did the documentation help, and, How
do
> I
> > > have doctest test all of my module's function's docstrings?
> > >
> > > Thanks in advance,
> > > Jacob Schmidt
> > >
> > > ___
> > > Tutor maillist  -  Tutor@python.org
> > > http://mail.python.org/mailman/listinfo/tutor
> > >
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Sorting/filtering data, dictionary question & Re:OT

2005-01-03 Thread Jacob S.
> [Bill]
> I've seen list comprehensions, but I didn't understand how they worked.
> Since I understand how my function works, it's not so hard to figure out
> what your doing with this list comp. I guess the brackets ([]) signify a
list.
> Then the for loop is placed on the right-hand side and then on the left,
you
> append to "the list". I think the other list comprehensions I saw before
> were performing more operations, but this one is not that hard to figure
out.

You're thinking right. The syntax is supposed to be something like

[ altereditem for item in iterable if condition ]

So,
to get all the even numbers between 1 & 10

>>> a = [x for x in range(1,11) if x % 2 == 0]
>>> print a
[2,4,6,8,10]

For a much, much better explanation, I recommend Alan Gauld's tutorial, the
section which is relevant can be found here
http://www.freenetpages.co.uk/hp/alan.gauld/tutfctnl.htm

HTH,
Jacob Schmidt

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Lottery simulation

2005-01-07 Thread Jacob S.



Unfortunately as I overly enjoy 
writing scripts, I tend to spoil the recipients of the 
tutor.
IF you do not wish to have a 
complete answer, read someone else's email and not mine.
 
### Start 
code###
import random
 
participants = 10ask = 
[raw_input('What is the participant\'s name? ') for x in 
range(participants)]
 
for x in 
range(52):    a = range(1,100)
 
    people = 
{}    for i in 
ask:    randomnum = 
random.choice(a)    
a.remove(randomnum)  ## This is to keep from giving two people the same 
number    people[i] = 
randomnum        ##realnum = 
random.randint(1,100) ## 
Uncomment this to choose between 1&99 regardless of 
people    realnum = random.choice(people.values())  ## 
Uncomment this to make sure someone wins. (default)
 
    ## Check -- did anyone win?
 
    for x,y in 
people.items():    if y == 
realnum:    
print "%s just won the lottery! Congratulations! " % x    
raw_input("Press enter to run next week's lottery. ")
HTH and that I don't over help someone,
Jacob Schmidt


  
   
  I am new to python and only 
  created very simple programs so far.I would like to simulate a lottery draw 
  for 10 participants and run it for 52 weeks. The lottery numbers would have a 
  range of 1 to 99. Each person would have just one number (random) and play for 
  52 weeks. 
   
  Are there any starting ideas 
  for me to get going on this project either thru the tutor or searching for 
  snippets already created by fellow programmers??
   
  Thanks a lot in advance for all 
  the help,
   
  Regards,
   
   
  **
  Ümit N 
  Tezcan
  SEYAÅž- European Projects 
  Coordinator
  Tel   : 
  +90-212-2330920 (Ext.153)
  Fax  : 
  +90-212-233-0936
  Mob : 
  +90-533-337-7352
  E-mail: 
  [EMAIL PROTECTED]
  www : 
  seyas.com.tr
  **
  This email/fax message is for 
  the sole use of the intended recipient(s) and may contain confidential and 
  privileged information, or trade secrets.  Any unauthorized review, use, 
  disclosure or distribution of this email/fax is prohibited.  If you are 
  not the intended recipient, please contact the sender by email/fax and destroy 
  all paper and electronic copies of the original 
  message.
   
   
  
  

  ___Tutor maillist  
  -  
Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor



___Tutor maillist  
-  
Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] German Tutorials auf Deutsch

2005-01-07 Thread Jacob S.
## Spoken by Ara ##
Pardon to the non-german speaking (or readers) on the list.

Guten Tag. Mein Deutsch ist nicht so gut (ich habe keinen Deutsche in sieben
Jahren geschreiben). Mann kann Python Tutorials auf Deutsch heir
http://www.freenetpages.co.uk/hp/alan.gauld/german/index.htm
und
http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index_ger.html
und
http://starship.python.net/crew/gherman/publications/tut-de/
finden.
I habe Alan Gauld Tutorial vorgelesen. Es is gut und es abdeckt zimliche
viele Themen.

Ara
 Done with text ##
Great! Another chance to try and decipher another language!
Guten Tag = Good Morning
Mein = My
Deutsch = German (In *this* case, I guess)
ist = is
nicht = not
so = so
gut = good
ich = I
habe = have
keinen = learned?
Deutsche = German (I guess again)
in = in
sieben = seven? No, that can't be it...
Mann = many
kann = kind? (roughly?)
auf = of
heir = here OR at?
und = and
finden = used as end of a list
Es = it

That's all I can decipher

Thanks for some fun,
Jacob

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] import question

2005-01-07 Thread Jacob S.
> It should work as you describe it.
> Can you just clarify how you are doing this?
> Are you setting sys.path in the same program you
> are trying to run? Or is it set in a Python startup script?
>
> How do you run a.py? Are you importing it into an existing
> Python session(with sys.path set or are you ruinning the
> file standalone?
>
> Basically the only thing I can think of is that your setting
> of sys.path isn't being seen.
>
> Can you put a debug print statement to display sys.path
> just before the import b statement? That way we make
> absolutely certain Pythoncan see the folder.
>
> Alan G.

I had some similar trouble with site-packages when I tried to install psyco
a little while ago. Apparently, the sys.path does not include sub folders of
site-packages more than one branch deep. I fixed it by moving the main
module folder up into the site-package folder. IOW, from
C:\python24\lib\site-packages\psyco-1.3\psyco to
C:\python24\lib\site-packages\psyco. And then it worked! So maybe Ryan has
to specify the exact folder?

HTH,
Jacob Schmidt

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problem with a variable in a CGI program

2005-01-07 Thread Jacob S.
> line of white space. Could it be you have an unterminated
> string (missing close quotes) at the end of your program?
> 
> Alan G

I would like to add maybe a missing or extra parenthesis?
I have trouble with that alot.

Jacob
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] walking directories

2005-01-07 Thread Jacob S.
> Shouldn't that be os.path.walk()?

It says in the documentation (it might be the newer ones?):

"Note: The newer os.walk() generator supplies similar functionality and can
be easier to use."
 -- 6.2 os.path -- Common pathname manipulations

And, yet, the os.walk() function states (condensed):

blah, blah, blah
Gives you three things. A root, a *list* of directories, and a *list* of
files.

The first I see wrong is he is not assuming a list return.
Secondly, it also says in the documentation:

"""
dirpath is a string, the path to the directory. dirnames is a list of the
names of the subdirectories in dirpath (excluding '.' and '..'). filenames
is a list of the names of the non-directory files in dirpath. Note that the
names in the lists contain no path components. To get a full path (which
begins with top) to a file or directory in dirpath, do os.path.join(dirpath,
name).
"""

with particular attention paid to the exclusion of "." and ".."
It would be my guess that what he enters for toplevel is interfering also
with his output.

import os

directory = "."  # Perhaps not a valid pathname?
for root, dirs, files in os.walk(directory):
for x in files:
print os.path.join(root,x)

yields what I believe he wants...

HTH,
Jacob Schmidt


> And os.path.walk takes 3 arguments:
> the starting point
> a function that it calls
> a placeholder for arguments to the function
>
> A simple file printer is:
>
> >>> def f(arg, dir, names): print names
> >>> os.path.walk('.', f, None)
>
> In your case you want to write an f() that iterates
> over the names argument and opens each file, does
> a string replacement and closs the file again.
>
> You probably should do some validation on the name
> and file type too...
>
> Thats why I'd use find and sed...
>
> Alan G.
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (no subject)

2005-01-09 Thread Jacob S.

>Hello I can't seem to get the IDLE to start up in my windows XP by clicking
on the desktop icon. To start it I have to >drop a .py file on the icon. Any
ideas?

Danny just answered that, I believe... so next!

>Also I can't seem to get xp to recognize .py files belonging to python.
Right now the icons for .py is a windows default >and not the python icon.
So if I double click on a script that I want to work on it doesn't open the
idle. I have to open the >script from IDLE.  Any ideas on this problem?

Go to Control Panel, then to Folder Options. Click on the File Associations
tab (I think that's what it's called-whatever-it's the last one) You should
get a whole bunch of registered file types.

Go down to PY.
Click on on the advanced button
Double click on Open
Change the command to "C:\python24\pythonw.exe"
"C:\python24\lib\idlelib\idle.pyw" -n -e "%1"
(Obviously, you are either going to have to get Danny's suggestion working,
or you will have to change it from pythonw.exe to python.exe)

I often think it's best to present a way to run scripts straight from the
interpreter. So, change Edit with IDLE's command to
"C:\python24\python.exe" "%1" %*
Change the name on the same thing to "Open with Console" --- or something
like that..

Click Ok however many times is necessary...

Now--what you've just done is to set it up so that double clicking results
in IDLE starting up, and right clicking shows two commands Open & Open with
console (or the equivalent) Open with console should run the script straight
from the interpreter.
HTH,
Jacob
(Yes, I'm the same Jacob that Danny mentioned)


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Input to python executable code and design question

2005-01-09 Thread Jacob S.
I wondered when someone would ask something like this.

eval() is good and it can be done using it.
I wrote a -- IMHO -- really great functiongraphing program using vpython.
If you would like to see it, just reply and say so.

Pros and cons of calculating all first:
pro - easier to read code
con - user may feel insecure while the points are being calculated --
for example, say you type in a big, complicated function, and while the
computer
sits there and calculates the points, the user might feel that something is
wrong. On
the other hand, if you calculate each point on its own, points are
immediately put
on the screen so your user knows that the thing is working (if you get my
drift)

Please tell me what you are using to plot the points. (big grin) Vpython,
wxpython, what?
I'm curious--it's just someone else is working on a project that I'm working
on...

To help you out.
You need some sort of error checking to be sure that within your given range
you
won't get something like a math domain error.
Ex.

y = 'sqrt(x)'
x = -15
while -15<=x<=15:
print eval(y)

Gives you something like

Traceback blah, blah
...
Math domain error

If you want more suggestions, ask
Please, tell me how you're doing. It sounds interesting.

HTH,
Jacob Schmidt



> Hello
>
> I am trying to make a program that will plot functions. For that, I need
> to be able to get an input (the function to be plotted) and execute it.
> So, my question is, how do I use the input? I have found no way to
> convert the string to some kind of executable code.
>
> I did research the problem. And found two things, first, an
> unsatisfactory solution from:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52217
> The code there, by means I cannot understand at all, executes a string
> as code. To be usable I have to make my code a huge string. It is not
> very elegant.
>
> The second possible solution I found was using eval, compile and/or
> exec. But I do not understand what do they do, or how to use them, for
> the matter.
>
> Related to the program I intend to do, which design would you say is
> more intelligent: one that first calculates the whole function, stores
> it, and then plots it; or one that calculates-plots-calc.-plot, and so on?
>
> Thanks for any information, and for your time.
> Ismael
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Hi. Is there another mailing list like this one?

2005-01-09 Thread Jacob S.
The subject line says it all... Okay I'll add some.

I'm am bored and people are not asking enough questions/answering them to
keep my mind busy. Is there any other mailing list that I can subscribe to
like this one that lets anyone ask and answer questions?

Thanks in advance,
Jacob Schmidt

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Input to python executable code and design question

2005-01-09 Thread Jacob S.
I have grown to like VPython as the curve attribute really seems to do the
trick. If you get it working on a Tkinter canvas, I would like to see the
code as I haven't quite found a way to plot points on to one of those.  A
simple graph function in VPython... (it isn't the whole thing, believe
me...)  It already is more powerful than most graphing calculators--see
except comment.

def graphit(function):
m = curve(color=color.blue)
x = -15
while -15<=x<=15:
try:
m.append(pos=(x,eval(function),0))
except:
m = curve(color=color.red)  # This is to catch domain errors and
keep the curve from connecting points across asymptotes
x = x+0.05  # Yes it might be too high a precision, but I usually
use 0.005

I would like to see the executable. I don't know anything about Qbasic 4.5,
so I don't know if I could view the source, etc...
Tell me if you want cut and paste or attachment to see the program. By the
way, I don't want to give the impression that I'm anything much better
than a newbie myself. I just have a big mouth
It might help setting it up. It supports x functions and polar graphs as
well. Perhaps for the future I will try 3d graphs, since VPython supports
3d.
Hah! There's something I don't remember Tkinter Canvas being able to do.

Jacob

> Jacob S. wrote:
>
> >eval() is good and it can be done using it.
> >I wrote a -- IMHO -- really great functiongraphing program using vpython.
> >If you would like to see it, just reply and say so.
> >
> >
> Out of curiosity, I would like to see your program. There's always
> something to learn (and even more so for me, being a newbie)
>
> >Please tell me what you are using to plot the points. (big grin) Vpython,
> >wxpython, what?
> >I'm curious--it's just someone else is working on a project that I'm
working
> >on...
> >
> >
> At the moment, nothing :-s
> I'm learning Phyton, and I thought that this would be an interesting
> challenge. For what I've seen, Tkinter's Canvas 'could possibly' do the
> job. I still have to try it out. In case that didn't work, I was
> thinking in looking through wxpython.
>
>
> >To help you out.
> >You need some sort of error checking to be sure that within your given
range
> >you
> >won't get something like a math domain error.
> >
> >
> Yes, I thought that:
> try:
> #function
> exception:
> pass
>
>
> >If you want more suggestions, ask
> >Please, tell me how you're doing. It sounds interesting.
> >
> >
> At the moment, I have almost nothing. After John Fouhy's replies I have
> rewritten the few lines I had at least three times :o)
> It will be simple, I intend to support viewing specific parts of the
> function (instead of a fixed view), multiple graphs, perhaps an option
> to save/load functions. I first made a program like this in Qbasic 4.5,
> and thought doing it again in Python with an interface and more advanced
> options may be very entretaining. :-) I can send you the source/exe if
> you want (sadly you can't choose what you want to see in the exe
> version, the function must be hard-coded).
>
> Thanks
> Ismael
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Slightly OT - Python/Java

2005-01-10 Thread Jacob S.
> *sigh* I have no net at home at moment, which is very frustrating when
> I want to d/l documentation & editors. For the mo, it's all Notepad.
> Ick.

Call me stupid or whatever, but how do you send and receive mail to this
list?
Maybe someone on the list could send you Eclipse as an attachment maybe?

Jacob Schmidt

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor



[Tutor] My best GUI app so far.

2005-01-10 Thread Jacob S.
Here's the code. If you have time, look it over and give me suggestions for
improvement!
(big toothy grin)

### Start of Calculator.py ###
from __future__ import division
from Tkinter import *

class Application(Frame):
def ctb(self):
if self.shouldblank:
self.distext.set('')
self.shouldblank = False
def adddigit0(self):
self.ctb()
self.distext.set(self.distext.get()+'0')
def adddigit1(self):
self.ctb()
self.distext.set(self.distext.get()+'1')
def adddigit2(self):
self.ctb()
self.distext.set(self.distext.get()+'2')
def adddigit3(self):
self.ctb()
self.distext.set(self.distext.get()+'3')
def adddigit4(self):
self.ctb()
self.distext.set(self.distext.get()+'4')
def adddigit5(self):
self.ctb()
self.distext.set(self.distext.get()+'5')
def adddigit6(self):
self.ctb()
self.distext.set(self.distext.get()+'6')
def adddigit7(self):
self.ctb()
self.distext.set(self.distext.get()+'7')
def adddigit8(self):
self.ctb()
self.distext.set(self.distext.get()+'8')
def adddigit9(self):
self.ctb()
self.distext.set(self.distext.get()+'9')
def adddigitdot(self):
if not self.distext.get().count('.'):
self.ctb()
self.distext.set(self.distext.get()+'.')
def equal(self):
if self.action:
self.newnum = self.distext.get()
self.newnum = str(eval(self.oldnum+self.action+self.newnum))
self.distext.set(self.newnum)
self.oldnum = '0'
self.action = ''
self.shouldblank = True
def add(self):
if self.action:
self.equal()
self.oldnum = self.distext.get()
self.action = '+'
else:
self.oldnum = self.distext.get()
self.action = '+'
self.shouldblank = True
def subtract(self):
if self.action:
self.equal()
self.oldnum = self.distext.get()
self.action = '-'
else:
self.oldnum = self.distext.get()
self.action = '-'
self.shouldblank = True
def multiply(self):
if self.action:
self.equal()
self.oldnum = self.distext.get()
self.action = '*'
else:
self.oldnum = self.distext.get()
self.action = '*'
self.shouldblank = True
def divide(self):
if self.action:
self.equal()
self.oldnum = self.distext.get()
self.action = '/'
else:
self.oldnum = self.distext.get()
self.action = '/'
self.shouldblank = True
def clear(self):
self.action = ''
self.oldnum = '0'
self.distext.set('0')
self.shouldblank = True
def memrecall(self):
self.distext.set(self.memory)
self.shouldblank = True
def memminus(self):
self.memory = str(eval(self.memory+"-"+self.distext.get()))
self.shouldblank = True
def memplus(self):
self.memory = str(eval(self.memory+"+"+self.distext.get()))
self.shouldblank = True



def createWidgets(self):
self.distext = StringVar()
self.display =
Entry(self,textvariable=self.distext,width=22,justify='right')
self.display.grid(row=0,column=1,columnspan=4)

self.b0 =
Button(self,text='0',command=self.adddigit0,width=4,height=3)
self.b0.grid(row=5,column=1)
self.b1 =
Button(self,text='1',command=self.adddigit1,width=4,height=3)
self.b1.grid(row=4,column=1)
self.b2 =
Button(self,text='2',command=self.adddigit2,width=4,height=3)
self.b2.grid(row=4,column=2)
self.b3 =
Button(self,text='3',command=self.adddigit3,width=4,height=3)
self.b3.grid(row=4,column=3)
self.b4 =
Button(self,text='4',command=self.adddigit4,width=4,height=3)
self.b4.grid(row=3,column=1)
self.b5 =
Button(self,text='5',command=self.adddigit5,width=4,height=3)
self.b5.grid(row=3,column=2)
self.b6 =
Button(self,text='6',command=self.adddigit6,width=4,height=3)
self.b6.grid(row=3,column=3)
self.b7 =
Button(self,text='7',command=self.adddigit7,width=4,height=3)
self.b7.grid(row=2,column=1)
self.b8 =
Button(self,text='8',command=self.adddigit8,width=4,height=3)
self.b8.grid(row=2,column=2)
self.b9 =
Button(self,text='9',command=self.adddigit9,width=4,height=3)
self.b9.grid(row=2,column=3)
self.bdot =
Button(self,text='.',command=self.adddigitdot,width=4,height=3)
self.bdot.grid(row=5,column=2)
self.equalsign =
Button(self,text="=",command=self.equal,width=4,height=3)
self.equalsign.grid(row=5,column=3)
self.plussign =
Button(self,text='+',command=self.add,width=4,height=3)
self

Re: [Tutor] My best GUI app so far.

2005-01-10 Thread Jacob S.
text='9',command=lambda:
self.adddigit('9'),row=2,column=3)
>  self.makeButton(text='.',command=self.adddigitdot,row=5,column=2)
>  self.makeButton(text="=",command=self.equal,row=5,column=3)
>  self.makeButton(text='+',command=self.add,row=5,column=4)
>  self.makeButton(text="-",command=self.subtract,row=4,column=4)
>  self.makeButton(text='x',command=self.multiply,row=3,column=4)
>  self.makeButton(text='/',command=self.divide,row=2,column=4)
>  self.makeButton(text='ON/C',command=self.clear,row=1,column=4)
>  self.makeButton(text='MRC',command=self.memrecall,row=1,column=1)
>  self.makeButton(text="M-",command=self.memminus,row=1,column=2)
>  self.makeButton(text="M+",command=self.memplus,row=1,column=3)
>
>
>  def __init__(self, master=None):
>  Frame.__init__(self,master)
>  self.master.title("Calculator by Jacob, Inc.")
>  self.pack(fill='both')
>  self.oldnum = '0'
>  self.memory = '0'
>  self.action = ''
>  self.shouldblank = True
>  self.createWidgets()
>
> app = Application()
> app.mainloop()
> ### End of Calculator.py ###
>
>
>
> Jacob S. wrote:
> > Here's the code. If you have time, look it over and give me suggestions
for
> > improvement!
> > (big toothy grin)
> >
> > ### Start of Calculator.py ###
> > from __future__ import division
> > from Tkinter import *
> >
> > class Application(Frame):
> > def ctb(self):
> > if self.shouldblank:
> > self.distext.set('')
> > self.shouldblank = False
> > def adddigit0(self):
> > self.ctb()
> > self.distext.set(self.distext.get()+'0')
> > def adddigit1(self):
> > self.ctb()
> > self.distext.set(self.distext.get()+'1')
> > def adddigit2(self):
> > self.ctb()
> > self.distext.set(self.distext.get()+'2')
> > def adddigit3(self):
> > self.ctb()
> > self.distext.set(self.distext.get()+'3')
> > def adddigit4(self):
> > self.ctb()
> > self.distext.set(self.distext.get()+'4')
> > def adddigit5(self):
> > self.ctb()
> > self.distext.set(self.distext.get()+'5')
> > def adddigit6(self):
> > self.ctb()
> > self.distext.set(self.distext.get()+'6')
> > def adddigit7(self):
> > self.ctb()
> > self.distext.set(self.distext.get()+'7')
> > def adddigit8(self):
> > self.ctb()
> > self.distext.set(self.distext.get()+'8')
> > def adddigit9(self):
> > self.ctb()
> > self.distext.set(self.distext.get()+'9')
> > def adddigitdot(self):
> > if not self.distext.get().count('.'):
> > self.ctb()
> > self.distext.set(self.distext.get()+'.')
> > def equal(self):
> > if self.action:
> > self.newnum = self.distext.get()
> > self.newnum = str(eval(self.oldnum+self.action+self.newnum))
> > self.distext.set(self.newnum)
> > self.oldnum = '0'
> > self.action = ''
> > self.shouldblank = True
> > def add(self):
> > if self.action:
> > self.equal()
> > self.oldnum = self.distext.get()
> > self.action = '+'
> > else:
> > self.oldnum = self.distext.get()
> > self.action = '+'
> > self.shouldblank = True
> > def subtract(self):
> > if self.action:
> > self.equal()
> > self.oldnum = self.distext.get()
> > self.action = '-'
> > else:
> > self.oldnum = self.distext.get()
> > self.action = '-'
> > self.shouldblank = True
> > def multiply(self):
> > if self.action:
> > self.equal()
> > self.oldnum = self.distext.get()
> > self.action = '*'
> > else:
> > self.oldnum = self.distext.get()
> > self.action = '*'
> 

Re: [Tutor] My best GUI app so far.

2005-01-10 Thread Jacob S.
digit('1'),row=4,column=1)
>  self.makeButton(text='2',command=lambda:
self.adddigit('2'),row=4,column=2)
>  self.makeButton(text='3',command=lambda:
self.adddigit('3'),row=4,column=3)
>  self.makeButton(text='4',command=lambda:
self.adddigit('4'),row=3,column=1)
>  self.makeButton(text='5',command=lambda:
self.adddigit('5'),row=3,column=2)
>  self.makeButton(text='6',command=lambda:
self.adddigit('6'),row=3,column=3)
>  self.makeButton(text='7',command=lambda:
self.adddigit('7'),row=2,column=1)
>  self.makeButton(text='8',command=lambda:
self.adddigit('8'),row=2,column=2)
>  self.makeButton(text='9',command=lambda:
self.adddigit('9'),row=2,column=3)
>  self.makeButton(text='.',command=self.adddigitdot,row=5,column=2)
>  self.makeButton(text="=",command=self.equal,row=5,column=3)
>  self.makeButton(text='+',command=self.add,row=5,column=4)
>  self.makeButton(text="-",command=self.subtract,row=4,column=4)
>  self.makeButton(text='x',command=self.multiply,row=3,column=4)
>  self.makeButton(text='/',command=self.divide,row=2,column=4)
>  self.makeButton(text='ON/C',command=self.clear,row=1,column=4)
>  self.makeButton(text='MRC',command=self.memrecall,row=1,column=1)
>  self.makeButton(text="M-",command=self.memminus,row=1,column=2)
>  self.makeButton(text="M+",command=self.memplus,row=1,column=3)
>
>
>  def __init__(self, master=None):
>  Frame.__init__(self,master)
>  self.master.title("Calculator by Jacob, Inc.")
>  self.pack(fill='both')
>  self.oldnum = '0'
>  self.memory = '0'
>  self.action = ''
>  self.shouldblank = True
>  self.createWidgets()
>
> app = Application()
> app.mainloop()
> ### End of Calculator.py ###
>
>
>
> Jacob S. wrote:
> > Here's the code. If you have time, look it over and give me suggestions
for
> > improvement!
> > (big toothy grin)
> >
> > ### Start of Calculator.py ###
> > from __future__ import division
> > from Tkinter import *
> >
> > class Application(Frame):
> > def ctb(self):
> > if self.shouldblank:
> > self.distext.set('')
> > self.shouldblank = False
> > def adddigit0(self):
> > self.ctb()
> > self.distext.set(self.distext.get()+'0')
> > def adddigit1(self):
> > self.ctb()
> > self.distext.set(self.distext.get()+'1')
> > def adddigit2(self):
> > self.ctb()
> > self.distext.set(self.distext.get()+'2')
> > def adddigit3(self):
> > self.ctb()
> > self.distext.set(self.distext.get()+'3')
> > def adddigit4(self):
> > self.ctb()
> > self.distext.set(self.distext.get()+'4')
> > def adddigit5(self):
> > self.ctb()
> > self.distext.set(self.distext.get()+'5')
> > def adddigit6(self):
> > self.ctb()
> > self.distext.set(self.distext.get()+'6')
> > def adddigit7(self):
> > self.ctb()
> > self.distext.set(self.distext.get()+'7')
> > def adddigit8(self):
> > self.ctb()
> > self.distext.set(self.distext.get()+'8')
> > def adddigit9(self):
> > self.ctb()
> > self.distext.set(self.distext.get()+'9')
> > def adddigitdot(self):
> > if not self.distext.get().count('.'):
> > self.ctb()
> > self.distext.set(self.distext.get()+'.')
> > def equal(self):
> > if self.action:
> > self.newnum = self.distext.get()
> > self.newnum = str(eval(self.oldnum+self.action+self.newnum))
> > self.distext.set(self.newnum)
> > self.oldnum = '0'
> > self.action = ''
> > self.shouldblank = True
> > def add(self):
> > if self.action:
> > self.equal()
> > self.oldnum = self.distext.get()
> > self.action = '+'
> > else:
> > self.oldnum = se

Re: [Tutor] My best GUI app so far.

2005-01-11 Thread Jacob S.
d=self.divide,row=2,column=4)
 self.makeButton(text='ON/C',command=self.clear,row=1,column=4)
 self.makeButton(text='MRC',command=self.memrecall,row=1,column=1)
 self.makeButton(text="M-",command=self.memminus,row=1,column=2)
 self.makeButton(text="M+",command=self.memplus,row=1,column=3)


 def __init__(self, master=None):
 Frame.__init__(self,master)
 self.master.title("Calculator by Jacob, Inc.")
 self.pack(expand=True)
 self.oldnum = '0'
 self.memory = '0'
 self.action = ''
 self.shouldblank = True
 self.createWidgets()

app = Application()
app.mainloop()
###End of Calculator.py###


> Jacob S. wrote:
> > Great! I took the improvements you gave me an added support for keys (So
you
> > can type in 1.25+2= instead of having to type the buttons.) As always, I
> > encourage improvements to my code. Maybe that will be my disclaimer... I
> > have always liked and wanted to adopt Liam's.
> >
> > Oh, by the way, I'm not trying to make you go blind, it's just I don't
tend
> > to worry about *my* eyesight and in my subconcious I'm just not
considerate
> > enough to implement healthy eye habits. sorry...
>
> I exagerated. I don't really think it is an eye health issue. I do think
that careful use of white
> space can greatly enhance the readability of your code, which is good for
others who might be
> reviewing it, and also for you when you come back to it later.
>
> > Okay, Jacob, reality check -- it's after midnight...
> > Here's the code.
>
> You can simplify the way you add in key bindings.
>
> First, you don't need to add the *args argument to all the handlers. You
know what the argument will
> be (an event object) and you don't want to use it, so you can just throw
it away in the lambdas.
> Kind of the opposite of what I did with adddigit - instead of adding an
argument, you throw one away. So
>lambda *x: self.adddigit('0',x)
> becomes
>lambda event: self.adddigit('0')
>
> There is no need for an extra loop to set up the key bindings. You have
all the information you need
> in makeButton. It could read like this:
>
>   def makeButton(self, text, command, row, column):
>   button = Button(self,text=text,command=command,width=4,height=3)
>   button.grid(row=row,column=column)
>   if len(text) == 1
>   self.bind_all(text,lambda x: command())
>
> Or you could pass in an optional argument for the key text so you can bind
to 'ON/C' etc.
>
> Nice work, by the way :-)
>
> Kent
>
> >
> > ###Start of Calculator.py###
> > from __future__ import division
> > from Tkinter import *
> >
> > class Application(Frame):
> >  def ctb(self):
> >  if self.shouldblank:
> >  self.distext.set('')
> >  self.shouldblank = False
> >
> >  def adddigit(self, digit, *args):
> >  self.ctb()
> >  self.distext.set(self.distext.get()+digit)
> >
> >  def adddigitdot(self,*args):
> >  if not self.distext.get().count('.'):
> >  self.ctb()
> >  self.distext.set(self.distext.get()+'.')
> >
> >  def equal(self,*args):
> >  if self.action:
> >  self.newnum = self.distext.get()
> >  self.newnum =
str(eval(self.oldnum+self.action+self.newnum))
> >  self.distext.set(self.newnum)
> >  self.oldnum = '0'
> >  self.action = ''
> >  self.shouldblank = True
> >
> >  def add(self,*args):
> >  self.handleOperator('+')
> >
> >  def subtract(self,*args):
> >  self.handleOperator('-')
> >
> >  def multiply(self,*args):
> >  self.handleOperator('*')
> >
> >  def divide(self,*args):
> >  self.handleOperator('/')
> >
> >
> >  def handleOperator(self, oper):
> >  if self.action:
> >  self.equal()
> >  self.oldnum = self.distext.get()
> >  self.action = oper
> >  else:
> >  self.oldnum = self.distext.get()
> >  self.action = oper
> >  self.shouldblank = True
> >
> >
> >  def clear(self):
> >  self.action = ''
> >  self.oldnum = '0&#

Re: [Tutor] My best GUI app so far.

2005-01-11 Thread Jacob S.
Ugggh, the code I sent looks ugly when it came back. Why does Outlook
Express wait until you receive mail to wrap the
text? Isn't there an on/off switch for the stupid wrapping that sucks and
starts working at the wrong time?

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] My best GUI app so far.

2005-01-11 Thread Jacob S.
> Ah, right you are. I should know better than to post untested code, it's
usually buggy!
>
> I think you need to do the same thing for add(), subtract(), multiply()
and divide(). For some
> reason I don't understand, for me add works from the keyboard and multiply
doesn't!?

The same thing happened to me. That's when I realized that we were using 'x'
for the text on the multiply button and binding 'x' to multiply(), whereas
both of us were trying to use '*' to initiate multiply().

If I don't like the * in the text of the button, I'll have to set up a
seperate binding. Here's the code again, a few things changed. -Added
binding of spacebar to clear function
   -Added binding of enter key to equal - for use with the
number off to the right of the keyboard.
   -Changed text on button so 'x' now reads '*'

As always, Feel free to give suggestions.

Thanks for helping out so much!
Jacob Schmidt

###Start of Calculator.py###
from __future__ import division
from Tkinter import *

class Application(Frame):
 def ctb(self):
 if self.shouldblank:
 self.distext.set('')
 self.shouldblank = False

 def adddigit(self, digit):
 self.ctb()
 self.distext.set(self.distext.get()+digit)

 def adddigitdot(self):
 if not self.distext.get().count('.'):
 self.ctb()
 self.distext.set(self.distext.get()+'.')

 def equal(self):
 if self.action:
 self.newnum = self.distext.get()
 self.newnum = str(eval(self.oldnum+self.action+self.newnum))
 self.distext.set(self.newnum)
 self.oldnum = '0'
 self.action = ''
 self.shouldblank = True

 def add(self):
 self.handleOperator('+')

 def subtract(self):
 self.handleOperator('-')

 def multiply(self):
 self.handleOperator('*')

 def divide(self):
 self.handleOperator('/')


 def handleOperator(self, oper):
 if self.action:
 self.equal()
 self.oldnum = self.distext.get()
 self.action = oper
 else:
 self.oldnum = self.distext.get()
 self.action = oper
 self.shouldblank = True


 def clear(self):
 self.action = ''
 self.oldnum = '0'
 self.distext.set('0')
 self.shouldblank = True

 def memrecall(self):
 self.distext.set(self.memory)
 self.shouldblank = True

 def memminus(self):
 self.memory = str(eval(self.memory+"-"+self.distext.get()))
 self.shouldblank = True

 def memplus(self):
 self.memory = str(eval(self.memory+"+"+self.distext.get()))
 self.shouldblank = True


 def makeButton(self, text, command, row, column):
 button = Button(self,text=text,command=command,width=4,height=3)
 button.grid(row=row,column=column)
 if len(text) == 1:
 self.bind_all(text,lambda x: command())


 def createWidgets(self):
 self.distext = StringVar()
 self.display
=Entry(self,textvariable=self.distext,width=22,justify='right')
 self.display.grid(row=0,column=1,columnspan=4)

 self.makeButton(text='0',command=lambda *x:
self.adddigit('0'),row=5,column=1)
 self.makeButton(text='1',command=lambda *x:
self.adddigit('1'),row=4,column=1)
 self.makeButton(text='2',command=lambda *x:
self.adddigit('2'),row=4,column=2)
 self.makeButton(text='3',command=lambda *x:
self.adddigit('3'),row=4,column=3)
 self.makeButton(text='4',command=lambda *x:
self.adddigit('4'),row=3,column=1)
 self.makeButton(text='5',command=lambda *x:
self.adddigit('5'),row=3,column=2)
 self.makeButton(text='6',command=lambda *x:
self.adddigit('6'),row=3,column=3)
 self.makeButton(text='7',command=lambda *x:
self.adddigit('7'),row=2,column=1)
 self.makeButton(text='8',command=lambda *x:
self.adddigit('8'),row=2,column=2)
 self.makeButton(text='9',command=lambda *x:
self.adddigit('9'),row=2,column=3)
 self.makeButton(text='.',command=self.adddigitdot,row=5,column=2)
 self.makeButton(text="=",command=self.equal,row=5,column=3)
 self.makeButton(text='+',command=self.add,row=5,column=4)
 self.makeButton(text="-",command=self.subtract,row=4,column=4)
 self.makeButton(text='*',command=self.multiply,row=3,column=4)
 self.makeButton(text='/',command=self.divide,row=2,column=4)
 self.makeButton(text='ON/C',command=self.clear,row=1,column=4)
 self.makeButton(text='MRC',command=self.memrecall,row=1,column=1)
 self.makeButton(text="M-",command=self.memminus,row=1,column=2)
 self.makeButton(text="M+",command=self.memplus,row=1,column=3)


 def __init__(self, master=None):
 Frame.__init__(self,master)
 self.master.title("Calculator by Jacob, Inc.")
 self.pack(expand=True)
 self.bind

Re: [Tutor] My best GUI app so far.

2005-01-11 Thread Jacob S.
I guess my next big thing is to try to make a copy of a TI - 36X Solar -- 
That will be an undertaking for me.
First I'll have to research the buttons to see what all they do. Then, I'll
have to do all of the text and command changes on the buttons as part of the
command of the second and third funtion buttons. Eww. This is quickly
getting difficult - and interesting!  There's probably something illegal
about copying a  trademarked calculator. Of course, if I make sure I don't
make myself the author, or put my names on it... Oh, and posting the code is
just like sharing the calculator I bought, right? Yeah, I love loopholes.
Anyway, I don't think it will matter because this is too trivial.
(Sound of hands rubbing together in anticipation of making such a big
thing.)
I'll post some code as soon as it's stable.

Jacob Schmidt



> Jacob S. wrote:
> > Exception in Tkinter callback
> > Traceback (most recent call last):
> >   File "C:\Python24\lib\lib-tk\Tkinter.py", line 1345, in __call__
> > return self.func(*args)
> > TypeError: () takes exactly 1 argument (0 given)
> >
> > I got this error when trying to send command = lambda x:
self.adddigit('1')
> > to makeButton - and for all of the
> > rest of the digits, too. The way I fixed it was to again put *x in from
of
> > the x in lambda - but I left it out in the key binding.
> > The reason it needs that is because the key binding sends a Tkinter
> > instance, event, to the second argument whereas
> > the button command does not. So to allow for both of them to use the
same
> > adddigit function I had to let the lambda in
> > the buttons to accept extra junk. I think.
>
> Ah, right you are. I should know better than to post untested code, it's
usually buggy!
>
> I think you need to do the same thing for add(), subtract(), multiply()
and divide(). For some
> reason I don't understand, for me add works from the keyboard and multiply
doesn't!?
>
> >
> > I also took out the list self.bl due to the fact that I am no longer
using
> > the list of lambdas in more than one place.
> > (I'm not sure I was before either)
> >
> > Oh,
> >
> > I get your
> > whitespace
> > and readibility
> > thing
> > too.  *grin*
>
> Cool. Neatness counts! :-)
>
> Kent
>
> >
> >  Here's the code again.
> >
> > ###Start of Calculator.py###
> > from __future__ import division
> > from Tkinter import *
> >
> > class Application(Frame):
> >  def ctb(self):
> >  if self.shouldblank:
> >  self.distext.set('')
> >  self.shouldblank = False
> >
> >  def adddigit(self, digit):
> >  self.ctb()
> >  self.distext.set(self.distext.get()+digit)
> >
> >  def adddigitdot(self):
> >  if not self.distext.get().count('.'):
> >  self.ctb()
> >  self.distext.set(self.distext.get()+'.')
> >
> >  def equal(self):
> >  if self.action:
> >  self.newnum = self.distext.get()
> >  self.newnum =
str(eval(self.oldnum+self.action+self.newnum))
> >  self.distext.set(self.newnum)
> >  self.oldnum = '0'
> >  self.action = ''
> >  self.shouldblank = True
> >
> >  def add(self):
> >  self.handleOperator('+')
> >
> >  def subtract(self):
> >  self.handleOperator('-')
> >
> >  def multiply(self):
> >  self.handleOperator('*')
> >
> >  def divide(self):
> >  self.handleOperator('/')
> >
> >
> >  def handleOperator(self, oper):
> >  if self.action:
> >  self.equal()
> >  self.oldnum = self.distext.get()
> >  self.action = oper
> >  else:
> >  self.oldnum = self.distext.get()
> >  self.action = oper
> >  self.shouldblank = True
> >
> >
> >  def clear(self):
> >  self.action = ''
> >  self.oldnum = '0'
> >  self.distext.set('0')
> >  self.shouldblank = True
> >
> >  def memrecall(self):
> >  self.distext.set(self.memory)
> >  self.shouldblank = True
> >
> >  def memminus(self):
> >  self.memory = str(eval(self.memory+"-"+self.d

Re: [Tutor] please help: conditional statement and printing element

2005-01-11 Thread Jacob S.
I think I speak for a few of us in the fact that we don't know if that's
close to the correct approach due to the fact that you haven't given us a
full line to look at. Is col[17] the last column? If so, take the code I
just sent and change the line to:

if line.startwith('25\t') and line.endswith('\t1'):

I add the tabs in to make sure that 25 and 1 is the only thing in the
column.
Oh, and add col[9], col[10], etc. to the "\t".join() call. Ooops, that
should also have brackets...

Here it is in full.

file1 = open('psl','r')
for line in file1:
if line.startswith('25') and line.endswith('1'):
line = line.split("\t")
print "\t".join([col[0],col[1],col[9],col[10]])
file1.close()

An alternative that seperates the column indices and the line qualifiers
from the code so they can easily be edited.
Ahh, lets change line to row.

##Beginning of code##
columns_to_print = [0,1,9,10,17]
beginning = '25'
ending = '1'

file1 = open('psl','r')
for row in file1:
if row.startswith(beginning) and row.endswith(ending):
row = row.split("\t")
printlist = [row[x] for x in columns_to_print]
print "\t".join(printlist)
file1.close()
## Ending of code ##

HTH,
Jacob Schmidt

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help: conditional statement and printing element

2005-01-11 Thread Jacob S.
coll is a string, 25 is an integer.

However, I would do it this way.

file1 = open('psl.txt','r')
for line in file1:
if line.startwith('25'):
line = line.split('\t')
print "\t".join(line[0],line[1],line[17])
file1.close()

This has the added advantage that if you have a big file, it will only take
the time
to split it if it meets the qualifications. i.e. if it starts with '25'
The only way that the advantage would not work is if the string method
startswith
takes more time to run than splitting and searching the first index for a
value. But I
doubt that very much.

HTH,
Jacob Schmidt


> Dear group,
>   For some reason my brain cannot think of any other
> option than what I have in my script. Could any one
> please help me in suggesting.
>
> What I have : (File name : psl)
> 22 2 457:411 25 0
> 25 0 457:411 25 0
> 25 0 457:411 25 0
> 25 0 457:411 25 0
> 25 0 457:411 25 0
> 25 0 457:411 25 0
> 25 0 457:411 25 0
> 25 0 457:411 25 0
> 25 0 457:411 25 0
> 22 0 457:411 25 0
> 25 0 457:411 25 0
> 25 0 457:411 25 0
> 24 1 457:411 25 0
> 22 0 457:411 25 0
> 21 0 457:411 25 0
> 25 0 457:411 25 0
> 25 0 457:411 25 0
>
>
> What to do:
> I want to print values that are 25 in column 1 and not
> the other values such as 24,22,21 etc.
>
>
> My script:
> >>> for i in range(len(psl)):
> col = split(psl[i],'\t')
> col1 = col[0]
> if col1 == 25:
> print col[0]+'\t'+col[1]+'\t'+col[17]
>
>
> >>>
>
> Result: I get nothing. Am I doing something very
> wrong. Why isnt if col1 == 25: functional.
>
> My idea is to check if col[0] == 25: then print
> columns 1,18 etc.
>
> Can you please help me.
>
> Thanks
> K
>
> __
> Do You Yahoo!?
> Tired of spam?  Yahoo! Mail has the best spam protection around
> http://mail.yahoo.com
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] My best GUI app so far.

2005-01-11 Thread Jacob S.
> > Great! I took the improvements you gave me an added support for keys (So
you
> > can type in 1.25+2= instead of having to type the buttons.) As always, I
> > encourage improvements to my code. Maybe that will be my disclaimer... I
> > have always liked and wanted to adopt Liam's.
>
> Here's a few thoughts  :)
>
>
>
> >  def equal(self,*args):
> >  if self.action:
> >  self.newnum = self.distext.get()
> >  self.newnum =
str(eval(self.oldnum+self.action+self.newnum))
> >  self.distext.set(self.newnum)
> >  self.oldnum = '0'
> >  self.action = ''
> >  self.shouldblank = True
>
>
> Instead of using text representations of the operators, and eval()ing
> a string, why not use the operator module?
>
> Your operator keys can set self.action to be operator.add,
> operator.subtract, etc; then your equal() function becomes
>
>  def equal(self, *args):
>  if self.action:
>  self.newnum = self.distext.get()
>  self.newnum= str(self.action(float(self.oldnum), \
>  float(self.newnum)))
>  self.distext.set(self.newnum)
>  self.oldnum = '0'
>  self.action = ''  # I'd actually prefer None here...
>  self.shouldblank = True
>
> >
> >  def add(self,*args):
> >  self.handleOperator('+')
>
> becomes
>
>  def add(self, *args):
>  self.handleOperator(operator.add)
>
> The handleOperator() function can stay the same.
>
>
> >  def clear(self):
> >  self.action = ''
> >  self.oldnum = '0'
> >  self.distext.set('0')
> >  self.shouldblank = True
>
> As I mentioned in a comment above, I'd prefer to use None for
> self.action when it's unset.  There's no real practical difference,
> but conceptually it's more accurate to use a null-object than to use
> an empty string.  Minor style point, I know, but you *did* ask for
> advice. ;)
>
> >  def memminus(self):
> >  self.memory = str(eval(self.memory+"-"+self.distext.get()))
> >  self.shouldblank = True
> >
> >  def memplus(self):
> >  self.memory = str(eval(self.memory+"+"+self.distext.get()))
> >  self.shouldblank = True
>
> Why use eval() here?  You could just as easily do these as
>
>  def memminus(self):
>  self.memory = str(float(self.memory) - \
> float(self.distext.get()))
>  self.shouldblank = True
>
> I try to avoid using eval() wherever possible, which is almost
> everywhere. ;)  There's a huge security hole in using eval() on
> arbitrary strings, and it's not the greatest performance either.
> (Each invocation of eval() will generate bytecode and create a code
> object that does essentially the same thing as my explicit conversion
> code does, so by doing it manually you save a parsing/compiling step.)
>   You're not eval()ing arbitrary strings here, at least, but it's
> still good practice to only use eval() when absolutely necessary.
>
>
> >  def __init__(self, master=None):
> >  Frame.__init__(self,master)
> >  self.master.title("Calculator by Jacob, Inc.")
> >  self.pack(expand=True)
> >  m = lambda x: self.adddigit(x)
> >  self.bl = [lambda *x: self.adddigit('0',x),
> > lambda *x: self.adddigit('1',x),
> > lambda *x: self.adddigit('2',x),
> > lambda *x: self.adddigit('3',x),
> > lambda *x: self.adddigit('4',x),
> > lambda *x: self.adddigit('5',x),
> > lambda *x: self.adddigit('6',x),
> > lambda *x: self.adddigit('7',x),
> > lambda *x: self.adddigit('8',x),
> > lambda *x: self.adddigit('9',x)]
> >  for y in range(10):
> >  self.bind_all(str(y),self.bl[y])
> >  self.bind_all("+",lambda x: self.add(x))
> >  self.bind_all("-",lambda x: self.subtract(x))
> >  self.bind_all("*",lambda x: self.multiply(x))
> >  self.bind_all("/",lambda x: self.divide(x))
> >  self.bind_all("=",lambda x: self.equal(x))
> >  self.bind_all(".",lambda x: self.adddigitdot(x))
>
> There's absolutely no point to doing lambda x: somefunc(x) -- all
> you're doing is adding an extra layer of function call.  You can
> replace all of those with something like
>
> self.bind_all('+', self.add)
>
> And actually, because I'm not fond of lambda to begin with, I'd
> redefine your adddigit() method:
>
>  def make_adddigit_callback(self, digit):
>  def adddigit(*args):
>  self.ctb()
>  self.distext.set(self.distext.get()+digit)
>  return adddigit
>
> (You may not need the *args above, if the button callback is expected
> to be zero parameters -- I don't use Tkinter, so I'm not sure
> offhand.)  Then you

Re: [Tutor] Time script help sought!

2005-01-11 Thread Jacob S.
Would this do the trick?

stringtime = '12:34'  ## This is the column with the time  12:34 is an
example

time = stringtime.split(":")
time = [int(x) for x in time]
time.reverse()
seconds = time[0]+time[1]
try:
seconds += time[2]
except IndexError:
pass
print seconds

I'm almost sure there is a better way to do this.

Jacob Schmidt

> Thanks for this Everyone!
>
> Trying to work with all the stuff folks are giving me on this i a have
> come across a problem... down
> the line i notice that some of the times will also have an hour as well
> as in H:M:S (e.g. 1:22:40)
>
> so in some cases i would need to convert H:M:S to sec and some just M:S
>
>
> or should there just be a fun that passes all the times and converts
> them to H:M:S first and
> just appends a 00:  ((e.g. 00:02:07) if there is no hour value?
>
> cheers,
>
> kevin
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Time script help sought!

2005-01-11 Thread Jacob S.
I don't think so. (correct me if I'm wrong) The datetime module is for
making date and time instances that you can add and subtract to get
timedelta objects. Other things involved of course, but I don't think it has
anything to do with parsing and
pretty printing columns of times. I'm not sure, don't quote me on it.

Jacob


> I also notice that there is the is the 'datetime' module, which is new
> to version 2.3, which i now have access to. My feeling is that this
> will do much of what i want, but i can't get my head round the standard
> library reference stuff
>
> http://www.python.org/doc/lib/module-datetime.html
>
> I don't have any texts with me either and it probably is too new to be
> in the Python Standard Library book by Fredrik Lundh or the Python
> Essential Reference by  David Beazley
>
>
> -kevin-
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Time script help sought!

2005-01-11 Thread Jacob S.
> The old mx.datetime module (on which Python's datetime module is based, I
> presume) had a strptime() function which would basically do the reverse
(you
> specify a format string and it would attempt to parse the date string you
give
> it).  Unfortunately, Python's datetime module doesn't have such a
function.
> This is the best way I have found of doing it:

Fortunately, the time module does.

time.strptime

HTH,
Jacob

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Time script help sought!

2005-01-11 Thread Jacob S.
Forgot to mention -- screwed up before. In my proposed try/except block,
etc. I forgot to do unit conversion.

Jacob

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] TypeError I don't understand

2005-01-12 Thread Jacob S.
Danny Yoo solved the problem, but I would like to suggest something.

target = '*' + str(living_species[counter]) + '*'
replacement = '(' + target + ',*' + str(current_species) +  '*)'

change these lines to

target = "*%s*" % (living_species[counter])
replacement = "(%s*%s*)" % (target,current_species)

It will (obviously) work your way, but I think that string formatting
simplifies and improves readability, IMHO.

HTH,
Jacob Schmidt


> Dear All,
>
> python gives me a type error that I don't understand
>
> running my program gives me "TypeError: len() of unsized object"
> but I know I that the object whose length I asked for is a list and
> therefor a sized type
>
> here is a sample of the output:
>
> type (living_species) : 
> len(living_species) : 1
> Traceback (most recent call last):
>File "new_prog1b.txt", line 15, in ?
>  while counter < len(living_species):
> TypeError: len() of unsized object
>
> here is the code:
>
> import random
>
> living_species = [0]
> dead_species = []
> tree = "*0*"
>
> current_time = 0
> end_of_time = 25
> current_species = 0
> branching_probablity = .1
> extinction_probablity = .1
>
> while current_time < end_of_time:
>  counter = 0
>  while counter < len(living_species):
>  if random.random() < branching_probablity:
>  current_species += 1
>  living_species.append(current_species)
>  target = '*' + str(living_species[counter]) + '*'
>  replacement = '(' + target + ',*' + str(current_species) +
> '*)'
>  tree = tree.replace(target, replacement)
>  counter += 1
>  # PROBLEM HERE
>  print 'type (living_species) :',type(living_species) # proves
> living_species is a list
>  print 'len(living_species) :', len(living_species)# proves
> length living_species is a number
>  counter = len(living_species) - 1# python says TypeError: len()
> of unsized object
>  while counter >- 1:
>  if random.random() < extinction_probablity:
>  dead_species = dead_species.append(counter)
>  living_species = living_species.remove(counter)
>  counter -= 1
>  current_time += 1
>
> print living_species
> print dead_species
> tree = tree.replace('*','')
> print tree
>
> Thank You,
>
> Vincent
>
>  
> --
> PhD Candidate
> Committee on the Conceptual and Historical Studies of Science
> University of Chicago
>
> PO Box 73727
> Fairbanks, AK 99707
>
> wanATwalrusDOTus (replace AT with "@" and dot with ".")
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] spaces in print

2005-01-12 Thread Jacob S.
Don't forget the string method join()!

print "".join(['\n','siday_q',key,'.wav'])

It works too ;-) (though I like the string formatting better for this.)
Jacob

> 
> 
> when i print:
> 
>  print '\n','siday_q', key, '.wav'# event
> 
> 
> i get:
> 
> siday_q 515 .wav
> 
> 
> how can you eliminate the spaces to get:
> 
> siday_q515.wav
> 
> 
> ?
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to create a key-value pairs with alternative elementsin a list ... please help.

2005-01-12 Thread Jacob S.
> Problem:
> How do i capture every alternative element in list a:


Use Jeff Shannon's approach to get keys and vals.

> >>> keys = [] # create a list of all keys i.e a,b,c)
> >>> vals = [] # create a list of all values i.e 
>#appele,boy,cat etc.
> 
> >>> dict = {}
> 
> >>> dict = zip(keys,vals)


What is that?!?
your dict thing ain't workin'
This is verified code... HA,HA,HA,Ha, ha, ha 
Well... okay, it's only tested, not verified.

fulllist = ['a','apple','b','boy','c','cat']
keys = fulllist[::2]
vals = fulllist[1::2]
dictionary = dict(zip(keys,vals))

HTH,
Jacob


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Regular expression re.search() object . Please help

2005-01-13 Thread Jacob S.
I assume that both you and Liam are using previous-er versions of python?
Now files are iterators by line and you can do this.

openFile = open("probe_pairs.txt","r")
indexesToRemove = []
for line in openFile:
if line.startswith("Name="):
line = ''   ## Ooops, this won't work because it just changes what
line references or points to or whatever, it doesn't
##actually change the object
openFile.close()

I think this is a great flaw with using for element in list instead of for
index in range(len(list))

Of course you later put IMHO better solutions (list comprehensions,etc.) -- 
I just wanted to point out that files have been
iterators for a few versions now and that is being used more and more. It
also saves the memory problem of using big files
and reading them all at once with readlines.

Jacob

> Liam Clarke wrote:
>
> > openFile=file("probe_pairs.txt","r")
> > probe_pairs=openFile.readlines()
> >
> > openFile.close()
> >
> > indexesToRemove=[]
> >
> > for lineIndex in range(len(probe_pairs)):
> >
> >if probe_pairs[lineIndex].startswith("Name="):
> >  probe_pairs[lineIndex]=''
>
> If the intent is simply to remove all lines that begin with "Name=",
> and setting those lines to an empty string is just shorthand for that,
> it'd make more sense to do this with a filtering list comprehension:
>
>  openfile = open("probe_pairs.txt","r")
>  probe_pairs = openfile.readlines()
>  openfile.close()
>
>  probe_pairs = [line for line in probe_pairs \
>if not line.startswith('Name=')]
>
>
> (The '\' line continuation isn't strictly necessary, because the open
> list-comp will do the same thing, but I'm including it for
> readability's sake.)
>
> If one wants to avoid list comprehensions, you could instead do:
>
>  openfile = open("probe_pairs.txt","r")
>  probe_pairs = []
>
>  for line in openfile.readlines():
>  if not line.startswith('Name='):
>  probe_pairs.append(line)
>
>  openfile.close()
>
> Either way, lines that start with 'Name=' get thrown away, and all
> other lines get kept.
>
> Jeff Shannon
> Technician/Programmer
> Credit International
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] style question: when to "hide" variable, modules

2005-01-15 Thread Jacob S.
I'm not too sure about this...

Couldn't you make that a package?
Rename Backup.py to __init__.py
Put all of the modules in a folder named Backup
in your sys.path - Question: Does it have to be
in site-packages?

Well, there's my two bits,
Jacob

> During the recent discussion on jython, a poster
> brought up the good point that one should hide
> variables and modules to indicate that they are
> not for public use:
> 
> self.__for_internal_purposes = 5
> 
> __internal_stuff.py
> """
> This module only makes sense for use with 
> the parent module.
> """
> 
> So one could write several modules using these
> guidelines. One could then issue the command 
> from a shell pydoc internal_stuff, and sure enough,
> one gets a nice listing of all the methods with the 
> __methods listed first, signalling to someone who 
> hasn't written the program (or to the author who 
> returns to it a few years later), that one shouldn't 
> look at these methods when looking what is useful
> from the script.
> 
> My question is, how far should one take these guidlines?
> 
> I am working on an OO script with several modules that 
> backs up a hardrive. There will be about 10 modules, but 
> really only *one* of them, called backup, would be used 
> as a pubilc interface. Should I name the rest of them things
> like __handle_archive.py, __file_system.py, and so on? That
> seems odd, since I have never seen this done before. However,
> it does have an elegance of clearly telling someone how to 
> hook into the modules.
> 
> Also, maybe more importantly, I want to know how to handle
> attributes that need to be shared. Imagine that there are around
> 20 attributes, such as the level the program runs at, and the number 
> of the disk being copied that need to be shared with different 
> modules.  Right now, my setup looks like this:
> 
> # this module is called backup.py
> 
> class Backup:
> 
>   __init__(self, verbose, level ):
>self.__make_objects()
>self.verbose = verbose
>self.level = level
>  
> 
>   def __make_objects(self):
> self.burn_obj = paxbac.burn.Burn(self)
> self.archive_obj = paxbac.archive.Archive(self)
> 
>   def get_disk(self):
> return self.__disk
> 
>def set_disk(self, the_num):
>   self.__disk = the_num
> 
>   def backup(self):
>  archive_obj.archive()
>  burn_obj.burn()
> 
> *
> 
> #this is aother module called burn.py
> 
> class Burn:
>   def __init__(self, main):
>   self.__main = main
> 
>   def burn(self):
>  cd_num = self.main.get_disk()
>  if self__main.level > 3:
> sys.stdout.write('Burning disk %s\n' %cd_num)
> 
> 
> 
> The main module backukp provides a number of public 
> methods that are really not public. For examle, no 
> one is going to want to use this module to find 
> out what disk the method is on. If I wanted to 
> be very strict with public and private variables
> and methods, I would have to:
> 
> 1. change burn.py to __burn.py
> 
> 2. create a module called __attributes.py, create an
> object in burn.py called self.__attributes_obj, and pass
> this object to each method.
> 
> These two steps seem to take things a bit far. On the other 
> hand, one could look at the set of modules and immediately
> know how to use them.
> 
> Thanks
> 
> Paul
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Lights game

2005-01-16 Thread Jacob S.
Kent's suggestions are great, but I wanted to add two.

> Hello list.
> 
> I'd really appreciate any comments, particulary regarding style 
> corrections. I'm a newbie...
> 
> Thanks!
> Ismael
> 
> 
> import random
> import tkMessageBox
> from Tkinter import *
> 
> class GUI:
> def __init__(self):
> self._crearGUI()
> 
> def _crearGUI(self):
> self.root = Tk()
> self.root.title("Lights")
> self.botones = [[0,0,0],[0,0,0],[0,0,0]]
> for i in range(3):
> for j in range(3):
> action = lambda n=i, m=j: self._accion(n,m)
> self.botones[i][j] = Button(self.root, height=5, 
> width=10, command=action)
> self.botones[i][j].grid(row=i, column=j, padx= 4, pady=4)
> 
> self._updateBotones()
> self.root.mainloop()
> 
> def _accion(self, i, j):
> self._click(i, j)
> try:
> self._checkWin()
> except ValueError:
> tkMessageBox.showinfo(title = "You won!", message = "You 
> rock, kid!")
> 
> if True == tkMessageBox.askyesno(title="What shall we do?", 
> message="Play another?"):
> self.root.destroy()
> lights.__init__() ## Is this... too ugly? Is there a 
> beter way?
> self.__init__()
> else:
> self.root.destroy()
> def _updateBotones(self):
> for i in range(3):
> for j in range(3):
> if lights.tablero[i][j] == True:
> self.botones[i][j].configure(bg="red")
> else:
> self.botones[i][j].configure(bg="grey")
> 
> def _click(self, i, j):
> lights.click(i,j)
> self._updateBotones()
> 
> def _checkWin(self):
> conteo = 0
> for i in range(3):
> for j in range(3):
> if lights.tablero[i][j] == True: conteo +=1


if lights.tablero[i][j] == True:
can be simplified to
if lights.tablero[i][j]:

> if conteo == 9:
> print "GANO"
> raise ValueError
>
> return
> 
> class Luces:
> def __init__(self):
> self.tablero = [[0,0,0],[0,0,0],[0,0,0]]
> self._hacerTablero()
>  
> def _hacerTablero(self):
> for i in range(3):
> for j in range(3):
> self.tablero[i][j] = not random.randint(0,1)

Why use
not random.randint(0,1)?
If it's random, wouldn't just
random.randint(0,1)
give the same result?

Why get a random number and then immediately return the opposite?
It's like resolving to write down heads if you flip tails, and tails if you
flip heads when you flip a coin! Why bother?
 
> def _cambiarCelda(self, i, j):
> self.tablero[i][j] = not self.tablero[i][j]
> 
> def _descartarNegativos(self, n):
> if n < 0:
> raise IndexError
> return n
> 
> def click(self, i,j):
> self._cambiarCelda(i,j)
> try:
> self._cambiarCelda(self._descartarNegativos(i-1), j)
> except IndexError:
> pass
> try:
> self._cambiarCelda(self._descartarNegativos(i+1), j)
> except IndexError:
> pass
> try:
> self._cambiarCelda(i, self._descartarNegativos(j-1))
> except IndexError:
> pass
> try:
> self._cambiarCelda(i, self._descartarNegativos(j+1))
> except IndexError:
> pass
> 
> if __name__ == '__main__':
> lights = Luces()
> lightsGUI = GUI()
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Posting a large amount of code?

2005-01-16 Thread Jacob S.
> > It would be a god excercise to extract all the p[ipe code into
> > a separate class and the GUI methods call those class methods
> > to get the work done. THis would allow for a fairly easy port
> > to a different GUI or even the creation of a command line
> > version, so you could do:

Actually according to the above paragraph, he suggests putting them all in
a seperate class. So pseudo-code...

class Pipe:
All things related to pipe program here.

class GUI:
def __init__(self):
self stuff defined etc.
def makeGuiStuff(self):
connetion = Pipe(initial variables)
make gui stuff here
put all button events such as
calculate(command = connection.calculate)
(I told you it was pseudo-code)

HTH,
Jacob

> You're exactly right setText() is a GUI method. I do have the pipe logic
all
> mixed up with the GUI code. Now that you point it out, most of my methods
> don't have a return statement. They are completely dependant on the GUI
> and wouldn't function without it. Virtually all the methods act directly
upon
> the GUI.
>
> If I'm  understanding you correctly, I should have methods more along the
> lines of this one (which is in my code now):
>
> def volCalc(self, ID, length):
> """Calculates the volume/gallons of water inside of
>the various pipe.
> """
> from math import pi
> gal = ((ID*.5)**2)*pi*(12*length)/(230.9429931)
> return gal
>
> It does it's 'job', return a result and is not effected  by the GUI at
all. I
> guess you could actually import this function into the interpreter and use
it
> without problems. But if you tried doing that with the other function
above
> (galCalc()) it wouldn't work out quite so well
>
> I'll have to see what I can do to take a step in this direction. It might
take
> my a little while :-)
>
> Thank you for your help!
>
> Bill
>
>
>
>
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need advice on streamlining code...

2005-01-17 Thread Jacob S.
I seem to always be the one to suggest this, but --
"String methods are better than using the string module because the string 
module has been ?deprecated? or will be soon. I think that is the word here. 
So, do this instead."

insideipgrepfd = os.popen("grep ifconfig_fxp0 /etc/rc.conf")
insideipgrep = insideipgrepfd.readline()  ## Says same thing below --  
readline() just reads first line
insideipfield, insideip = insideipgrep[0].strip().split("=")
insideipsplit = insideip.split()
insideipquads = insideipsplit[1].split(".")
insidemaskquads = insideipsplit[4].split(".")

And, heck, I know it wouldn't be that simple, but if the line stays the same 
but just the numbers change, you can do,

insideipgrepfd = os.popen("grep ifconfig_fxp0 /etc/rc.conf")
insideipgrep = insideipgrepfd.readlines()  ##Wait, if you're just using the 
first line use insideipgrepfd.readline()
insideipgrep = insideipgrep.lstrip("ifconfig_fxp0=\"inet ")
temp = insideipgrep.split(" netmask ")
insideipquads = temp[0].split(".")
insideipmaskquads = temp[1].split(".")

Warning, code just above is not very stable --  if the text of the line 
changes in anyway it won't work.

HTH,
Jacob Schmidt
The following block of code works, and provides the necessary output I'm
looking for...but I have a feeling that it's working through sheer brute
force and could be better:
   insideipgrepfd = os.popen("grep ifconfig_fxp0 /etc/rc.conf")
   insideipgrep = insideipgrepfd.readlines()
   insideipfield, insideip = string.split(string.strip(insideipgrep[0]), 
"=")
   insideipsplit = string.split(insideip, " ")
   insideipquads = string.split(insideipsplit[1], ".")
   insidemaskquads = string.split(insideipsplit[4], ".")

the line in /etc/rc.conf looks like:
ifconfig_fxp0="inet 172.31.2.100 netmask 255.255.255.0"
Any and all thoughts/pointers are appreciated.
   ~elh
--
Eric L. Howard   e l h @ o u t r e a c h n e t w o r k s . c o m

www.OutreachNetworks.com313.297.9900

JabberID: [EMAIL PROTECTED] Advocate of the Theocratic Rule
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Walking a directory

2005-01-17 Thread Jacob S.
Kent's suggestions are always my favorites, along with others, 
c.   --nevermind
To get the full path in your list-- change Kent's to this

import os
filelist = []
for root,directories,filenames in os.walk("Aircraft"):
   for filename in filenames:
   if filename.endswith("-set.xml"):
   filelist.append(os.path.join(root,filename))
for x in filelist:
   print x
What I want to do is rather simple, but I cannot find any good
documentation for something like this.
The directory structure is sort of like this:
Aircraft
A-10
+A-10cl-set.xml
+A-10fg-set.xml
For example Aircraft/A-10/A-10cl-set.xml
Now I want to loop though each aircrafts folder (such as A-10) and
find each *-set.xml file, get the aircraft part (such as A-10cl) and
add it to a list.
While this does seem simple, how is the question.
I know about the walk function, but cannot find any good examples for it.
--

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need advice on streamlining code...

2005-01-18 Thread Jacob S.
yeah, I wasn't sure about that readline/lines thing, cos I'm not sure
how popen works.
Well, I'm not positive about it either! But that doesn't mean that you can't 
comment out what you had, try this, and uncomment the previous if it doesn't 
work. I would imagine that it works because it seems to me if it can split 
the whole input, it can certainly split just one split deep!!! Anyway...

Jacob
On Mon, 17 Jan 2005 21:38:37 -0500, Jacob S. <[EMAIL PROTECTED]> wrote:
I seem to always be the one to suggest this, but --
"String methods are better than using the string module because the 
string
module has been ?deprecated? or will be soon. I think that is the word 
here.
So, do this instead."

insideipgrepfd = os.popen("grep ifconfig_fxp0 /etc/rc.conf")
insideipgrep = insideipgrepfd.readline()  ## Says same thing below --
readline() just reads first line
insideipfield, insideip = insideipgrep[0].strip().split("=")
insideipsplit = insideip.split()
insideipquads = insideipsplit[1].split(".")
insidemaskquads = insideipsplit[4].split(".")
And, heck, I know it wouldn't be that simple, but if the line stays the 
same
but just the numbers change, you can do,

insideipgrepfd = os.popen("grep ifconfig_fxp0 /etc/rc.conf")
insideipgrep = insideipgrepfd.readlines()  ##Wait, if you're just using 
the
first line use insideipgrepfd.readline()
insideipgrep = insideipgrep.lstrip("ifconfig_fxp0=\"inet ")
temp = insideipgrep.split(" netmask ")
insideipquads = temp[0].split(".")
insideipmaskquads = temp[1].split(".")

Warning, code just above is not very stable --  if the text of the line
changes in anyway it won't work.
HTH,
Jacob Schmidt
> The following block of code works, and provides the necessary output 
> I'm
> looking for...but I have a feeling that it's working through sheer 
> brute
> force and could be better:
>
>insideipgrepfd = os.popen("grep ifconfig_fxp0 /etc/rc.conf")
>insideipgrep = insideipgrepfd.readlines()
>insideipfield, insideip = 
> string.split(string.strip(insideipgrep[0]),
> "=")
>insideipsplit = string.split(insideip, " ")
>insideipquads = string.split(insideipsplit[1], ".")
>insidemaskquads = string.split(insideipsplit[4], ".")
>
> the line in /etc/rc.conf looks like:
>
> ifconfig_fxp0="inet 172.31.2.100 netmask 255.255.255.0"
>
> Any and all thoughts/pointers are appreciated.
>
>~elh
>
> --
> Eric L. Howard   e l h @ o u t r e a c h n e t w o r k s . c o 
> m
> 
> www.OutreachNetworks.com 
> 313.297.9900
> 
> JabberID: [EMAIL PROTECTED] Advocate of the Theocratic 
> Rule
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

--
'There is only one basic human right, and that is to do as you damn well 
please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Fw: Please submit to tutor list: dictionary update prob

2005-01-19 Thread Jacob S.
Hi everyone, sent this on to the list as told to.
cc to eri to verify my sending to list...
;-) Jacob
dear jacob,
sorry to send this to you but if you may, kindly send to tutor list as im
no longer subscribed.  my problem is in the update dict portion: it just
doesnt update regardless how many contacts i add. kindly advise where
my mistake is or code gone wrong. the rest of the options i will do on my
own so just hold off the helps for now. appreciate all your good help.
please cc to this account.
--
regards,
erimendz
#!/usr/bin/env python
import cPickle, os, sys, re, stat
#import string
## Global variables
home = '~'
filename = os.path.join(os.path.expanduser(home), 'abook.dat')
data_holder = {}

## Functions
##
def about_program():
   print
   print '\t'*2, 'A simple address book written in Python'
   raw_input('\nPress  to continue...')
## add_contact ##
def add_contact(d):
   while True:
   name = add_name()
   email = add_email()
   d[name] = email
   print 'Add another contact? '
   ans = ask_yes_no()
   if ans == 0:# no
   print 'Save to address book? '
   get_ans = ask_yes_no()
   if get_ans == 1:# yes
   #collected = d
   check = if_file_exist(filename)
   if check is True:
 update_dict(data_holder, filename)
   else:   # file no exist
   write_book(data_holder, filename)
   break
   else:
   d.clear()   #clear dict
   break
def add_name():
   msg = 'Enter contact name: '
   while True:
   try:
   name = raw_input(msg)
   if len(name) != 0:
   if len(name) <= 20:
   return name
   else:
   print 'Name too long: please limit to 20 characters'
   else:
   print 'Try again: blank not allowed!'
   except EOFError:# catch ^C-D keypress
   print
def add_email():
   msg = 'Enter email address: '
   while True:
   try:
   email = raw_input(msg)
   if len(email) == 0:
   print 'Blank not allowed!'
   else:
   valid_format = 
r'[EMAIL PROTECTED](\.[-a-z0-9]+)*\.(com$|\
   edu$|net$|gov$|mil$|org$|int$|aero$|biz$|coop$|
museum$|pro$|info$)'
   valid_email = re.compile(valid_format)
   if valid_email.match(email):
   return email
   else:
   print '%s is not a valid address: try again!' % email
   except EOFError:
   print

def ask_yes_no():
   try:
ask = raw_input('Yes or No? [y|N] ')
if ask.lower() in ['y', 'ye', 'yes', 'yep', 'ok']:
return 1# yes
else:
return 0# no
   except EOFError:
print
def if_file_exist(f):
   ''' test if file exists; returns boolean '''
   return os.path.exists(os.path.join(os.path.expanduser('~'), f))
def get_filesize(f):
   ''' check file size '''
   return os.stat(os.path.join(os.path.expanduser('~'), f))[stat.ST_SIZE]
def write_book(d, f):
   write = open(f, 'wb')
   cPickle.dump(d, write)
   write.close()
def update_dict(d, f):
   ''' update the saved dictionary file '''
   read = open(f, 'rb')
   newdic = cPickle.load(read)
   newdic.update(d)
   read.close()

## view_abook() ##
def view_abook(d, f):
   check = if_file_exist(f)
   if check is True:
   # load file and pretty print
   read = open(f, 'rb')
   d = cPickle.load(read)
   for k, v in d.iteritems():
   print '%s\t%s' % (k, v)
   read.close()
   else:
   print 'no contacts listed!'

## function tester, sort of ##
def ifaccessible(f):
   ''' test if file is accessible by user; returns boolean '''
   return os.access(os.path.join(os.path.expanduser('~'), f), os.F_OK)

def main():
   while True:
   select = main_menu()
   while True:
   if select in [ '1', 'p']:
   about_program()
   break
   elif select in [ '2', 'a']:
   add_contact(data_holder)
   break
   elif select in [ '3', 's']:
   print "save_changes()"
   break
   elif select in [ '4', 'v']:
   view_abook(data_holder, filename)
   break
   elif select in [ '5', 'f']:
   print "find_contact()"
   break
   elif select in [ '6', 'e']:
   print "edit_contact()"
   break
   elif select in [ '7', 'r']:
   print "remove_contact()"
   break
   elif select in [ '0', 't', 'T']:
   #print if_file_exist(filename)
   #print get_filesize(filename)
   try:
   print get_filesize(filename)
   except OSError:
   print '%s not found!' % filename
   break
   elif select in [ '8', 'q']:
  

[Tutor] Unexpected result from decimal

2005-01-19 Thread Jacob S.
Hi all,
   I'm having a problem that is ticking me off. (to put it lightly)
Why does decimal do this --  I thought that getcontext().prec was number of 
decimal places?

import decimal
decimal.getcontext().prec = 2
a = decimal.Decimal(2)
b = decimal.Decimal(3)
100*a/b
Decimal("67")
print 100*a/b
67

Why does it do this?
It's really, really, messing things up for me because results are not 
interpreted in my programs correctly.
Jacob 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Unexpected result from decimal

2005-01-21 Thread Jacob S.
Okay, so how do I get decimal to set precision of *significant digits*?
Why have a decimal.getcontext().prec if it doesn't provide a useful result?
The number of digits in a number is irrelevant to that numbers value.
It just doesn't make sense to me.
I tried quantize the other day and it didn't work -- gave some sort of 
error,
I don't remember what it was, and I can't get it to do it again today.
So, I guess it works now and I can go back to wondering why
getcontext().prec = a
is not equal to
quantize("0."+"0"*(a-1)+"1")

Thanks,
Jacob
Comments to everyone's post below.
>>> import decimal
>>> decimal.getcontext().prec = 2
>>> a = decimal.Decimal(2)
>>> b = decimal.Decimal(3)
>>> 100*a/b
Decimal("67")
>>> print 100*a/b
This prints "67".
try -
a=decimal.Decimal(2.0)
This will not work.  You can't convert a float directly to a 
decimal.Decimal
(I believe this is so that you are forced to understand that there are
precision issues involved).  'a = decimal.Decimal("2.0")' will do what you
meant, though.
Decimal is a totally different type from integers and floats. It is not 
affected by float
division problems. It is not my type, it is in the standard distribution of 
python 2.4
You have to represent floats as strings, because if you don't, then a float 
with lost precision is
used instead of the exact precision.
For example -- 
If I pass 1.1 to decimal.Decimal, it will receive 1.101 or something 
like that so it can try to
keep perfect precision on a float that started from the beginning without 
it. This is what decimal is
trying to resolve in the first place!
However, if I pass a string, strings aren't affected by binary floating 
point problems and they can
be kept in perfect precision from the beginning.

b = decimal.Decimal(3)
print 100*a/b
However, this will print out "67", just as the above did.  The reason is 
the
one that Tim outlined: precision isn't the number of digits after the
decimal place - when I was at school the latter was called "decimal 
places"
and precision was "significant digits".

Jacob- one slight flaw/quirk in Python is if you want floating point
computations you have to specify a floating point.
[...]
Same as writing 100/3.0 as opposed to 100/3. Try it.
Note that you can do 'from __future__ import division' and 100/3 will be 
the
same as 100/3.0 (and 100//3 will give you 3).
See above
=Tony.Meyer
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: Fw: Please submit to tutor list: dictionary update prob

2005-01-21 Thread Jacob S.
Just one question...
Why are you off the list?
I see no point.
If you want to stop getting the mail, you can change the options of your 
list account online...
That's the only reason I see...

Let's see -- reasons
1. Cost -- No, it's free
2. Security -- If you were subscribed to it once, it's too late to worry 
about that (Though there is no reason to)
   a. There is an option (in Outlook Express at least) to make your name 
invisible to others when emailing
   b. You can make your name invisible on the subscriber's list on the 
website by using the options in your account page

Anyone want to comment --  maybe a link to get him to the subscriber's 
option page?

HTH,
Jacob Schmidt 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] glob or filter help

2005-01-22 Thread Jacob S.
Filter can be replaced with IMHO the more readable list comprehensions.
I would try
def get_fles(exts,upd_dir):
   "return list of all the files matching any extensions in list exts"
   fle_list = []
   for each in exts:
   ext_ls = glob.glob("%s*.%s" % (upd_dir,each))
   fle_list.extend(ext_ls)
   return [x for x in fle_list if not islink(x)]
I have the following code in my updates script (gets the five most recent
updated files on my site)
def get_fles(exts, upd_dir):
'''return list of all the files matching any extensions in list exts'''
fle_list = []
for each in exts:
 cmd = upd_dir + "*." + each
 ext_ls = glob.glob(cmd)
 fle_list = fle_list + ext_ls
return filter(notlink, fle_list)
I wanted to just get one list, of all the .htm and .exe files in my 
upd_dir.
I was trying to make a far more elegant solution that what's above, that
could generate a list through a filter.  Is there a way to trim the code 
down
to something that does ONE sort through the directory and picks up the 
.htm
and .exe files? (note, it is not necessary for this to recurse through
subdirectories in the upd_dir).  I have cmd defined above because calling
"glob.glob(upd_dir + "*." + each) returned the error "cannot concatenate
string and list objects" - is this the only way around that, or is there a
better way?

Also in the above code, "notlink" is just a function that returns True if
"islink()" returns truethere has to be a better way to use this with
filter(), how can i make filter use "if islink()!=true" as its condition?
The script is working now, (I know, I know, if it ain't broke, don't fix
it...) but I want to be a better programmer so more elegant solutions are
accepted gratefully.
-Jay
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Print record x in a file

2005-01-22 Thread Jacob S.
This will get a random record
I hope you do not think the comments are patronising
but you did say you are new so I did not want to give
naked code.
import random
#the above gives the program the ability to get a
#pseudo random number
file = open('test.rantxt')
listcontents = file.readlines()
#gives you the file as a list of records or it did on
#(assuming each line is a record)
file.close()
lenoflist = len(listcontents)-1
#find the length of the list and take one of because
computers count from 0
Yes, but len returns counting from 1.
Anyway, you would have to add one to correct that anyway, wouldn't you?
If randrange is start <= x *<=* end, then you don't have to add one, you
just use the length.
If randrange is start<= x < end like __builtin__ range, you have to put
randrange(1,lenoflist+1)
x = random.randrange(0,lenoflist)
I would use randint because list indices need to be integers -- unless of
course I mistaken and
randrange returns an integer also. (But that would be repetitive to have to
functions do the same thing)
print listcontents[x]
HTH,
Jacob
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] flattening a list

2005-01-22 Thread Jacob S.
Ahh, my pitiful form of flattening a list that cheats...
def flatten(li):
li = str(li)
li = li.replace("[","")
li = li.replace("]","")
li = li.replace("(","")
li = li.replace(")","")
li = "[%s]"%li
return eval(li)
It works! It's probably just a bit slower.
Jacob Schmidt
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Advise...

2005-01-25 Thread Jacob S.
Hi all.
   Long time no see. (About five days, right?)
Anyway, I know the first thing that some of you are going to say is using 
eval(). I don't want a whole
guilt trip on security risks and all that. I do not want to share the code 
with anyone else while it's on my
computer, and I sure don't have anyone near me that knows python. I would be 
surprised if more than 50
people in Portland, IN knew anything about python. So security is not a 
problem. I guess what I'm
looking for is someone who knows the Reimann Sum better than I do and can 
tell me whether I can do
something to make it more efficient. It's horribly slow with ten thousand 
steps-- I don't know the notation
very well, but it loops the loop O(step*(maximum-minimum)) times, which is 
horribly sucky.
   In case anyone doesn't know, Reimann's sum is the computer's version of 
the definite integral, the area
under a curve in a particular domain.

Basic input and output.
If a curve is a straight line, say y = x, the area under the line on an 
interval can be found by geometric means.
However, if you use a parabola, or any other function, say y = 3*x**2,

What is the function? 3*x*x
What is the minimum? 2
What is the maximum? 5
117.000435
Which, considering that it is supposed to be exactly 117, It's darn good. 
Unfortunately, it also takes about
10 seconds to do all that.
Any suggestions? Any advice? TIA
Jacob Schmidt


from __future__ import division
import psyco
psyco.full()
fofx = raw_input("What is the function? ")
minimum = raw_input("What is the minimum? ")
maximum = raw_input("What is the maximum? ")
minimum = float(minimum)
maximum = float(maximum)
total = 0
step = 10
x = minimum
while minimum <= x <= maximum:
   area = eval(fofx)*1/step
   total = total+area
   x = x+1/step
print total
# 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Advise...

2005-01-26 Thread Jacob S.
Thanks everyone!
Kent started the suggestion of making a code object, but everyone else seems 
to have worked their way to it.
Beautiful! I only have to call exec once, and it cuts down time 
considerably.

Here is the new code.
Jacob Schmidt
Please remind me if I've forgotten anything.
### Start ###
from __future__ import division
from math import *
import psyco
psyco.full()
def reimannsum(fofx,x,max1):
   total = 0
   step = 1e-5
   exec "def f(x): return %s" % fofx
   while x <= max1:
   total = total+f(x)
   x = x+step
   return abs(total*step)
fofx = raw_input("What is the function? ")
minimum = raw_input("What is the minimum? ")
maximum = raw_input("What is the maximum? ")
minimum = float(minimum)
maximum = float(maximum)
print reimannsum(fofx,minimum,maximum)
 End ##
If the user must be able to enter in the function, then it would be
better
to evaluate this once and turn it into some sort of function that
you can
call inside the loop (it's the eval that is so expensive).  How to
do that
depends a lot on how complex the possible functions can be (if
they'll only
include 'x*+/-' and numbers, for example, it's not so tricky).
exp = raw_input('Type expression')
func = eval('lambda x: " + exp)
print func(42)
etc...
Or if you really can't grokm lambda:
exec('def func(x): return " + exp)
should do the same...
Alan G.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Unique Items in Lists

2005-01-26 Thread Jacob S.
col2_set = sets.Set(col2)

how can I get a uniq elements that repeated several
times:
for item in range(len(list)):
for k in range(len(list)):
   if item == k:
   if list[item] != k[list]:
 print item
First off, this would never work. You are iterating over the same list so go 
through each step on paper or in your head.
Oh, and don't use list for a variable name--it's a builtin function that you 
don't want to write over.
An example

a = [1,1,4,2,3,1,5]
for item in range(len(a)):
   for k in range(len(a)):
   if item == k:
   if a[item]!=a[k]:  ## I think this is what you meant to 
put--otherwise you would be trying to index an index!
   print item   ## This returns an index, maybe you want the 
element instead?

Ok... here's how it runs with all the variables replaced with the values 
defined by the loop.

if 0 == 0:
   if 1!=1:
   print 1
That is okay.
if 0 == 1:
   if 1 != 1:  ## The first 1 comes from a[0] (item=0), the second 1 from 
a[1] (k=1)
   print 1 ## This is obviously not what you want, so immediately we 
see a problem.

Then it goes through 
(0,2),(0,3),..(1,0),(1,1)(1,2),(2,0),(2,1),

Anyway, this is all irrevelant because sets takes care of doubles.
import sets
a = sets.Set([1,2,1,4,3,5,5,2,3,3,2])
a
Set([1, 2, 3, 4, 5])
list(a)  ## This is one of the uses of the builtin list -- to make a 
list of an iterable.
[1, 2, 3, 4, 5]

HTH,
Jacob
This isnt working either.  logic appears correct.
looking forward for help pleas.
thank you
Srini


__
Do you Yahoo!?
The all-new My Yahoo! - What will yours do?
http://my.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Preffered way to search posix filesystem

2005-01-27 Thread Jacob S.
Try this
def findfile(thefile, 
toplevel="C:\\windows",findcount=-1,subdirectories=True,returnlist=False):
   results = []
   t = 0
   if subdirectories:
   for root,dirs,files in os.walk(toplevel):
   for x in files:
   fullname = os.path.join(root,x)
   if x.lower() == thefile.lower():
   print "Found %s" % fullname
   results.append(fullname+": 0:")
   t = t+1
   else:
   print "Searching %s" % fullname
   if t == findcount:
   break
   print "\nFound %s matches:" % t
   pplist(results)
   else:
   n = 0
   for x in os.listdir(toplevel):
   fullname = os.path.join(toplevel,x)
   if x.lower()==thefile.lower():
   print "Found:\n%s: 0:" % fullname
   n = 1
   results.append(fullname)
   break
   if not n:
   print "Found 0 matches."
   if returnlist:
   return results

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Should this be a list comprehension or something?

2005-01-28 Thread Jacob S.

Its not so much a criterion that they *should* be used that way,
its just that its what they do. A list comprehension creates a list!
Thats why they are called *list* comprehensions. :-)
See, I'd always figured that the reason it was called a list
comprehension was because the list comprehension operated on a list,
and the operation was comprehension.
It can easily be checked by...
Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
a = range(10)
b = [x for x in a if x % 2 == 0]
c = ['12','21','14','13']
d = [a[2] for x in c]
a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b
[0, 2, 4, 6, 8]
c
['12', '21', '14', '13']
d
[2, 2, 2, 2]
type(a)

type(b)

type(c)

type(d)


Everything I did with list comprehensions above shows that list 
comprehensions return a list.
Mostly it is evidenced by the type function...

Maybe, this post is silly?
Oh, well.
Jacob 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Naming conventions (was: Should this be a list comprehension or something?

2005-01-28 Thread Jacob S.
You're my best friend. Everyone else looves camelCase, and I hate it too. It 
doesn't make sense. It doesn't fit English.
It doesn't fit Spanish. It doesn't fit any other language AFAIK, so why 
should a human (who uses spoken language) to computer interpreter use a 
naming convention that doesn't match spoken language? That's my opinion.

Jacob Schmidt

On Wed, 26 Jan 2005, Sean Perry wrote:
And now, for the pedant in me. I would recommend against naming
functions with initial capital letters. In many languages, this implies
a new type (like your Water class). so CombineWater should be 
combineWater.
I hate hate hate hate hate camelcase and will never use it.  In my book,
if the name has *any* capitals in it, the first letter is capitalized,
too.  Anything else is unaesthetic.
To me, when I have names that are composed of multiple words (say, "rice
quantity"), I have two approaches: distinguishing the words by case
(RiceQuantity) or separating by underscores (rice_quantity).
I never confuse classes/instances and methods, because I use noun phrases
for classes and instances (HeatedWater, VerifiedInput) and verb phrases
for the methods (CombineWater, CookRice).  I suppose I could get
confusion, for example, when the combination either a noun phrase or
verb phrase (SoundOut: is that a name describing the Sound that's being
put Out, or is it a method that's is tentatively Sounding Out somthing?)
but so far that hasn't been an issue for me.
Of course in my case, I write code only for myself, so I have the luxury
of not worrying about what Joe in the next cubicle is doing, and what Jane
will do when she's trying to read Bob's and my code together.  So I have
the luxury of turning my nose up at camelCase.
I should add that, the one time I made changes to someone else's Python
code for release (a minor patch to nntplib.py), I used the same case
conventions already in place in the module.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Control flow

2005-01-29 Thread Jacob S.
I noticed that too, Liam.
b = input("Weather is really bad, still go out to jog? [y/n]") # Would 
it kill you to have whitespace in a prompt?
should really be
b = raw_input("Weather is really bad, still go out to jog? [y/n]")
to get the effect he wants.

input() doesn't only take integers, it takes valid python objects. Integers 
are objects, but so are lists, dictionaries, tuples,
actually it takes everything, BUT!!! it trys to return a valid python object 
for input.
So it will take a string--don't quote me on this--if you explicitly put the 
string in quotes.
If you don't put the string in quotes, it instead searches the namespaces 
for that object.
So say the user typed in bad_weather when the interpreter gave that prompt. 
Then, b == "y" evaluates true because bad_weather == "y". Did I explain it 
right? Or am I trying to explain something you already know? I know I get 
frustrated when people try to explain concepts that I already know...

HTH,
Jacob Schmidt
< erk, to the list, to the List!>
if ( bad_weather =='y' ):
  # ask user only if weather is bad.
  b = input ( "Weather is really bad, still go out to jog?[y/n]" )
  if b == 'y':
 go_jogging()
Anyone else notice that he's never gonna go jogging if the weather is bad?
Unless I've got input() wrong, it only takes integers... ?
Regards,
Liam Clarke
--
'There is only one basic human right, and that is to do as you damn well 
please.
And with it comes the only basic human duty, to take the consequences.

--
'There is only one basic human right, and that is to do as you damn well 
please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Naming conventions (was: Should this be alist comprehension or something?

2005-01-29 Thread Jacob S.
I just read your post a heck of alot easier than I read Liam's. ;-)
Jacob Schmidt
iguessthereisnooptionleftexcepttorunwordstogetherwithoutanykindofbreakatall
thatshouldannoyeveryoneequally
Kent
Liam Clarke wrote:
Just please_don't_use_underscores. They_make_my_eyes_go_funny_, 
_and_code_hard_to_read_in_my_opinion.

_u_n_d_e_r_s_c_o_r_e_s_ _a_r_e__u_g_l_y_
I got out of the habit of using them really fast.
Also, __ & _ tend to have special meaning in Python (which is bad
enough as it is), so I don't use them for that reason as well.
Liam Clarke
On Fri, 28 Jan 2005 22:54:08 -0500, Jacob S. <[EMAIL PROTECTED]> wrote:
You're my best friend. Everyone else looves camelCase, and I hate it too. 
It
doesn't make sense. It doesn't fit English.
It doesn't fit Spanish. It doesn't fit any other language AFAIK, so why
should a human (who uses spoken language) to computer interpreter use a
naming convention that doesn't match spoken language? That's my opinion.

Jacob Schmidt
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


  1   2   >