Re: [Tutor] Boolean question

2011-03-15 Thread Jack Trades
On Wed, Mar 16, 2011 at 12:22 AM, Donald Bedsole wrote:

>
> not (False and True)
>
> Python evaluates it as "True"
>
> Is it because:
> 1)You evaluate what's in the parentheses first.  A thing can not be
> false and true at the same time, so the answer is false.
>

Yes, the expression in the parenthesis is evaluated first.  However it's not
just one thing being evaluated.

'and' evaluates one argument at a time and returns immediately if the
argument is False.

In this case there are 2 distinct 'things'.  False and True.  False,
obviously, evaluates to False, which causes 'and' to stop and return False.
This reduces the expression to...

not False


> 2)However, the "not" outside the parentheses flips the meaning of what
> is inside the parentheses, so false becomes "True." ?
>

Correct, the expression "not False" evaluates to True.

-- 
Jack Trades
Pointless Programming Blog <http://pointlessprogramming.wordpress.com>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Boolean question

2011-03-15 Thread Jack Trades
On Wed, Mar 16, 2011 at 1:24 AM, Donald Bedsole  wrote:

>
> Ok, so, as another example:
>
> not(True and False) is "True"
>
> because: the first argument "True" is true, and the second argument
> "False" when returned is negated by "not" becomes "not False" which
> evaluates to True?
>
>
Correct.  When Python sees (True and False) it first evaluates True, which
is obviously True.  Because the first argument was not False, it continues
on and evaluates False.  At this point Python stops evaluating anything else
(for example if you had (True and False and True)) and returns False, which
is then negated by 'not'.


-- 
Jack Trades
Pointless Programming Blog <http://pointlessprogramming.wordpress.com>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] time taken to execute certain task

2011-03-16 Thread Jack Trades
On Wed, Mar 16, 2011 at 9:40 PM, tee chwee liong  wrote:

>  hi,
>
> i would like to know the time taken to execute a certain task in python. i
> used time.time and time.clock and i see the time taken is different? what is
> the right method to use?
>
> import time
> def testtime(num):
> start=time.time()
> #print start
> for n in range(num):
> #print n
> print time.time()-start
>
> testtime(101)
>
> start = time.clock()
> for x in range(101):
>   y = x  # do something
> end = time.clock()
> print "Time clock elapsed = ", end - start, "seconds"
>
> thanks
> tcl
>
>

First you have to start by testing things that are similar.  I've rewritten
your tests to look exactly the same except for the time.time() or
time.clock().

In your first example, you are calculating an end time for each iteration of
the for loop.  In your second example you are only calculating the end time
once, after the for loop has finished.

Here's how I would compare them...

(I hope the indentation doesn't get hosed.  If it does I can repost.)

import time

def testtime(num):
  start = time.time()
  for n in range(num):
1 + 1 # do something
  print time.time() - start

testtime(101)
#===> 3.50475311279e-05

def testclock(num):
  start = time.clock()
  for n in range(num):
1 + 1  # do something
  print time.clock() - start

testclock(101)
#===> 0.0

Now that each test is exactly the same, you are in a better position to
judge the differences.  And there are some obvious differences!  Why?  To
determine that you need to find out just what each function is supposed to
return.

The help() function will show you what each function (time or clock) is
supposed to return.  It looks like this...


help(time.time)
time(...)
time() -> floating point number

Return the current time in seconds since the Epoch.
Fractions of a second may be present if the system clock provides them.

help(time.clock)
clock(...)
clock() -> floating point number

Return the CPU time or real time since the start of the process or since
the first call to clock().  This has as much precision as the system
records.


As you can see, time.time() returns the current time in seconds from the
Epoch, while time.clock() returns the time since the program started, or the
time since the first call to time.clock().

The "epoch" is an arbitrary point in the past (don't rely on it always being
the same).  So both time.time() and time.clock() return the number of
seconds, but each of them starts at a different time.

As to which one's best?  I don't know.  I know there are some profiling
tools that will give you a better idea about the performance of a function,
but I rarely use them so I'll let someone else give you advice on this.

For a quick-n-dirty test, either will work just fine.  I usually use
time.time(), but I only really ever do this "just for kicks".

-- 
Jack Trades
Pointless Programming Blog <http://pointlessprogramming.wordpress.com>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Print/Loop Question

2011-03-17 Thread Jack Trades
On Thu, Mar 17, 2011 at 1:19 PM, Jeff Goodwin wrote:

> I'm trying to run the below program and get it to print out feedback as the
> loop goes. However, if you enter a number too high or too low, it skips the
> print statement under the if and elif clauses and asks the user to "Guess a
> number between 1-100" again. Any suggestions on how to get it to print the
> "too high" and "too low" responses?? Once the number is entered correctly it
> prints "Just Right" and exits correctly.
>
> number = 44
>
> while guess != number :
> guess = int(raw_input("Guess a number between 1 - 100: "))
> *if* guess > number :
> *print* ("Too high")
>
> *elif* guess < number :
> *print* ("Too low")
> *else*:
> *print* ("Just right" )
>

Your solution is correct, except for one thing.

When you start the while loop 'guess' is not yet defined.  That's why it
gives you an error.  You need to define 'guess' before you start your while
loop, like so...

number = 44
guess = 0

while guess != number :
  guess = int(raw_input("Guess a number between 1 - 100: "))
  if guess > number :
print ("Too high")
  elif guess < number :
print ("Too low")
  else:
print ("Just right" )

After that change it worked for me.  Did you get this error when you tried
your code?

Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'guess' is not defined

>From your question it sounds like I might be missing something though.  If
that didn't help, please provide more details.

-- 
Jack Trades
Pointless Programming Blog <http://pointlessprogramming.wordpress.com>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python

2011-08-14 Thread Jack Trades
On Sun, Aug 14, 2011 at 8:04 AM, je.rees e-mail  wrote:

> I have made a small program but I would like to know how to write or. There
> is multiple choice answer.
> Good=raw_input("Good to hear")
> ok=raw_input("Good good")
> Bad=raw_input("Oh dear")
> I would only like the person using the program to be able to pick one.
>
> Thanks
>

You might want to try something like this...

def ask():
  ans = raw_input("Please enter (g)ood, (o)k or (b)ad: ")

  if ans == "g" or ans == "good":
print "Good to hear"
  elif ans == "o" or ans == "ok":
print "Good good"
  elif ans == "b" or ans == "bad":
print "Oh dear"
  else:
print "Incorrect choice"

ask()

And here's how it works...

>>> ask()
Please enter (g)ood, (o)k or (b)ad: b
Oh dear
>>> ask()
Please enter (g)ood, (o)k or (b)ad: o
Good good
>>> ask()
Please enter (g)ood, (o)k or (b)ad: ok
Good good

Or you could also use something a bit more general like this...

def ask(question, list_of_responses):
  ans = raw_input(question)
  return list_of_responses[int(ans)]

>>> ask("(0)Good (1)OK (2)Bad: ", ["Good to hear", "Good good", "Oh dear"])
(0)Good (1)OK (2)Bad: 0
'Good to hear'


-- 
Jack Trades <http://www.rentageekit.com>
Pointless Programming Blog <http://pointlessprogramming.wordpress.com>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need advice about a dictionary ({})

2011-09-10 Thread Jack Trades
On Sat, Sep 10, 2011 at 1:08 PM, Richard D. Moores wrote:

> So I've done quite a bit more work. With phone_book.py the user can
> not only access phone numbers by the person's initials, but can add
> items to the data file. I've also solved the problem of adding a
> person who's initials have already been used in a key.
>
> I've pasted phone_book_for_pasting.py at .
>
> I'd appreciate any comments, instructive criticism, etc.
>
>
It looks pretty good overall, though I didn't examine it too closely.  IMHO
there are some awkward bits which I think come from your representation of
the data.

I would probably make the phonebook itself a list, with each entry being a
dict.  Something like:

book = [
{'name':'Mark Sanders', 'cell':'422-318-2346', '
email':'msand...@stanfordalumni.org'},
{'name':'AAA', 'phone':'575-3992', 'phone2':'1-800-472-4630',
'notes':'Membership #422 260 0131863 00 8'},
#...
]


Then you can easily search your phone book by name, email, type of contact,
relation, etc.  A search by name would look like this:

def find_by_name(name):
  for entry in book:
if entry['name'] == name:
  return entry

find_by_name('Mark Sanders')
#==> {'name':'Mark Sanders', 'cell':'422-318-2346', '
email':'msand...@stanfordalumni.org}

or a more general procedure for doing searches on your book could be:

def find(criteria, term):
  for entry in book:
if entry[criteria] == term:
  return entry

find('name', 'Mark Sanders')
#==> {'name':'Mark Sanders', 'cell':'422-318-2346', '
email':'msand...@stanfordalumni.org}


Similarly you could search for initials by providing a to_initials
procedure:

def to_initials(name):
  return ''.join([i[0] for i in name.split(' ')])

def find_by_initials(initials):
  for entry in book:
if to_initials(entry['name']) == initials:
  return entry

find_by_initials('MS')
#==> {'cell': '422-318-2346', 'name': 'Mark Sanders', 'email': '
msand...@stanfordalumni.org'}


Adding a new entry would then be as simple as:

def add_new_entry(entry, book):
  book.append(entry)


For storing data I would probably use Pickle, which would look something
like this:

from cPickle import load, dump

f = open('book.pk', 'w')
dump(book, f)
f.close()

and loading your book is similar

f = open('book.pk', 'r')
book = load(f)
f.close()


If you want a human readable storage format I would look into json, but
pickle has served me well for most purposes.  Surely you can store your
phonebook as plain text and parse it the way you have, but it's not
necessary to do that with all the tools that exist for that purpose.


-- 
Nick Zarczynski
Pointless Programming Blog 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need advice about a dictionary ({})

2011-09-10 Thread Jack Trades
On Sat, Sep 10, 2011 at 4:36 PM, Richard D. Moores wrote:

> Your idea doesn't seem efficient for me --
> lots of typing and editing.
>

Not sure what you mean by that?  I've updated the gist with a quick 5min
implementation of a GUI using Tkinter and the approach I outlined.  I think
using a GUI is best way to minimize "typing and editing" in an app like
this.  You can find it here:

https://gist.github.com/1208786#file_book.py

If you're talking about re-entering all your data from your file, you would
write a script to do that.  This program assumes that you are starting from
scratch with a blank phone book.  If you would like help converting your
existing file, I'm sure I or others can help, but I'd need to see the
original file.

-- 
Nick Zarczynski
Pointless Programming Blog 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need advice about a dictionary ({})

2011-09-10 Thread Jack Trades
>
> Using Python 2.7 for it, it seems to work fine, except that I can't
> see how the GUI helps. It opens only when I use the g option to find
> an entry already made. Useful for editing an entry, though.
>

Well the idea would be to build the app as a full-blown GUI.  The GUI search
and edit functionality was just a proof-of-concept to show how that may
work.

I was just having some fun and seeing what I could do in less than an hour.
Turning this into a full blown app is not what I had in mind, though if you
want to build on it to learn I would be willing to help.


>
> As for the non-GUI script, I get this error no matter which choice I
> make. I'm too dumb, and have forgotten too much of Python 2.x to
> debug:
>
> ==
> What's next:
> (q)  Quit
> (a)  Add new Entry
> (v)  View all Entries
> (s)  General Search
> (si) Search by Initials
> (sn) Search by Name
>
> > q
> Traceback (most recent call last):
>  File "c:\P32Working\Pickles\nicks_simple_phone_book_app.py", line
> 171, in 
>main_loop()
>  File "c:\P32Working\Pickles\nicks_simple_phone_book_app.py", line
> 94, in main_loop
>> """)
>  File "", line 1, in 
> NameError: name 'q' is not defined
> Process terminated with an exit code of 1
> 
>

My guess is that this has something to do with Python 3.x not having
raw_input.  Try changing the raw_input calls to input.  I don't get that
error with 2.7.



>
> > If you're talking about re-entering all your data from your file, you
> would
> > write a script to do that.
>
> Ha! I would?
>
>
Well, yeah.


A line in the file always begins with a name, with  at
> least one phone number, then if a company, the hours they are
> reachable by phone, possibly their web address, maybe an email
> address, my contact there plus maybe her secretary. If a physician,
> there might very well be his specialty, his nurse's name, mention of
> who recommended him to me, etc.


Like I said, I'd have to see the file to comment more, but it sounds like it
may be too irregular to make writing a script an easy process.  Though I
can't be sure without seeing it.  You could always enter these things by
hand...

I should probably ask; what is your goal for this app?  Is it to learn some
Python while making a usable app?  Or are you looking for a robust address
book for quick lookups of information?  If it's the latter, I'd recommend
you look around for something that's already made.  It will save you a lot
of trouble in the long run.

If you're looking for a good learning experience this kind of app is a great
starting place.  However expect to run into problems along the way, up to
and possibly beyond possibly hosing all the data you have entered into the
app.  Make regular backups of the data and keep your original around.


> It seems that the format of info for
> your way is set rigidly in advance, or am I wrong?
>
>
Not really.  Key/value pairs can be entered in arbitrary order.  I used = to
seperate key/values because that's what you used in your app and | to
seperate k/v pairs to allow spaces without quoting strings.  You could
easily replace these tokens (= or |) with whatever you want.

If you have another format that differs by more than those characters you
would need to write a different parser.  However there does have to be some
consistency to the format of your data to make parsing easier.  The less
rigid your data the more work you will have to do to parse it.  Since you
said earlier that you will probably have less than 100 entries in your phone
book, you may want to think about restructuring your data by hand to make it
easier to parse before writing your parser.

-- 
Nick Zarczynski
Pointless Programming Blog 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor