[Tutor] Re: A simpler mousetrap

2004-12-16 Thread Wolfram Kraus
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


[Tutor] OT: list as newsgroup (was: Please submit to tutor list: dictionary update prob)

2005-01-20 Thread Wolfram Kraus
Jacob S. wrote:
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

You don't need to be subscribed to the list, you can also use it as a 
newsgroup via gmane:
news://news.gmane.org (for more details: http://news.gmane.org)
It works fantastic, I use it for a lot of mailinglists.

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


[Tutor] Re: Unique Items in Lists

2005-01-27 Thread Wolfram Kraus
Brian van den Broek wrote:
[...]
Hi Srini,
for the task of finding out which items are repeated and how many times, 
I'd do this:


def dups_in_list_report(a_list):
'''Prints a duplication report for a list.'''
items_dict = {}
for i in a_list:
if i in items_dict:
items_dict[i] = items_dict[i] + 1
else:
items_dict[i] = 1
get(key, default) is your friend here:
  for i in a_list:
  items_dict[i] = items_dict.get(i, 0) + 1
get() (and his "brother" setdefault()) are mighty dictionary-methods.
for key in items_dict.copy():   # Try it without the .copy()
if items_dict[key] == 1:# and see what happens.
del items_dict[key]
dict_keys = items_dict.keys()
dict_keys.sort()
>
for key in dict_keys:
print '%s occurred %s times' %(key, items_dict[key])
This whole part can be rewritten (without sorting, but in Py2.4 you can 
use sorted() for this) with a list comprehension (Old Python2.1 style, 
with a newer version the keys() aren't needed):
  for k,v in [(k, items_dict[k]) \
  for k in items_dict.keys() if items_dict[k] > 1]:
  print '%s occurred %s times' %(key, items_dict[key])

f = [1,1,2,3,3,3,3,4,4,4,4,4,4,4,5]
dups_in_list_report(f)

And, now that I get back on-line, I see that Chad posted the same basic 
idea. But, perhaps the extra stuff here is of use, too.
You can apply the get()  there, too ;-)

HTH,
Brian vdB

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


[Tutor] Re: Unique Items in Lists

2005-01-27 Thread Wolfram Kraus
Chad Crabtree wrote:
Ok you got me thinking.  I used the same thing I posted before but 
created a one liner that as a side affect makes adict like before. 
[adict.__setitem__(x,adict.get(x,0)+1) for x in l]

I think it's kinda funny and ugly, ohh and not particuarly clear 
about what it does.

Uhh, list-comprehensions with side effects. Must. resist.
And now write the Zen of Python 10 times ;-)
Greetings,
Wolfram
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Presentation

2005-02-01 Thread Wolfram Kraus
Paul Hartley wrote:
[...]
When I was a member of the Forth Interest Group in the USA we learned
that Forth was used on the buggy that went to mars, that it started
life controlling huge radio telescopes which only had 4k (yes 4k) of
memory for both language and application.
Well, the rover used Forth, but the rover-website is Plone powered:
http://plone.org/newsitems/mars-rover
Plone is a CMS built on top of Zope, which itself is Python powered. For 
more sites running plone see: http://plone.org/about/sites/

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


[Tutor] Re: how to separate hexadecimal

2005-02-02 Thread Wolfram Kraus
jrlen balane wrote:
i have a 4 digit hex number (2 bytes) and i want to separate it into 2
digit hex (1 byte each) meaning i want to get the upper byte and the
lower byte since i am going to add this two.
how am i going to do this?
should i treat it just like a normal string?
please help, thanks.
ex. hexa = '0x87BE"  # what i want to do is:
  a = 0x87, b = 0xBE# so that i could do this:
  c = a + b#which should be equal to 0x145
Not sure where you get hexa from, but given your example you can use 
int(x, base) with base = 16 to convert your string to an integer and 
then use the %x formatstring:
>>> hexa = '0x87BE'
>>> upper = int(hexa[2:4], 16)
>>> lower = int(hexa[4:6], 16)
>>> print '0x%x + 0x%x = 0x%x' % (upper, lower, upper+lower)
0x87 + 0xbe = 0x145

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


[Tutor] Re: Are you allowed to shoot camels? [kinda OT]

2005-02-03 Thread Wolfram Kraus
Alan Gauld wrote:
[...]
1) I'll use Perl for the regex stuff from now on, Perl is obviously
built for this.

Yes, or PHP. Both have RE baked in.
Beware! Overcome the temptation!
Try this: http://kodos.sourceforge.net/
HTH ;-)
Wolfram
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: print out lines that start with a word

2005-02-09 Thread Wolfram Kraus
Ron Nixon wrote:
Can anyone tell me what I've done wrong in this
script.
I'm trying to get only the lines that start with
"This" for a text file.
Here's what I wrote:

import re
f = open('c:/lines.txt').readlines()
for line in f:
match = re.search('^This',f)
if line == match:
print match

Pardon my ignorance, but why is everybody fond of regexps ;-) ? Are they 
faster? What about good ol' startswith(): 
http://docs.python.org/lib/string-methods.html#l2h-204
Untested:

f = open('c:/lines.txt').readlines()
for line in f:
  if line.startswith('This'):
print line # Or whatever match is, no regexp-expert here, sorry
Wondering,
Wolfram
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: print out lines that start with a word

2005-02-09 Thread Wolfram Kraus
Liam Clarke wrote:
regexes are common across a lot of languages, even Java has them. 
Though the pain that would be I daren't not imagine. So the syntax is
 familiar, whereas string methods may not be.
But IMHO string methods are (more) explicit and readable, the name tells 
you what the method is doing. I know that sometimes regexp are really 
fine, e.g. extracting something from html or maybe speed issues (can 
anyone enlighten me on that one?), but for simple task like the OP's 
problem I'd always use string methods.

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


[Tutor] Re: print out lines that start with a word

2005-02-09 Thread Wolfram Kraus
Liam Clarke wrote:
x= ["Dude", 'How is it going man', ' ']
print x
['Dude', 'How is it going man', ' ']

j=[]
for item in x:
... if re.search('\S+',item):
... j.append(item)

print j
['Dude', 'How is it going man']
What about:
x= ["Dude", 'How is it going man', ' ']
print [a for a in x if a.strip()]

Now, I first did that in a Perl script, but it easily comes across to
Python. \S+ will usually mean 'one or more non-whitespace characters'.
Brilliant for when your first Perl script accidentally appended \n to
everything, even \n and \t. *embarassed*
Whereas, while I'm sure there is a string method that can do that, I'm
not sure what it is.
Well the documentation on that is not sooo big ;-)
Also - say you have a list of words - 
j = " bag apple tomato cheese *marmite*  sausages *scones*"

and you wanted to pick up each word that was asterisked. 
I did this as a string method then a regex.


try:
... 	indexes=[]
... 	lastIndex = 0
... 	while 1:
... 		x = j.index("*", lastIndex + 1)
... 		indexes.append(x)
... 		lastIndex = x
... except ValueError:
... 	pass
... 

print indexes
[4,  10]
myString = j[5:10]

That gives me  [25, 33, 45, 52], propably a C&P bug?
Now the regular expression - 


x = re.finditer("\*(?P.*?)\*", j)
a = x.next()
print a.group('myString')
apple
Same error as above? And you said you want _all_ asteriksed words!
How about this cute lil list comprehension:
print [w for w in j.split() if words[0] == '*' and words[-1] == '*']
Now, while the regEx syntax is a big harsh to begin with, once you get
the hang of it, it's OK, and the string method version I used felt too
'hacky' for me. Of course, both only work with pairs of asterisks, so
I guess that makes them both hacky. : )
That's my 2c, I use string methods for stuff like that .startswith, .endswith, 
if 'foo' in x stuff is good as well. But sometimes, a regex is the
right tool for the job.
I didn't say that they are useless (and don't wanna troll or start a 
flameware), but IMHO they are a PITA when it comes to debugging. Ever 
touched a regexp after one year ;-)?

Regards, 

Liam Clarke
Greetings,
Wolfram
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: print out lines that start with a word

2005-02-09 Thread Wolfram Kraus
Damn!
C&P-bug here to! Is this a virus? ;-)
print [w for w in j.split() if words[0] == '*' and words[-1] == '*']
Should be:
print [w for w in j.split() if w[0] == '*' and w[-1] == '*']
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: print out lines that start with a word

2005-02-09 Thread Wolfram Kraus
Liam Clarke wrote:
print [w for w in j.split() if w[0] == '*' and w[-1] == '*'] 

Wouldn't that only work if it was bug *car* jeff?
I can imagine bug*car*jeff would throw it.
Cheers, 

Liam Clarke
x = 'bug*car*jeff*foo*bar'
[x.split('*')[a] for a in range(1,len(x.split('*')), 2)]
When you mix * and spaces I will give up ;-)!
Wolfram
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Trivia program.

2005-02-16 Thread Wolfram Kraus
. Sm0kin'_Bull wrote:
Hi, I got a problem with this program.
 
 
name = raw_input("Hi. What's your name? ")
called = name * 5
called = ' '.join([name]*5)
print "\nIf a small child were trying to get your attention, " \
   "your name would become:"
print called
When i input the name like "John Goodman"
 
it prints like...
 
John GoodmanJohn GoodmanJohn GoodmanJohn GoodmanJohn Goodman
 
But i want to print it like...
 
John Goodman  John Goodman  John Goodman  John Goodman  John Goodman
 
How can I do it?

[name]*5 gives you a list with five items, every item is name. join uses 
a space (' ') to join all items in the list into a new string.

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


[Tutor] Re: how to read from a txt file

2005-02-17 Thread Wolfram Kraus
Brian van den Broek wrote:
jrlen balane said unto the world upon 2005-02-17 02:41:
[...]
data_file = open('C:/Documents and Settings/nyer/Desktop/nyer.txt', 'r')
[...]
The immediate one, due to my advice, is that each line of your file ends 
with a newline character ('\n'). So, you cannot call int on '1000\n'.

Try
data_points.append(int(line[:-1]))
instead. That will call int on line minus the last character (the newline).
The OS is from MS, so the lines will probably end with '\r\n'. It is 
better to call strip() on each line:
data_points.append(int(line.strip()))

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


[Tutor] Re: Method/subclass

2005-02-22 Thread Wolfram Kraus
Liam Clarke wrote:
Hi all,
I'm working on my first object-based-from-the-ground-up project, and I
have some queries.
http://www.rafb.net/paste/results/lDUmWS78.html
Here are my two classes here. For each different function, search,
edit, view, etc. a different SQL operation will take place, and a
different child window will be returned to the main window.
Roughly speaking.
I was going to create a method for each of the different functions in
both class, but I was wondering if it would be better to subclass for
each function. I've never done this before, so it's a little
confusing.
Incidentally, is this 

searchWin = genericChild
an OK way to create a class instance of genericChild? It seems to work
OK, and Pythoncard does funny things with __init__ for windows ( I
can't figure out how to pass __init__ arguments for example.)
But I'm worried that there's some unforeseen consequence of this kind
of thing, it just seems strange not finishing with ().
So yeah, should I do a method for each function, or subclass my generic classes?
Regards, 

Liam Clarke
I didn't look at the rest of the code, but you want
searchWin = genericChild()
instead. (Do a print searchWin to see why ;-))
HTH,
Wolfram
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: one line code

2005-04-04 Thread Wolfram Kraus
Christian Meesters wrote:
Hi
Yesterday night I was thinking about the following problem: I do have
a list like l = ['1','2','3','abc','','4'] - for instance like a list
one could get from a file import with the csv module (which is where
my 'problem' comes from). Now I would like to generate the following
list, preferably with one line of code: l2 =
[1.0,2.0,3.0,'abc','',4.0] With other words I'd like to tell Python:
Convert into a float if possible, otherwise append anyway. Is this
possible in one line? (Right now my code is a lot longer.)
Well, not really in one line, but one function & one line:
def f(x):
try:
return float(x)
except ValueError:
return x
l2 = [f(x) for x in l]
(I could imagine some obfuscated one-line LC using sting.digits an "or", 
but that will look too much like Perl ;-))

I was trying with 'filter' + lambda forms, list comprehensions etc.,
but could not find a solution. Could it be that a C-like solution
with '?' and ':' is more straightforward than a solution with Python
or am I just too blind to see a real pythonic solution here?
I am aware that putting a solution in one line of code might be
against the 'Zen of Python' (... Complex is better than complicated
... Readability counts ...), but since I'm just asking out of
curiosity, perhaps I'll get an answer anyway. ;-)
Thanks a lot in advance. Cheers Christian
HTH,
Wolfram
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Text Directly to Screen?

2005-05-06 Thread Wolfram Kraus
Aaron Elbaz wrote:
> Hi,
> 
> My question has to do with outputting text.
> 
> Normally, you ouput to a console or a gui...but for my task, a hack
> might be needed..
> 
> What I want to do is output text *directly* to the screen. And if
> possible, restrict the window area to specific dimensions (top right
> in mind). It should basically be like a layer of Cellophane over all
> other windows, so that users can't interact, they only 'see' the
> output of the chat session, and this chat session would be visible
> over all windows, including the native OS gui.
> 
> It sounds awfully cool, but awfully complicated too. I'm not sure
> where to start looking..
> 
> Any ideas?
> 
> -thanks

I don't think that there is a OS independent solution for this problem, 
but if you are using KDE under Linux you can try superkaramba 
(http://netdragon.sourceforge.net/ssuperkaramba.html). There is a 
similar package for gnome, too, google is your friend.

HTH,
Wolfram

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


Re: [Tutor] all methods in a module

2005-05-27 Thread Wolfram Kraus
Johan Meskens CS3 jmcs3 wrote:
> hello
>
> 
import random
print random.setstate.__doc__
> 
> Restore internal state from object returned by getstate().
> 
> 
> my question is
> " how can i loop through all the methods in a module 
>   and print out their '__doc__' content ?
> 
> 
for d in dir( random ):
> 
>   print random.???d???.__doc__
> 
> 
> thanks
> jmcs3

Untest no-brainer with "eval", there might be better solutions:


 >>> import random
 >>> for d in dir(random):
...  print eval('random.%s.__doc__' % d)

HTH,
Wolfram

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


Re: [Tutor] File Input of "Objects"

2005-06-01 Thread Wolfram Kraus
Chuck Allison wrote:
> Hello tutor,
> 
>   I notice that with 'print >> f' one can print the string
>   representation of objects to a file. Is there a corresponding input
>   facility that parses through a file creating objects? I can't find
>   one. In the meantime, I did this:
> 
> 
f = open('out.dat','w')
print >> f, 1, 2
f.close()
s = open('out.dat').read()
x,y = tuple(map(eval,s.split()[:2]))
x,y
> 
> (1, 2)  
> 
> This is just what came to mind without thought. Is there a Pythonic
> way to read formatted objects? Thanks.
> 
If you want to save objects to a file and reread them later, the best 
solution is pickle:
http://www.python.org/doc/2.4.1/tut/node9.html#SECTION00922
and
http://www.python.org/doc/2.4.1/lib/module-pickle.html

HTH,
Wolfram

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


Re: [Tutor] Changing what you've already printed

2005-06-22 Thread Wolfram Kraus
Curses might help you:
http://docs.python.org/lib/module-curses.html

Take a look at the Demo-directory which is included in the Python 
source-package. There is a curses subdir in it which might get you started.

HTH,
Wolfram

Ed Singleton wrote:
> Is it possible (and easy) to change something you've already printed
> rather than print again?
> 
> For example, if I'm making a little noughts and crosses game and I
> print the board:
> 
>|   |   
>|   |   
> ___|___|___
>|   |   
>|   |   
> ___|___|___
>|   |   
>|   |   
>|   |   
> 
> Then the computer has it's go, and rather than print the board out
> again and have the previous empty board appear higher up, I want to
> just add a X to the board I've already created.
> 
> Eg.
> 
> 
>|   |   
>|   |   
> ___|___|___
>|   |   
>| X |   
> ___|___|___
>|   |   
>|   |   
>|   |   
> 
> I've programs do this on the command line in Linux, so I assume it
> must be possible.  (I don't mind making my programs Linux only so
> that's not a problem).
> 
> Any clues or pointers to documentation gratefully recieved.
> 
> Thanks
> 
> Ed
> ___
> 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] Why is this error showing up? (Original Message: (Tutor) What's wrong with this code?) Ignore previous post.

2005-07-07 Thread Wolfram Kraus
You wrote filename == raw_input("Filename to load: ") instead of 
filename = raw_input("Filename to load: ")

HTH,
Wolfram

Nathan Pinno wrote:
> Hi all,
> 
> Here's one of the messages that pops up:
> 
> Traceback (most recent call last):
>   File "D:\password.py", line 77, in ?
> filename == raw_input("Filename to load: ")
> NameError: name 'filename' is not defined
> 
> Why is it popping up whenever I try to load a file?
> 
> Here's the latest code:
> 
> # This is the code for a password protected program to store passwords.
> password = "hello"
> print "The Password Program"
> print "Copyright 2005 Nathan Pinno."
> print
> answer = raw_input("What is the password? ")
> while password != answer:
> print "The password is incorrect."
> answer = raw_input("What is the password? ")
> def main_menu():
> print "1) Add a login info card"
> print "2) Lookup a login info card"
> print "3) Remove a login info card"
> print "4) Print Login info list"
> print "5) Save login list"
> print "6) Open Login list"
> print "9) Exit"
> 
> def load_login(site,filename):
> in_file = open(filename,"r")
> while 1:
> in_line = in_file.readline()
> if len(in_file) == 0:
> break
> in_line = in_line[:-1]
> [site,id,passcard] = string.split(in_line,",")
> list[site] = id and passcard
> in_file.close()
> 
> def save_login(site,filename):
> out_file = open(filename,"w")
> for x in site.keys():
> out_file.write(x+","+sites[x]+"\n")
> out_file.close()
> 
> menu_choice = "0"
> list = {}
> print "Welcome to the second half of the program."
> print main_menu()
> while menu_choice != "9":
> menu_choice = raw_input("Choose an option: ")
> if menu_choice == "1":
> print "Add a login info card"
> site = raw_input("Site: ")
> id = raw_input("User ID: ")
> passcard = raw_input("Password: ")
> list[site] = id and passcard
> menu_choice = raw_input("Choose an option: ")
> elif menu_choice == "2":
> print "Lookup a login info card"
> site = raw_input("Site: ")
> if site.has_key(site):
> print "The ID is: ",id(site)
> print "The password is: ",passcard(site)
> else:
> print site," was not found."
> menu_choice = raw_input("Choose an option: ")
> elif menu_choice == "3":
> print "Remove a login info card"
> site = raw_input("Site: ")
> if sites.has_key(site):
> del numbers[site]
> else:
> print site," was not found."
> menu_choice = raw_input("Choose an option: ")
> elif menu_choice == "4":
> print "Login Info"
> for x in site.keys():
> print "Site: ",x," \tID: ",numbers[x]," \tPassword: ",numbers[x]
> print
> menu_choice = raw_input("Choose an option: ")
> elif menu_choice == "5":
> filename = raw_input("Filename to save: ")
> save_login(list,filename)
> menu_choice = raw_input("Choose an option: ")
> elif menu_choice == "6":
> filename == raw_input("Filename to load: ")
> load_login(list,filename)
> menu_choice = raw_input("Choose an option: ")
> print "Have a nice day!"
> 
> Anything else that needs addressing?
> 
> Thanks,
> Nathan Pinno
> http://www.npinnowebsite.ca/
> 

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


Re: [Tutor] maximum recursion depth exceeded !

2005-07-07 Thread Wolfram Kraus
Mohammad Moghimi wrote:
> Hi there
> I wrote a recursive function a got this error how can I increase 
> maximum recursion depth. And what is its default value?
> -- Mohammad
> do you Python?!!

Start your python interpreter and:

 >>> import sys
 >>> sys.getrecursionlimit()
1000
 >>> help(sys.setrecursionlimit)

HTH,
Wolfram

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


Re: [Tutor] generating documentation for a module

2005-07-07 Thread Wolfram Kraus
Mike Hansen wrote:
> Is there a utility that generates documentation for your python 
> modules/scripts/programs based on their doc strings that looks similar to the 
> library documentation on the python web site?
> 
> What do you use to generate documentation for your python 
> modules/scripts/programs?
> 
> Mike

Never used it, but this should do what you want:

http://docs.python.org/lib/module-pydoc.html

Batteries included ;-)
HTH,
Wolfram

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


Re: [Tutor] maximum recursion depth exceeded !

2005-07-07 Thread Wolfram Kraus
Alan G wrote:
>> Start your python interpreter and:
>> 
> import sys sys.getrecursionlimit()
>> 1000
> help(sys.setrecursionlimit)
> 
> 
> Ooh, that's nice. When did the ability to tweak it programmatically 
> appear? Or has it always been there and I've just never noticed?

It isn't in the 1.5.2 documentation but in the 2.0 documentation, so
it has been there for some time ;-)

> Looks like a good candidate for use inside an exception handler...
> 
> Alan G.
> 

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


Re: [Tutor] Directory or File ?

2005-08-02 Thread Wolfram Kraus
Damien wrote:
> Hi all,
> I want to know if a file is a directory or a simple file.
> I have done a little ugly script :
> # i is my filename, os is imported
> old = os.getcwd()
> try:
> chdir(i)
> is_dir = True
> except:
> is_dir = False
> os.chdir(old)
> return is_dir
> 
> But maybe there is a better way ?
> If you know a better way, please tell me.
> 
> Thanks,
> Damien G.

Use os.path.isdir:
http://python.org/doc/2.4.1/lib/module-os.path.html#l2h-1739

HTH,
Wolfram

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


Re: [Tutor] n.isalnum() is failing

2007-07-03 Thread Wolfram Kraus
Use isdigit instead of isalnum.

HTH,
Wolfram

On 03.07.2007 09:51, Terry wrote:
> Hi!
> 
> I am running Python 2.5, and I have an IF statement in the below program
> that does not seem
> to be doing it's job. The program simply acquires a range of years from
> the user and prints out
> all the leap years between the two dates. I am having trouble in
> trapping for possible user
> errors. I am using x.isalnum() to check that I have a number for each
> year entered, and it
> doesn't look to me like it is functioning properly.
> 
> When I purposely enter bad data, such as '' for one of the a year
> entries, the IF statement:
> 
> if start.isalnum() == 1 and end.isalnum() == 1:
> 
> -Fails to detect that '' is not a number and lets the program then
> die tragically a horrible
> sudden awkward death on the very next line:
> 
> start = int(start); end = int(end)
> 
> Traceback (most recent call last):
>   File "/home/lucky/Documents/Python_Programs/leap_years.py", line 119,
> in 
> start = int(start); end = int(end)
> ValueError: invalid literal for int() with base 10: ''
> 
> If I say on the commandline:
> 
 n = ''
 n.isalnum()
> True  False!!!

> 
> 
> My program starts here:
> 
> def leap():
> answer = 0
> t1 =  / 4
> if t1 == int(t1):
> t2 =  / 100
> t3 =  / 400
> if t2 <> int(t2) or t3 == int(t3):
> answer = "-- leap year!"
> return answer
> 
> print "This program finds all leap years between two dates.";print;print
> 
> start = raw_input("Enter  for beginning year : ")
> end = raw_input("Enter  for ending year : ")
> 
> if len(start) == 4 and len(end) == 4:
> if start.isalnum() == 1 and end.isalnum() == 1:  
> #<--fails to detect '' as not a number
> start = int(start); end =
> int(end)   #<--commits
> suicide here
> if start > 0 and end > start:
> print; print
> for i in range(start, end + 1):
> answer = leap(i)
> if answer != 0:
> print i, answer
> print "Done!"
> 
> 
> 
> 
> ___
> 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] Joining non strings in to string

2005-10-28 Thread Wolfram Kraus
Eddie S wrote:
> Hi,
> I have a list containing numbers. I want to join this list in to a
> string which I can then output. The problem is I cant seem to join
> list of non-string items in to a string.
> 
> My list looks something like:
> 
> list = [5,7,20,19,49,32]
> 
> I could loop through the list outputing each number individually but I
> am sure there is a nicer method of doing it.
> 
> Cheers Eddie

Use List Comprenhensions, join() and str():

numlist = [5,7,20,19,49,32]
','.join([str(x) for x in numlist])

BTW: never use "list" as a name for your list

http://docs.python.org/tut/node7.html#SECTION00714

HTH,
Wolfram

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


Re: [Tutor] dont understand this error MySQLdb

2005-12-14 Thread Wolfram Kraus
nephish wrote:
> hey there,
> i am using the MySQLdb module and i keep getting this error, it doesnt
> offer much in the way of explanation
> 
> _mysql_exceptions.InterfaceError: (0, '')
> 
> does anyone know what this means ?
> 
> thanks
> 
I think you should better post in the Mysql for Python forum over at sf.net:
http://sourceforge.net/forum/forum.php?forum_id=70461

And beside that it is hard to tell without any code. Can you write a 
very simple example to reproduce this error?

HTH,
Wolfram

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


Re: [Tutor] Codehelp: confused by the output in IDLE

2005-12-16 Thread Wolfram Kraus
vikas mohan wrote:
> Hi again!
>  
> The following is a piece of code that I have written:
> 
> def funcA(x): # function describiing the oddness or eveness of an x number
>   if x%2 == 0:
> print x, "is even"
>   else:
> print x, "is odd"
>
> def funcB(y): # function describiing the oddness or eveness of an y number
>   if y%2 ==0:
> print y, "is even"
>   else:
> print y, "is odd"
>
> # no more functions after this line
> 
> *x=input("Please type a number: ")
> print x*
> 
> *y=input("Please type another number: ")
> print y*
> 
> *if x>y:
> print x,("is greater than"),y
> else:
> print y,("is greater than"),x*
> 
> *if y and x >=0:
> print ("Both are positive numbers!")*
> 
> print funcA(x)
> print funcB(y)
> 
>  And this is the output in IDLE after execution:
> 
> *Please type a number: 5
> 5
> Please type another number: 10
> 10
> 10 is greater than 5
> Both are positive numbers!
> 5 is odd
> None
> 10 is even
> None*
> 
>  
> I don't understand why I am getting 2 instances of "None" in the output, 
> when it has not been programmed by me. What is going on?
>  
> Pls. advice
>  
> Thanks again,
> V

You print inside your function (print x, "is odd") and you print the 
result of your function (print funcA(x)). As your function doesn't 
explicitly return a value, you get None, see: 
http://www.python.org/doc/2.4.2/tut/node6.html#SECTION00660
So either just call the function or return the string from your function.

HTH,
Wolfram

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


Re: [Tutor] Links for programming using MySQL

2006-01-19 Thread Wolfram Kraus
John Joseph wrote:
> Hi I  wanted  to try out python with MySQL databases , I would like
> to get info about the link to sites , which gives you examples on how
> to do  python programming  by using MySQL database Please guide 
> Thanks Joseph John
> 
> 
Try this one:
http://sourceforge.net/docman/?group_id=22307

HTH,
Wolfram

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


Re: [Tutor] Indexing in a series for a newbie

2006-01-19 Thread Wolfram Kraus
Jon Moore wrote:
> Hello
> 
> I need some help for a program I am writing as a newbie to Python.
> 
> I have created a series:
> 
> WORDS = ("python", "program", "code", "xylophone")
> 
> and then assigned one of them randomly to the variable 'word':
> 
> word = random.choice(WORDS)
> 
> I know that if I do:
> 
> print word
> 
> The randomly chosen word will be displayed. I also know that if I type:
> 
> print WORDS[x]
> 
> I will get the corresponding word back. But how do I find 
> 'programaticaly' the index number for the string that random.choice has 
> chosen?
> 
> The reason I ask is that I an writing a simple word jumble game and need 
> to link the randomly chosen word to a hint should the user need one.
> 
> -- 
> Best Regards
> 
> Jon Moore
You can convert your WORDS-tuple to a list and use the index() method:

idx = list(WORDS).index(word)

HTH,
Wolfram

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


Re: [Tutor] [newbie alert] why can't I find a function that gives me the sign of an integer?

2006-01-27 Thread Wolfram Kraus
Rinzwind wrote:
> In basic I can use SGN to get back -1, 0,  +1 if a number is <0, 0, >0.
> I searched on  the web for a bit but sgn and sign give me way too many 
> discussions about Decimals. python.org  with 
> numbers/digits doesn't tell about a function.
> 
> Maybe Python uses a different name for it so I am not looking for the 
> correct wording :( Sucks not knowing syntax from my memory and having to 
> look them up alot).
> 
> Wim
> 
> 
If you can accept False,0,True instead of -1,0,1 you can use:
x and x == abs(x)

HTH,
Wolfram

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


Re: [Tutor] [newbie alert] why can't I find a function that gives me the sign of an integer?

2006-01-27 Thread Wolfram Kraus
Rinzwind wrote:
> In basic I can use SGN to get back -1, 0,  +1 if a number is <0, 0, >0.
> I searched on  the web for a bit but sgn and sign give me way too many 
> discussions about Decimals. python.org  with 
> numbers/digits doesn't tell about a function.
> 
> Maybe Python uses a different name for it so I am not looking for the 
> correct wording :( Sucks not knowing syntax from my memory and having to 
> look them up alot).
> 
> Wim
> 
> 
> 
D'Oh!

It works with -1/0/1, too:
x and x/abs(x)

 >>> x = -2
 >>> x and x/abs(x)
-1
 >>> x = 2
 >>> x and x/abs(x)
1
 >>> x = 0
 >>> x and x/abs(x)
0

HTH,
Wolfram

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


Re: [Tutor] Todays Learning Python Question From a Newbie ;)

2006-02-02 Thread Wolfram Kraus
Jon Moore wrote:
[...]

> Thanks to  André, there is a way to win every time if you take the first 
> move (see below), so there MUST be a whole in the computers stratergy! 
> Based on what we all know about the game, I would say that you can not 
> make it so that the computer can win every time, but it should be 
> possable to make it tie.
> 
> x: 0
> o: 4
> x: 7
> o: 2
  ^
Make this 6,3,8 or 5 and it will be a tie

> x: 6
> 
> 0 | 1 | 2
> -
> 3 | 4 | 5
> -
> 6 | 7 | 8
> 
>


Wolfram

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


Re: [Tutor] unable to insert data into database

2006-02-17 Thread Wolfram Kraus
Servando Garcia wrote:
> Hello to all
> I have been trying to insert data into a database using MySQLdb  
> with no success. I have no idea why this script is not working. I took 
> it from a tutorial from DEV Shed.
> 
> #!/usr/bin/python
> import MySQLdb
> # connect
> db = MySQLdb.connect(host="localhost", user="root", 
> passwd="**",db="tutorial")
> 
> # create a cursor
> cursor = db.cursor()
> 
> #User Input
> name = raw_input("Please enter a name: ")
> color = raw_input("Please enter a color: ")
> 
> #Insert data into table "Horses"
> cursor.execute("INSERT INTO horses(Names,Color) VALUE (%s,%s)",(name,color))
> 
> 
First of all: Does the database "tutorial" exists? Is there a table 
"horses" in that database?
Please show the complete error message you get. The code looks good so far.

HTH
Wolfram

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


Re: [Tutor] unable to insert data into database

2006-02-17 Thread Wolfram Kraus
Wolfram Kraus wrote:
> Servando Garcia wrote:
> 
>>Hello to all
>>I have been trying to insert data into a database using MySQLdb  
>>with no success. I have no idea why this script is not working. I took 
>>it from a tutorial from DEV Shed.
>>
>>#!/usr/bin/python
>>import MySQLdb
>># connect
>>db = MySQLdb.connect(host="localhost", user="root", 
>>passwd="**",db="tutorial")
>>
>># create a cursor
>>cursor = db.cursor()
>>
>>#User Input
>>name = raw_input("Please enter a name: ")
>>color = raw_input("Please enter a color: ")
>>
>>#Insert data into table "Horses"
>>cursor.execute("INSERT INTO horses(Names,Color) VALUE (%s,%s)",(name,color))
>>
>>
> 
> First of all: Does the database "tutorial" exists? Is there a table 
> "horses" in that database?
> Please show the complete error message you get. The code looks good so far.
> 
> HTH
> Wolfram
> 

Servando Garcia wrote:
##
I have tested the database from a MySQL command line and yes the 
database exists so does the table. The code runs without error but the 
database is not affected
##

Please keep the replies on the list!

Sorry for asking the obvious (Database/Table exists)! You are missing

db.commit()
db.close()

in your code. IIRC auto-commit was switched of for MySQLdb long time ago.

HTH,
Wolfram

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


Re: [Tutor] need to automate connection

2006-04-25 Thread Wolfram Kraus
Payal Rathod wrote:
> On Tue, Apr 25, 2006 at 06:59:29PM +1200, Liam Clarke wrote:
> 
>>Hi Payal,
>>
>>I see you're connecting to an smtp server Any particular reason yoou
>>can't use smtplib?
>>http://www.python.org/doc/current/lib/module-smtplib.html
> 
> 
> Because I don't know it exists :)
> 
> But I don't want to send any mail. I just want to establish a connection 
> send MAIL TO: and RCPT TO: and exit.
> Any ideas with that? With warm regards,
> -Payal

What about telnetlib? ;-)

http://docs.python.org/lib/module-telnetlib.html

HTH,
Wolfram

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


Re: [Tutor] Nested list comprehensions

2006-05-15 Thread Wolfram Kraus
Kent Johnson wrote:
> John Fouhy wrote:
> 
>>On 15/05/06, Kent Johnson <[EMAIL PROTECTED]> wrote:
>>
>>>You can come pretty close with generators, though it hurts to think
>>>about what is actually going on behind the scenes here:
>>>
>>>In [1]: import itertools
>>>
>>>In [2]: def fibs():
>>>...: yield 0
>>>...: yield 1
>>>...: fib1 = fibs()
>>>...: fib2 = fibs()
>>>...: fib2.next()
>>>...: for a, b in itertools.izip(fib1, fib2):
>>>...: yield a+b
>>
>>Yikes!
>>
>>f = fibs()
>>for i in range(100):
>>start = time.clock()
>>x = f.next()
>>dur = time.clock() - start
>>print i, x, dur
>>if dur > 10:
>>break
>>
>>0 0 2.03936533833e-005
>>1 1 5.5873022968e-006
>>2 1 1.59238115459e-005
>>3 2 1.25714301678e-005
>>4 3 1.9580388e-005
>>5 5 2.1538427e-005
>>6 8 2.9370582e-005
>>7 13 6.0699203e-005
>>8 21 7.87809623849e-005
>>9 34 0.000119568269152
>>10 55 0.000383568302675
>>11 89 0.000409269893241
>>12 144 0.000650082622233
>>13 233 0.000979454092629
>>14 377 0.00172200656787
>>15 610 0.00713330884232
>>16 987 0.00450979104886
>>17 1597 0.0128720270314
>>18 2584 0.0150373860365
>>19 4181 0.0283779083654
>>20 6765 0.0490199173359
>>21 10946 0.135228918759
>>22 17711 0.240615497221
>>23 28657 0.365666586116
>>24 46368 0.827867508301
>>25 75025 2.14721368219
>>26 121393 4.08266218193
>>27 196418 20.1769099145
>>
>>Hmm, do you know an easy way to check how much memory python is using?
>> My HDD was swapping like crazy by the end of that..
> 
> 
> Does the Haskell version do any better? ISTM this formulation is 
> fundamentally inefficient; calculating fib(n) is going to create 
> something like fib(n-1) fib objects. In the Python case each fib is a 
> generator which I imagine means it has some kind of stack frame 
> associated with it.
> 
> Kent
> 
fib is the standard use-case for the memoize decorator:
http://wiki.python.org/moin/PythonDecoratorLibrary#head-11870a08b0fa59a8622201abfac735ea47ffade5

HTH,
Wolfram

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


Re: [Tutor] partial string matching in list comprehension?

2006-05-26 Thread Wolfram Kraus
doug shawhan wrote:
> I have a series of lists to compare with a list of exclusionary terms.
> 
> 
> 
> junkList =["interchange",  "ifferen", "thru"]
> 
> The comparison lists have one or more elements, which may or may not 
> contain the junkList elements somewhere within:
> 
> l = ["My skull hurts", "Drive the thruway", "Interchangability is not my 
> forte"]
> 
> ... output would be
> 
> ["My skull hurts"]
> 
> I have used list comprehension to match complete elements, how can I do 
> a partial match?
> 
> def removeJunk(reply, junkList):
> return [x for x in reply if x not in junkList]
> 
> It would be so much prettier than searching through each list element 
> for each term - I tend to get lost in a maze of twisty corridors, all alike.
> 
> Thanks!
> 
> 
Dunno if the performance of this solution is good and if it is more 
readable then RegExps, but here is LC:
[x for x in l if not [j for j in junkList if x.lower().find(j) > -1]]

 >>> l = ["My skull hurts", "Drive the thruway", "Interchangability is 
not my forte"]
 >>> junkList =["interchange",  "ifferen", "thru"]
 >>> [x for x in l if not [j for j in junkList if x.lower().find(j) > -1]]
['My skull hurts', 'Interchangability is not my forte']
   ^ Is there an "e" missing?

Because I don't like RegExps! ;-)

HTH,
Wolfram

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


Re: [Tutor] partial string matching in list comprehension?

2006-05-26 Thread Wolfram Kraus
Kent Johnson wrote:
> Wolfram Kraus wrote:
> 
>>doug shawhan wrote:
>>
>>>I have a series of lists to compare with a list of exclusionary terms.
>>>
>>>
>>>
>>>junkList =["interchange",  "ifferen", "thru"]
>>>
>>>The comparison lists have one or more elements, which may or may not 
>>>contain the junkList elements somewhere within:
>>>
>>>l = ["My skull hurts", "Drive the thruway", "Interchangability is not my 
>>>forte"]
>>>
>>>... output would be
>>>
>>>["My skull hurts"]
>>>
>>>I have used list comprehension to match complete elements, how can I do 
>>>a partial match?
>>>
>>>def removeJunk(reply, junkList):
>>>return [x for x in reply if x not in junkList]
>>>
>>>It would be so much prettier than searching through each list element 
>>>for each term - I tend to get lost in a maze of twisty corridors, all alike.
>>>
>>>Thanks!
>>>
>>>
>>
>>Dunno if the performance of this solution is good and if it is more 
>>readable then RegExps, but here is LC:
>>[x for x in l if not [j for j in junkList if x.lower().find(j) > -1]]
> 
> A little cleaner is
> [ j for j in junkList if j not in x.lower() ]
> 
> This will compute x.lower() for each element of junkList...
> 
> Kent
> 

Ahh, yes. Stupid old string methods :-S
But you are not quite correct, it has to be

[x for x in l if not [j for j in junkList if j in x.lower() ]]

See the "not"-ed parts ;-)

Wolfram

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


Re: [Tutor] [tutor] debug process

2006-06-12 Thread Wolfram Kraus
[EMAIL PROTECTED] schrieb:
> Hello,
> 
> Is there a way to debug (trace) the python code line by line?
> 
> emily
> 

Hi emily!

You can use The Python Debugger or pdb, see:
http://www.python.org/doc/2.4.2/lib/module-pdb.html

HTH,
Wolfram

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


Re: [Tutor] about copy.copy

2006-07-18 Thread Wolfram Kraus
On 18.07.2006 09:58, linda.s wrote:
> But in the following example, a/b/c change and it looks like there is
> no difference.
 a=[[1,2,3], [4,5,6]]
 b=a
 c=copy.copy(a)
 a[0][0]='a'
 a
> [['a', 2, 3], [4, 5, 6]]
 b
> [['a', 2, 3], [4, 5, 6]]
 c
> [['a', 2, 3], [4, 5, 6]]
> 

If you wanna do this, you need copy.deepcopy. See
http://docs.python.org/lib/module-copy.html for an explanation

HTH,
Wolfram

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


Re: [Tutor] more rps

2006-08-15 Thread Wolfram Kraus
On 15.08.2006 08:42, Christopher Spears wrote:
> Here is the latest version of my Rock, Paper, Scissors
> game:
> 
> #!/usr/bin/python
> 
> import random
> random.seed()
> 
> class Human:
>   def __init__(self):
>   self.points = 0
>   self.choice = " "
>   
>   def plays(self):
>   fromUser = raw_input("Pick (R)ock, (P)aper, or
> (S)cissors! ")
>   translate = {'r':'rock', 's':'scissors',
> 'p':'paper'} 
>   try:
>   self.choice = translate[fromUser.lower()]
>   except KeyError:
>   print 'Invalid Response'
>   
> class Computer:
>   def __init__(self):
>   self.points = 0
>   self.choice = " "
>   
>   def plays(self):
>   comp_choice = random.randint(0,2)
>   if comp_choice == 0:
>   self.choice = 'rock'
>   elif comp_choice == 1:
>   self.choice = 'paper'
>   else:
>   self.choice = 'scissors'
>   
> def compare_objects(human, computer):
>   print "Human picked ", human.choice
>   print "Computer picked", computer.choice
>   results = { 'rock' : {'rock' : 'draw', 'paper': 0,
> 'scissors': 1},
>   'paper' : {'rock' : 1, 'paper': 'draw', 'scissors':
> 0},
>   'scissors' : {'rock' : 0, 'paper' : 1, 'scissors' :
> 'draw'}
>   }
>   
>   outcome = results[human.choice][computer.choice]
>   if outcome == 0:
>   print "Computer Wins!"
>   computer.points = computer.points + 1
>   elif outcome == 1:
>   print "Human Wins!"
>   human.points = human.points + 1
>   else:
>   print "Draw!"
>   
> 
> if __name__ == "__main__":
>   print "Welcome to Rock, Paper, Scissors!"
>   final_points = raw_input("Play to how many points? ")
>   human = Human()
>   computer = Computer()
>   while (human.points < final_points or computer.points
> < final_points):
>   human.plays()
>   computer.plays()
>   compare_objects(human, computer)
>   print "Score:\tHuman: ",human.points,"\tComputer:
> ",computer.points
>   print "Game Over!"
>   
>   
> I actually figured out how to build the 2x2 matrix. 
> I'm quite proud of this.  Like all of my good ideas,
> the answer came to me in the shower. :-)
> 
> Unfortunately, my while loop doesn't seem to be
> working.  I've played around with it with no success. 
> Hints, anyone?
> 

Look at the type of human.points and final_points:

>>> final_points = raw_input("Play to how many points? ")
Play to how many points? 10
>>> type(final_points)

>>> 1 < final_points
True
>>> 100 < final_points
True
>>> 1000 < final_points
True

HTH,
Wolfram

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


Re: [Tutor] how to wirte code In python :str = (a>b?"Yes":"NO")

2007-02-16 Thread Wolfram Kraus
On 16.02.2007 08:01, xiufeng liu wrote:
> Hi, all,
> 
> In python if there is any similar way like in Java, or C++ to express
> the following:
> str = (a>b?"Yes":"NO")
> 
> 
> thanks!

In Python 2.5 you can do the following (untested):

str = "Yes" if a>b else "No"

See: http://docs.python.org/whatsnew/pep-308.html

HTH,
Wolfram

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


Re: [Tutor] hypotenuse

2008-03-14 Thread Wolfram Kraus
Am 14.03.2008 09:40, Alan Gauld schrieb:
>>> Why can you not use something like:
>>>
>> hypotenuse = hyp_squared**1/2
> 
> And for completeness that could also be written:
> 
> hypotenuse = pow(hyp_squared,1/2)
> 
> Again, without the need to import math.
> 
But beware of the integer divison in Python:

 >>> pow(2,1/2)
1
 >>> pow(2,.5)
1.4142135623730951
 >>> pow(2,1.0/2)
1.4142135623730951

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


Re: [Tutor] Strip?

2008-04-30 Thread Wolfram Kraus

Am 30.04.2008 16:18, Hansen, Mike schrieb:

strip(  s[, chars])
Return a copy of the string with leading and trailing characters
removed. If chars is omitted or None, whitespace characters are removed.
If given and not None, chars must be a string; the characters in the
string will be stripped from the both ends of the string this method is
called on. Changed in version 2.2.3: The chars parameter was added. The
chars parameter cannot be passed in earlier 2.2 versions. 


What characters are included as whitespace characters? Spaces? Tabs?
Newlines? For some reason, I was reading whitespace as just spaces.

Mike


See http://docs.python.org/lib/node39.html

"whitespace
A string containing all characters that are considered whitespace. 
On most systems this includes the characters space, tab, linefeed, 
return, formfeed, and vertical tab. Do not change its definition -- the 
effect on the routines strip() and split() is undefined."


HTH,
Wolfram


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


Re: [Tutor] String Replacement question

2008-05-21 Thread Wolfram Kraus

Am 21.05.2008 11:35, Faheem schrieb:

Hi all,
 How do I replace the same value multiple times without repeating the
same variable name/value repeatedly?
for ex.  

 some = 'thing' 
 print '%s %s %s %s' % (some,some,some,some)


in this case, my question is how do i replace "% (some,some,some)" with
something more concise?

thanks in advance,
Faheem


Hi!

Two possible solutions:

print "%s %s %s %s" % (tuple([some]*4))

print " ".join([some for x in range(4)])

HTH,
Wolfram

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


Re: [Tutor] help for building tui?

2008-07-03 Thread Wolfram Kraus

Am 04.07.2008 08:33, Dong Li schrieb:

Hi, everyone

If I want to create a text user interface for my application, is there
any existed module to facilitate such building?



Yes, there is curses:

http://docs.python.org/lib/module-curses.html
http://www.amk.ca/python/howto/curses/

HTH,
Wolfram

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


Re: [Tutor] what does the "@" operator mean?

2008-12-17 Thread Wolfram Kraus

Am 16.12.2008 02:03, Alan Gauld schrieb:


"Marc Tompkins"  wrote


If you're just starting out in Python, decorators can be hard to get
your head around...


I've been using Python for oover 10 years and still find decorators
hard to get my head around! :-)

I confess I'm not a fan, they go against the Python spirit of
explicit is best in my opinion. If I'm calling a function I like to
know I'm calling a function... I know they make the code look
pretty but IMHO they are a pain to debug and I'm never totally
convinced I've got it exactly right.

Alan G


Just found this via dzone.org: 
http://gumuz.nl/weblog/simple-python-decorator-classes/


Very interesting read.

HTH,
Wolfram

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