Re: [Tutor] need idea

2010-02-10 Thread Andre Engels
On Wed, Feb 10, 2010 at 10:27 PM, invincible patriot
 wrote:
> hi
> i want to compare a string with a dictionary
> or u can say that i want to take user input A STRING, and want to compare
> each character of that string with the KEYS  in the dictionary, and then i
> wana print the values for the characters that are present in that strinng
> that we got as the input and were present in the dictionary as well
>
> can you please give me some idea how to do that
>
> what i hav done is that
> 1) I have made a dictionary with the keys and the values
> 2) I have taken the input from the user and hav saved it into a variable
>
> not i wana compare string that was given to us and replace them with the
> values given in the dictionary

It's not yet completely clear to me what you want, but the following
should help you:

Let str be the string, and dict the dictionary, then:

[c for c in str if c in dict]

will give you the characters in the string that are keys in the dictionary.




-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need idea

2010-02-10 Thread Andre Engels
On Thu, Feb 11, 2010 at 12:12 AM, invincible patriot
 wrote:

> thanks
> let me clear you that what i am trying to do
> suppose we hav a input string and a dict
> our_dict={'a':'u', 't':'a', 'c':'g', 'g':'c'}
> input_string='atcg'
>
>
> now what i wana do is that where ever we are having 'a' i wana replace it
> with 'u', 't' with 'a' and so on
> i tried using input_string.replace('a', 'u')
> but it is replacing only one character
> i wana replace these 4 characters according to the dictionary
>
> i hope it is now clear
>
> kindly let me know how to proceed now

See http://www.tutorialspoint.com/python/string_translate.htm

-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] ask

2010-02-19 Thread Andre Engels
On Sat, Feb 20, 2010 at 8:07 AM, Shurui Liu (Aaron Liu)
 wrote:
> How to describe a math formula: sphere=(4/3)*PI*R**3?

A function seems like the logical thing to do:

import math

def spherical_volume(radius):
return (4.0/3)*math.pi*radius**3

-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] matching words from a text to keys in a dictionary

2010-03-08 Thread Andre Engels
On Mon, Mar 8, 2010 at 5:05 PM, Karjer Jdfjdf  wrote:

>  I want to compare words in a text to a dictionary with values attached to
> the words.
>
> The dictionary  looks like:
> { word1: [1,2,3] word2: [2,3,4,a,b ] ... }
>

Please give the actual dictionary, not something that it 'looks like' - an
actual dictionary would never 'look like' this: it has commas between the
elements, and quotes around anything that is a word.


> I'm trying to find a way to achieve this, but I'm having trouble getting
> corrects results.
>
> If I do the def below, nothing is matched.
>
> def searchWord(text, dictionary):
> text = text.split()
> for word in text:
> print word
> if word in dictionary:
> value = dictionary[str(word)]
> else:
> value = None
> return w
>
> If I try another way, I keep getting errors:
>
> def searchWord(text, dictionary):
> for key in dictionary:
> value = dictionary[key]
> if re.search(key, text):
> w = value
> else:
> w = None
> return w
>
>
> TypeError: list indices must be integers, not str
>

That's quite a clear statement: If this is indeed caused by the function you
show here, then the only explanation is that 'dictionary' is not a
dictionary at all, but a list.


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Changing the value in a list

2010-03-11 Thread Andre Engels
On Thu, Mar 11, 2010 at 4:32 PM, Ken G.  wrote:
> If the following program change list[2] to 2010, replacing 1997 (and it
> does), why doesn't the second program work in changing line[ 9:11] to 20
> from 08?
> FIRST PROGRAM:
>
>   list = ['physics', 'chemistry', 1997, 2000]
>   print list[2]
>   list[2] = 2010
>   print list[2]
>
> OUTPUT:
>
>   1997
>   2010
>
> SECOND PROGRAM:
>   line = [2010020820841134]
>   if line[ 9:11] == "08":
>       line[ 9:11] = 20
>       print line[ 9:11]
>
> OUTPUT:
>
>   "TypeError: 'str' object does not support item assignment."
>
>
> Thanking you all in advance,

First, you seem to have made a mistake in copying your programs: In
the second program to get your error message,

line = [2010020820841134]

should read

line = "2010020820841134"

As for your question: The error message already says it better than I
do: If x is a string, then x[9] =  is not allowed, nor is
x[9:11] = .


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] First program

2010-03-12 Thread Andre Engels
On 3/12/10, yd  wrote:
> Hi,
> I am new to programming, altough i have read a few books about OOP and
> O'Reily's Learning Python.
> I would like some critique on my first program, is it normal for it to be
> this long to do something simple?

Well, many of your lines are user interface. Writing two lines of text
to the user will in general cost you (at least) two lines of code.

> I know i could have turned some of these things into classes and functions
> but i don't know how to do that yet.

I definitely see use for functions (long lists of if...elif.. are
usually better modeled using functions and a dictionary); using
classes feels like overkill for something this simple.

> Some critique of the algorithm and writing style or anything in general
> would help and any pointers would be appreciated.

General remark: The usual number of spaces indented per level is 4,
rather than the 2 that you use. This makes it easier to see the
indentation level at first glance.

> #title Area calculator
> #author Yudhishthir Singh
>
>
> #welcome screen
> msg = 'Welcome to the area calculator program '
> print(msg)
> print('-'*len(msg))
> loop = 'y'
> print()
> while loop == 'y':
>   #Choices menu
>   print('Please select a shape\n')
>   print('1. Rectangle')
>   print('2. Square')
>   print('3. Parallelogram ')
>   print('4. Trapezoid ')
>   print('5. Circle ')
>   print('6. Ellipse')
>   print('7. Traingle\n')
>   print('-'*len(msg))
>   choice = input('\nPlease enter your choice: ')
>   if choice.isdigit() ==True:
> choice = int(choice)

1. The if can be shortened to

if choice.isdigit():

2. This thing can be removed completely if you chance the if-statements below to

if choice == "1"

etcetera.

>   if choice ==1:
> #Rect
> height = input('please enter the height: ')
> width = input('please enter the width: ')
> height = int(height)
> width = int(width)
> areaRectangle = height*width
> print('\nThe area of a rectangle with {0} height and {1} width is
> '.format(height,width),areaRectangle,'\n')

I think it's ugly to mix styles here - either use format or use commas, not both

>   elif choice ==2:
> #Square
> side = input('enter the height or width: ')
> side = int(side)
> areaSquare = side**2
> print('\nThe area of a square with a height or width of {0} is
> '.format(side), areaSquare,'\n')
>   elif choice ==3:
> #Parallelogram
> height = input('enter the height: ')
> base = input('enter the width aka base: ')
> height = int(height)
> base = int(base)
> areaParallelogram = height*base
> print('\nThe area of a parrallelogram with height {0} and width {1} is
> '.format(height,base), areaParallelogram,'\n')
>   elif choice ==4:
> #Trapezoid
> height = input('enter the height: ')
> base1 = input('enter the width of shorter side: ')
> base2 = input('enter the width of longer side: ')
> height = int(height)
> base1 = int(base1)
> base2 = int(base2)
> areaTrapezoid = (height/2)*(base1+base2)
> print('\nThe area of a trapezoid with height {0} ,base {1} and {2} is
> '.format(height,base1,base2), areaTrapezoid, '\n')
>   elif choice ==5:
> #Circle
> radius = input('radius: ')
> radius = int(radius)
> areaCircle = 3.14*(radius**2)
> print('\nThe area of a circle with radius {0} is '.format(radius),
> areaCircle, '\n')
>   elif choice ==6:
> #Ellipse
> radius1 = input('enter length of radius 1: ')
> radius2 = input('enter length of radius 2: ')
> radius1 = int(radius1)
> radius2 = int(radius2)
> areaEllipse = 3.14*radius1*radius2
> print('\nThe area of an ellipse with radii of length {0} and {1} is
> '.format(radius1,radius2), areaEllipse, '\n')
>   elif choice ==7:
> #Triangle
> base = input('enter base: ')
> height = input('enter height: ')
> base = int(base)
> height = int(height)
> areaTriangle = (1/2 *base)*height
> print('\nThe area of a triange with height {0} and base {1} is
> '.format(height,base), areaTriangle, '\n')
>   else:
> raise Exception('{0}, is not a valid choice'.format(choice))

This will cause the program to stop-with-error if something wrong is
entered. I think that's quite rude. I would change this to:
  else:
print('{0}, is not a valid choice'.format(choice))

>   loop = input('Do you want to calculate the area of another shape? Y/N: ')
>   loop = loop.lower()



-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] First program

2010-03-12 Thread Andre Engels
On Sat, Mar 13, 2010 at 3:11 AM, Ray Parrish  wrote:
> Andre Engels wrote:
>>
>> On 3/12/10, yd  wrote:
>>>  else:
>>>    raise Exception('{0}, is not a valid choice'.format(choice))
>>>
>>
>> This will cause the program to stop-with-error if something wrong is
>> entered. I think that's quite rude. I would change this to:
>>  else:
>>    print('{0}, is not a valid choice'.format(choice))
>>
>
> Here's what I get from that, could you please explain why?

You're probably using Python 2.4 or 2.5; the .format method has been
introduced in Python 2.6, and is considered the 'standard' way of
working in Python 3. For older Python versions, this should read

print('%s, is not a valid choice'%(choice))




-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problem with little program

2010-03-14 Thread Andre Engels
On Sat, Mar 13, 2010 at 7:56 PM, Marco Rompré  wrote:
> Hello I have a little problem, I am trying to define a function ligneCar(n,
> ca) that would print n times the caracters ca.
> For now I have the user entering a short sentence corresponding to ca.
> Here is my code:
> def ligneCar(n,ca):
>     c=0
>     while c         print ca
>         c+=1
> ca = input ('Enter a short phrase : ')
> n = input ('Enter how many times you want  : ')
> Thats the definition of my function ligne_Car
> then in another python file
> I want to recall my function ligne_Car but it is not working.

Please give us more information - what code are you using to 'recall'
your function, what were you expecting to be the result and what is
actually the result?


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] a bug I cannot solve myself ;-)

2010-03-25 Thread Andre Engels
2010/3/25 spir ☣ :
> Hello,
>
>
> I'm writing a kind of language simulation. Here, an expression like "a#3.b" 
> maps to a NamedData node, with an attribute 
> terms=[('.','a'),('#',3),('.'''b')].
> (The lang uses '#' instead of "[...]" for item indexing.)
> When this node is "run", the source code maps to a name lookup operation in 
> current scope, passing the terms attr as argument. Below the code with debug 
> prints and the error I get and cannot understand:
>
> ==
> class Scope(Code):
>    ...
>   �...@staticmethod
>    def lookup(scope, terms):
>        ''' actual data refered to by name (or context) terms'''
>        data = scope    # actually, initial container
>        for term in terms:
>            (sign,key) = term
>            print data, (sign,ATTR,sign==ATTR,sign is ATTR), key
>            if sign == "ATTR":    # sign == ATTR='.'
>                print "getAttr"
>                data = data.getAttr(key)
>            else:                 # sign == ITEM='#'
>                print "getItem"
>                data = data.getItem(key) ### line 82 ###
>        return data
> === output ===
> currentScope ('.', '.', True, True) a
> getItem
> ... traceback ...
>  File "/home/spir/prog/python/claro/scope.py", line 82, in lookup
>    data = data.getItem(key)
> AttributeError: 'Scope' object has no attribute 'getItem'
> ==
>
> (Scopes actually have no getIem, they're plain symbol (attribute) containers.)
>
> There must be something such obvious I'm too stupid to see it! What do I 
> overlook? How can it branch to the "getItem" side of the choice?


if sign == "ATTR":

should be

if sign == ATTR:


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Iterating through a list of strings

2010-05-03 Thread Andre Engels
On Mon, May 3, 2010 at 7:16 AM, Thomas C. Hicks  wrote:
> I am using Python 2.6.4 in Ubuntu.  Since I use Ubuntu (with its every
> 6 months updates) and want to learn Python I have been working on a
> post-install script that would get my Ubuntu system up and running with
> my favorite packages quickly.  Basically the script reads a text file,
> processes the lines in the file and then does an apt-get for each line
> that is a package name.  The text file looks like this:
>
> %Comment introducing the next block of packages
> %Below are the packages for using Chinese on the system
> %Third line of comment because I am a verbose guy!
> ibus-pinyin
> ibus-table-wubi
> language-pack-zh-hans
>
> etc.
>
> I read the lines of the file into a list for processing.  To strip
> out the comments lines I am using something like this:
>
> for x in lines:
>    if x.startswith('%'):
>        lines.remove(x)
>
> This works great for all incidents of comments that are only one
> line.  Sometimes I have blocks of comments that are more than one
> line and find that the odd numbered lines are stripped from the list
> but not the even numbered lines (i.e in the above block the line
> "%Below are the ..." line would not be stripped out of the
> list).
>
> Obviously there is something I don't understand about processing
> the items in the list and using the string function x.startswith() and
> the list function list.remove(). Interestingly if I put in "print x"
> in place of the lines.remove(x) line I get all the comment lines
> printed.
>
> Can anyone point me in the right direction?

Don't change the list that you are iterating over. As you have found,
it leads to (to most) unexpected results. What's going on, is that
Python first checks the first line, finds that it needs to be deleted,
deletes it, then goes to the second line; however, at that time the
original third line has become the second line, so the original second
line is not checked.

There are several ways to resolve this problem; to me the most obvious are:
1. Get the lines from a copy of the list rather than the list itself:

 # use lines[:] rather than lines to actually make a copy rather than
a new name for the same object
linesCopy = lines[:]
for x in linesCopy:
if x.startswith('%'):
lines.remove(x)

2. First get the lines to remove, and remove them afterward:

linesToDelete = []
for x in lines:
if x.startswith('%'):
linesToDelete.append(x)
for x in linesToDelete:
lines.remove(x)

If that looks a bit clumsy, use a generator expression:

linesToDelete = [x for x in lines if x.startswith('%')]
for x in linesToDelete:
   lines.remove(x)

which idiomatically should probably become:

for x in [y for y in lines if y.startswith('%')]:
   lines.remove(x)


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Iterating through a list of strings

2010-05-03 Thread Andre Engels
On Mon, May 3, 2010 at 10:19 AM, Luke Paireepinart
 wrote:

> Hmm, why not
> lines = [line for line in lines if not line.strip().startswith('%')]

I knew I missed something


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Learning python using Michael Dawson's book

2010-05-19 Thread Andre Engels
On Tue, May 18, 2010 at 5:14 AM, Luke Paireepinart
 wrote:
> Forwarding. Peter use reply-all don't reply offlist please.
>
> -- Forwarded message --
> From: Peter 
> Date: Mon, 17 May 2010 10:08:47 -0400
> Subject: Re: [Tutor] Learning python using Michael Dawson's book
> To: Luke Paireepinart 
>
> Hi,
> The result in the book has lettering like the following:
> ___    __       __
> |    |    |    |     |    |
> |    |__|    |     |    |
> |    __     |      |    |
> |    |    |    |     |    |
> |__|    |__|     |__|

Well, that's definitely not what the code would be producing, nor does
it seem to be related to what the example claims to be doing...
Perhaps instead of

print(
   """
   """
   )

which is a very strange idiom (though valid), you should write:

print(
   """
 _____   __
 |||| ||
 ||__|| ||
 |__ |  ||
 |||| ||
 |__||__| |__|
  """
   )

or perhaps you are looking at one example and the explanation of another?



-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help

2010-07-13 Thread Andre Engels
On Tue, Jul 13, 2010 at 11:50 AM, Dipo Elegbede  wrote:
> I was trying to write a code that prints prime numbers between 1 and 20.
>
> I have by myself seen that something is wrong with my code and also my
> brain.
>
> Could anyone be kind enough to tell me what to do
>
> Where I am confused is how to test for other numbers without one and the
> number itself. It turns out that all numbers pass the condition I set so
> that would presuppose that all numbers are prime which is not.
>
> How exactly can I get it to run checks with other numbers such that it
> doesn't include the number itself and 1.
>
> The code is as follows:
>
> for i in range(1,20):
>
>     if float(i) % 1 == 0 and float(i) % i == 0:
>     print i, 'is a prime number'

Your code only checks whether the number divides by 1 and itself. It
should check the numbers in between, and if _any_ divides the number,
decide it is not a prime number. This is best done in a separate
function (note: I am writing it here for clarity of the underlying
algorithm, there are various ways in which it could be made faster,
shorter or more Pythonic):

def isPrime(n):
divisorFound = False
for i in xrange(2, n):
if n % i == 0:
divisorFound = True
return not divisorFound # divisorFound is true if and only if
there is a number i (1http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Handling 'None' (null) values when processing sqlite cursor results

2010-07-14 Thread Andre Engels
On Wed, Jul 14, 2010 at 6:31 AM, Monte Milanuk  wrote:
> Hello all,
>
> I'm struggling a bit trying to find the right way to deal with null values
> in my sqlite database when querying it and processing the results in python.
>
> If my cursor.fetchall() results return the following:
>
> (104, None, u'Sylvester', None, u'Evans', None, u'527-9210 Proin Av.',
> u'Liberal', u'VT', u'24742', u'1-135-197-1139',
> u'vehicula.pellentes...@idmollis.edu', u'2010-07-13 22:52:50', u'2010-07-13
> 22:52:50')
>
> At first I was having fits as str.join() was giving me a 'NoneType error'.
>  I found one way around that, by processing the results so the 'None' values
> got omitted from the list by the time they got to str.join().
>
> I thought that was the end of that, until I tried working with the returned
> records in another fashion and found that having the 'None' values omitted
> really messed with the list order which I was depending on i.e. list[5]
> could be different fields depending on how many 'None' values had been
> omitted.  And if I didn't omit them, when I printed out the user name in the
> format 'first''middle''last' from the above record, I got
> 'Sylvester''None''Evans' rather than just 'Sylvester''Evans' (i.e. with no
> middle initial).
>
> So... I guess my question is, is there a good/proper way to handle the
> 'None' values as returned by sqlite from a table that may have some null
> values in individual records?  Basically I want not have the None/Null
> values show up but to keep them as place holders to make sure i get the
> values in the right spots...

It depends a bit on what you want to do with the values. My preference
would be to keep the result of cursor.fetchall(), and instead
re-define the output function(s) that I use (so don't use
str.join(record), but some myjoin(str,record) that I defined). Or,
even better, to define a class for these, create an object of the
class from the fetchall result, and have things like the myjoin before
as class methods or properties.

-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help

2010-07-14 Thread Andre Engels
On Tue, Jul 13, 2010 at 12:34 PM, Nitin Pawar  wrote:
> Adding to what Andre said,
> another way of optimizing the problem would be
> storing the prime number in the range you want to check an array and see if
> the given number is divisible by any of those prime number

As I wrote, my code was not optimalized for either code size or
execution time. Other obvious speed-ups, apart from the one you
mention, are to only search up to the square root of the number
(rather than to the number minus 1), and to immediately break out of
the loop once a divisor has been found.


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Indentation woes in elif statement

2010-08-11 Thread Andre Engels
On Wed, Aug 11, 2010 at 3:11 AM, rara avis  wrote:
> Hi: I am trying to teach myself Python, and am stuck at the indentation with
> the elif statement.
> This is what I am trying to type:
>
> x=3
> if x==0:

What are you trying to accomplish? What result did you expect to get?
What result did you actually get?


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (no subject)

2010-09-05 Thread Andre Engels
On Sun, Sep 5, 2010 at 4:17 PM, Roelof Wobben  wrote:

> I understand the error message.
> I follow this example in the book :
> http://openbookproject.net/thinkcs/python/english2e/ch11.html
> And there element is not defined.

It is:

for element in nested_num_list:



-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] for loop results into list

2010-09-05 Thread Andre Engels
On Sun, Sep 5, 2010 at 8:51 PM, Micheal Beatty  wrote:
>  On 09/05/2010 01:26 PM, Evert Rol wrote:
>>>
>>> Hello all,
>>>
>>> I'm having a little problem figuring out how to accomplish this simple
>>> task. I'd like to take a list of 6 numbers and add every permutation of
>>> those numbers in groups of four. For example for 1, 2, 3, 4, 5, 6 add 1 + 1
>>> + 1 +1 then 1 + 1 + 1 +2 etc. until reaching 6 + 6 + 6 + 6. Using a for
>>> loop, that was the easy part, now I'd like to take the results and count the
>>> number of times each number occurs.
>>> My problem occurs when I try to create a list from the results of the for
>>> loop, it puts each individual number into its own list. I've looked
>>> everywhere for the solution to this and can find nothing to help.
>>>
>>> Any suggestions would be much appreciated
>>
>> If you had some code, that would be very helpful. Now it's a bit of
>> guesswork what exactly you have (code tends to be clearer than a full
>> paragraph or two of text).
>> At least, I currently don't understand what your problem is (or what your
>> for-loop involves).
>> Eg, are you looping and calling a function recursively, do you have four
>> nested loops (or nested list comprehensions)? Or some other convenient loop
>> to step through all combinations?
>>
>> Anway, if you have a recent Python version (2.7 or 3.1), the itertools
>> module provides a handy utiity:
>> http://docs.python.org/py3k/library/itertools.html#itertools.combinations_with_replacement
>> Eg,
>>
> map(sum, combinations_with_replacement(range(1,7), 4))
>>
>> [4, 5, 6, 7, 8, 9, 6, 7, 8, 9, 10, 8, 9, 10, 11, 10, 11, 12, 12, 13, 14,
>> 7, 8, 9, 10, 11, 9, 10, 11, 12, 11, 12, 13, 13, 14, 15, 10, 11, 12, 13, 12,
>> 13, 14, 14, 15, 16, 13, 14, 15, 15, 16, 17, 16, 17, 18, 19, 8, 9, 10, 11,
>> 12, 10, 11, 12, 13, 12, 13, 14, 14, 15, 16, 11, 12, 13, 14, 13, 14, 15, 15,
>> 16, 17, 14, 15, 16, 16, 17, 18, 17, 18, 19, 20, 12, 13, 14, 15, 14, 15, 16,
>> 16, 17, 18, 15, 16, 17, 17, 18, 19, 18, 19, 20, 21, 16, 17, 18, 18, 19, 20,
>> 19, 20, 21, 22, 20, 21, 22, 23, 24]
>>
>> seems to do what you want.
>>
>> But, I'd still say to adopt your own code first, and when you've learned
>> from that, just use the one-liner above. You're most welcome to ask your
>> question, best done in combination with code, actual output and expected
>> output. Then we can point you in the right direction.
>>
>> Cheers,
>>
>>   Evert
>>
> Thanks Evert, here is the code.
>
>
> fourdsix = [1, 2, 3, 4, 5, 6]
> for i in fourdsix:
>    for j in fourdsix:
>        for k in fourdsix:
>            for l in fourdsix:
>                fourdsix_result = [i, j, k, l]
>                attribs = sum(fourdsix_result) - min(fourdsix_result)
>                print attribs
>
> This gives me the proper results, now it's just a matter of getting it into
> a list so I can further work with the data.
> I've tried the following
> attrib_list = [attribs]
>
> and
> attrib_list = []
> attrib_list.append(attribs)
> print attrib_list
>
> but these both only create a list of the last number.

Put the attrib_list = [] before the beginning of the outer loop, and
it should work as intended. Now you are creating a new list each time,
which is not what you want.



-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] why do i get None as output

2010-09-06 Thread Andre Engels
On Mon, Sep 6, 2010 at 8:34 AM, Roelof Wobben  wrote:
> Hello,
>
> I have this programm:
>
> def encapsulate(val, seq):
>     if type(seq) == type(""):
>     return str(val)
>     if type(seq) == type([]):
>     return [val]
>     return (val,)
>
> def insert_in_middle(val, seq):
>     middle = len(seq)/2
>     return seq[:middle] + encapsulate(val, seq) + seq[middle:]
>
> def make_empty(seq):
>     """
>   >>> make_empty([1, 2, 3, 4])
>   []
>   >>> make_empty(('a', 'b', 'c'))
>   ()
>   >>> make_empty("No, not me!")
>   ''
>     """
>     word2=""
>     teller=0
>     if type(seq) == type([]):
>     teller=0
>     while teller < len(seq):
>     seq[teller]=""
>     teller = teller + 1
>     elif type(seq) == type(()):
>     tup2 = list (seq)
>     while teller > tup2.len():
>     tup2[teller]=""
>     teller = teller + 1
>     seq = tuple(tup2)
>     else:
>     seq = ""
>
> test = make_empty([1, 2, 3, 4])
> print test
>
> But now I get None as output instead of []
>
> Can anyone explain why that happens ?

test = make_empty([1, 2, 3, 4]) makes test equal to the return value
of make_empty. But make_empty does not return anything, and in that
case its return value is made equal to empty. Compare:

def f(x):
x = x + 1

def g(x):
x = x + 1
return x

def h(x):
return x +1

print f(1)
>> None

print g(1)
>> 2

print h(1)
>> 2


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] why do i get None as output

2010-09-06 Thread Andre Engels
On Mon, Sep 6, 2010 at 9:41 AM, Roelof Wobben  wrote:
>
>
>> To: tutor@python.org
>> From: alan.ga...@btinternet.com
>> Date: Mon, 6 Sep 2010 08:27:31 +0100
>> Subject: Re: [Tutor] why do i get None as output
>>
>>
>> "Roelof Wobben"  wrote
>>
>> def make_empty(seq):
>> word2=""
>> teller=0
>> if type(seq) == type([]):
>> teller=0
>> while teller < len(seq):
>> seq[teller]=""
>> teller = teller + 1
>> elif type(seq) == type(()):
>> tup2 = list (seq)
>> while teller > tup2.len():
>> tup2[teller]=""
>> teller = teller + 1
>> seq = tuple(tup2)
>> else:
>> seq = ""
>>
>> test = make_empty([1, 2, 3, 4])
>>
>> But now I get None as output instead of []
>>
>>
>> Because None is the default return value from a function.
>> If you do not return a value (which you don;t in this case) then
>> Python automatically returns None.
>>
>> You need to return something from your make_empty function.
>>
>> Also, if all you want to do is return an empty version of
>> whatever has been passed in there are much easier
>> ways of doing it! And in fact, a list of empty strings is
>> not the same as an empty list...
>>
>>
>> HTH
>>
>> --
>> Alan Gauld
>> Author of the Learn to Program web site
>> http://www.alan-g.me.uk/
>>
>>
>> ___
>> Tutor maillist - Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
> Oke,
>
> I put a return seq in the programm and it looks now like this :
>
> def encapsulate(val, seq):
>     if type(seq) == type(""):
>     return str(val)
>     if type(seq) == type([]):
>     return [val]
>     return (val,)
>
> def insert_in_middle(val, seq):
>     middle = len(seq)/2
>     return seq[:middle] + encapsulate(val, seq) + seq[middle:]
>
> def make_empty(seq):
>     """
>   >>> make_empty([1, 2, 3, 4])
>   []
>   >>> make_empty(('a', 'b', 'c'))
>   ()
>   >>> make_empty("No, not me!")
>   ''
>     """
>     if type(seq) == type([]):
>     seq = []
>     elif type(seq) == type(()):
>     seq=()
>     else:
>     seq = ""
>     return seq
>
> if __name__ == "__main__":
>     import doctest
>     doctest.testmod()
>
> This works but I don't think its what the exercise means :
>
>
> Create a module named seqtools.py. Add the functions encapsulate and
> insert_in_middle from the chapter. Add doctests which test that these two
> functions work as intended with all three sequence types.
>
> Add each of the following functions to seqtools.py:
>
> def make_empty(seq):
> """
>   >>> make_empty([1, 2, 3, 4])
>   []
>   >>> make_empty(('a', 'b', 'c'))
>   ()
>   >>> make_empty("No, not me!")
>   ''
> """
>
> So i think I have to use encapsulate and insert_in_middle. And I don't use
> it.

I don't think so. They don't look like the kind of thing that would be
useful for this function. In your example seqtools.py is supposed to
be a (toy example of a) library, a collection of functions to do
things with sequence-like objects to be used by other programs. These
functions in general need not have much to do with eachother, except
that they work on the same type of objects.


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] slicing a string

2010-09-06 Thread Andre Engels
On Tue, Sep 7, 2010 at 12:44 AM, lists  wrote:
>>> Assuming that mytext is "test", I've found that mytext[-1:-4:-1]
>>> doesn't work (as I expected it to) but that mytext[::-1] does.
>>>
>>> While that's fine, I just wondered why mytext[-1:-4:-1] doesn't work?
>>
>> How does it not "work"? What did you expect to happen? What did it do 
>> instead?
>>
>> Greets
>> Sander
>>
>
> Hi, assuming mytext is "test", word[-1:-4:-1] returns tse
>
> My understanding of how the index works on test would be:
>
> 0  1  2  3
> t   e  s   t
> -4 -3 -2 -1
>
> So I just wasn't clear on what happened to the last 't' I expected to see.


>>> "test"[0:3]
'tes'

[m:n] shows the elements from m upto but excluding n.


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] FW: Can this be done easly

2010-09-19 Thread Andre Engels
On Sun, Sep 19, 2010 at 7:02 PM, Roelof Wobben  wrote:
>
>
>
> 
>> From: rwob...@hotmail.com
>> To: __pete...@web.de
>> Subject: RE: [Tutor] Can this be done easly
>> Date: Sun, 19 Sep 2010 17:01:22 +
>>
>>
>>
>>
>> 
>>> To: tutor@python.org
>>> From: __pete...@web.de
>>> Date: Sun, 19 Sep 2010 18:27:54 +0200
>>> Subject: Re: [Tutor] Can this be done easly
>>>
>>> Roelof Wobben wrote:
>>>
> Hint: why does this work:
>
>> def __init__(self, x=0, y=0):
>
> ...while this doesnt:
>
>> def _init_(self, base_point, width=0, length=0):
>
> Peter
>>>
 Maybe because base_point has no value ?
>>>
>>> No. One __init__ has two underscores (correct) on each side, the other
>>> _init_ only one (wrong).
>>>
>>> ___
>>> Tutor maillist - Tutor@python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
> Hello,
>
> Everybody thanks.
>
> For this exercise :
>
> 3.Write a function named move_rect that takes a Rectangle and two parameters 
> named dx and dy. It should change the location of the rectangle by adding dx 
> to the x coordinate of corner and adding dy to the y coordinate of corner.
>
> Is this one of the possible solutions :
>
>
> class Point:
>    def __init__(self, x=0, y=0):
>        self.x = x
>        self.y = y
>
> class Rectangle(object):
>    def __init__(self, base_point, width=0, length=0):
>        self.base_point = base_point
>        self.width = width
>        self.length = length
>
> def moverect(rectangle, dx, dy):
>    rechthoek.base_point.y += dy
>    rechthoek.base_point.x +=dx
>    return rechthoek
>
> punt = Point(3,4)
> rechthoek = Rectangle (punt,20,30)
> test = moverect (Rectangle, 4,3)
> print rechthoek.base_point.x


This test happens to work, but your program is incorrect.

In moverect, you should work with the local variable (rectangle), not
with the global one (rechthoek), because it should be possible to call
it for any Rectangle, not just with the Rectangle that happens to be
called rechthoek. Then, when you call it, you should specify the
Rectangle that you call it for, so

test = moverect (Rectangle, 4, 3)

should be

test = moverect(rechthoek, 4, 3)

Furthermore, you do not use test (which will be null anyway), so you
can shorten this to

moverect(rechthoek, 4, 3)

-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] FW: Can this be done easly

2010-09-19 Thread Andre Engels
On Sun, Sep 19, 2010 at 8:33 PM, Roelof Wobben  wrote:

> Hello,
>
> I changed the programm to this :
>
> import unittest
> class Point:
>    def __init__(self, x=0, y=0):
>        self.x = x
>        self.y = y
>
> class Rectangle(object):
>    def __init__(self, base_point, width=0, length=0):
>        self.base_point = base_point
>        self.width = width
>        self.length = length
>
> def moverect(roelof, dx, dy):
>    roelof.base_point.y += dy
>    roelof.base_point.x +=dx
>    return roelof
>
> r = Rectangle(Point(3, 4), 20, 30)
> moverect(r, 10, 11)
> assert r.base_point.x == 13, "wrong x position %d" % r.base_point.x
> assert r.base_point.y == 15, "wrong y position %d" % r.base_point.y
>
> But no output at all

Which output had you expected, and why?


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] variable numbers of for loops

2010-11-23 Thread Andre Engels
On Tue, Nov 23, 2010 at 2:16 PM, Jose Amoreira  wrote:

> Is there a more straightforward way of solving my specific problem or, better
> yet, a general solution to the need of a variable number of for loops?

If you need a variable number of loops, put the loops themselves in a
loop, which you go through the required number of times. In your case
I would do:

def allwrds(alphabet,n):
result = [""] # for n=0, we have a single empty string
for _ in range(n):
 result = [w+letter for letter in alphabet for w in result]
return result

Or, in case you are not comfortable with list comprehension (or want
easy translation to a language without such a powerful tool):

def allwrds(alphabet,n):
result = [""] # for n=0, we have a single empty string
for _ in range(n):
tempwrds = []
for w in result:
for letter in alphabet:
tempwrds.append(w+letter)
result = tempwrds
return result

-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] url parsing

2009-02-15 Thread Andre Engels
On Sun, Feb 15, 2009 at 1:37 PM, Emad Nawfal (عماد نوفل)
 wrote:

> I'm not sure this is the best strategy, but it seems to work:
>
 url ="http://this/is/my/url/to/parse";
 m = url.replace("//", '/').split("/")
 n = m[0]+"//"+"/".join(new[1:])
 n
> 'http://this/is/my/url/to'

What is 'new' in your solution? Apart from that, the following looks simpler:

>>> url = "http://this/is/my/url/to/parse";
>>> parts = url.split('/')
>>> sol = '/'.join(parts[:-1])
>>> sol
'http://this/is/my/url/to'




-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] exec "self.abc=22" ?

2009-02-17 Thread Andre Engels
On Mon, Feb 16, 2009 at 10:01 PM, Wayne Watson
 wrote:
> My limited repertoire. Actually, there wasn't much of a traceback. It came
> up in a small OK dialog. I copied what I could.  I see my image I used above
> did make it to the list, so here's the skinny.
>
>
> I see Marc covered it with setattr. How does one do it with a dictionary?
> What else lurks out there that might be useful along these lines?

It all depends on what you will use it for. As said, exec should work,
but it usually is not the way to go - if there's outside input
involved, it's _extremely_ unsafe, if everything comes from inside
your program it's an ugly sledgehammer to crack a nut. So please take
one step back - WHY do you want to do this? Where does this string
"self.abc = 22" come from? What are the values it can have? Can you
create a toy example that shows the problem you want to solve?

--
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Passing perimeters in dictionary values?

2009-02-24 Thread Andre Engels
On Tue, Feb 24, 2009 at 8:03 PM, nathan virgil  wrote:
> I'm experimenting with OOP using the Critter Caretaker script from Python
> Programming for the Absolute Beginner as my basis. I've noticed that a
> dictionary/function combo is a great way to handle menus, and so I've
> adapted the menu to read as:
>
>
> selection = raw_input("Choice: ")
> choices = {"0":quit, "1":crit.talk, "2":crit.eat, "3":crit.play}
> choice = choices[selection]
> choice()
>
> so that I can call methods from a dictionary, instead of having an
> excruciatingly long if structure. Unfortunately, the problem I'm running
> into with this is that I can't pass any perimeters through the dictionary. I
> can't figure out how, for example, I could have an option that calls
> crit.eat(2) and another that calls crit.eat(4). The only thing I can think
> of is going back to the if structure, but my instinct tells me that this is
> a Bad Idea. What can I do?

You could use a tuple, consisting of the function and its parameter:

choices = {"0": (quit,), "1": (eat,2), "2": (eat,4)}
choice = choices[selection]
choice[0](*choice[1:])

But as said by someone else, if the choices are the lowest n natural
numbers, a list feels more natural:

choices = [(quit,), (eat,2), (eat,4)]
choices = choice[int(selection)]
choice[0](*choice[1:])



-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Passing perimeters in dictionary values?

2009-02-24 Thread Andre Engels
On Wed, Feb 25, 2009 at 12:47 AM, Andre Engels  wrote:
> - Show quoted text -
> On Tue, Feb 24, 2009 at 8:03 PM, nathan virgil  wrote:
>> I'm experimenting with OOP using the Critter Caretaker script from Python
>> Programming for the Absolute Beginner as my basis. I've noticed that a
>> dictionary/function combo is a great way to handle menus, and so I've
>> adapted the menu to read as:
>>
>>
>> selection = raw_input("Choice: ")
>> choices = {"0":quit, "1":crit.talk, "2":crit.eat, "3":crit.play}
>> choice = choices[selection]
>> choice()
>>
>> so that I can call methods from a dictionary, instead of having an
>> excruciatingly long if structure. Unfortunately, the problem I'm running
>> into with this is that I can't pass any perimeters through the dictionary. I
>> can't figure out how, for example, I could have an option that calls
>> crit.eat(2) and another that calls crit.eat(4). The only thing I can think
>> of is going back to the if structure, but my instinct tells me that this is
>> a Bad Idea. What can I do?
>
> You could use a tuple, consisting of the function and its parameter:
>
> choices = {"0": (quit,), "1": (eat,2), "2": (eat,4)}
> choice = choices[selection]
> choice[0](*choice[1:])
>
> But as said by someone else, if the choices are the lowest n natural
> numbers, a list feels more natural:
>
> choices = [(quit,), (eat,2), (eat,4)]
> choices = choice[int(selection)]
> choice[0](*choice[1:])

That last one should of course be:

choices = [(quit,), (eat,2), (eat,4)]
choice = choices[int(selection)]
choice[0](*choice[1:])






-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Passing perimeters in dictionary values?

2009-02-25 Thread Andre Engels
On Wed, Feb 25, 2009 at 2:32 AM, nathan virgil  wrote:
> Erm, it's still not working...
>
> Whenever I try to use the talk method (which reports the mood, and doesn't
> take parameters), it says I gave it too many parameters. Maybe it might help
> if I posted the code in it's entirety
>
>
> # Critter Caretaker
> # A virtual pet to care for
>
> class Critter(object):
>     """A virtual pet"""
>     def __init__(self, name, hunger = 0, boredom = 0):
>     self.name = name
>     self.hunger = hunger
>     self.boredom = boredom
>
>     def __pass_time(self):
>     self.hunger += 1
>     self.boredom += 1
>
>     def __get_mood(self):
>     unhappiness = self.hunger + self.boredom
>     if unhappiness < 5:
>     mood = "happy"
>     elif 5 <= unhappiness <= 10:
>     mood = "okay"
>     elif 11 <= unhappiness <= 15:
>     mood = "frustrated"
>     else:
>     mood = "mad"
>     return mood
>
>     mood = property(__get_mood)
>
>     def talk(self):
>     print "I'm", self.name, "and I feel", self.mood, "now.\n"
>     self.__pass_time()
>
>     def eat(self, food = 4):
>     print "Brruppp.  Thank you."
>     self.hunger -= food
>     if self.hunger < 0:
>     self.hunger = 0
>     self.__pass_time()
>
>     def play(self, fun = 4):
>     print "Wheee!"
>     self.boredom -= fun
>     if self.boredom < 0:
>     self.boredom = 0
>     self.__pass_time()
>
>     def backdoor(self):
>     print "hunger:", self.hunger, "boredom:", self.boredom
>
> def quit():
>     print "God-bye!"
>
>
> def main():
>     crit_name = raw_input("What do you want to name your critter?: ")
>     crit = Critter(crit_name)
>
>     selection = None
>     while selection != "0":
>     print \
>     """
>     Critter Caretaker
>
>     0 - Quit
>     1 - Listen to your critter
>     2 - Feed your critter
>     3 - Play with your critter
>     """
>
>     selection = raw_input("Choice: ")
>     choices = {"0":(quit, None), "1":(crit.talk, None), "2":(crit.eat,
> 3), "3":(crit.play, 3), "Xyzzy":(crit.backdoor, None)}
>     if selection in choices:
>    choice = choices[selection]
>    choice[0](choice[1])

Yes, that won't work - you are now calling 'quit' and 'talk' with the
argument 'None' rather than without an argument. One way to resolve
this would be to use my proposal: take out the "None"s (but keep the
comma before it) and chance this line to
  choice[0](*choice[1:])
which also has the advantage of still working with more than one argument

Another would be to not change the definition of choices, but replace
choice[0](choice[1])

by:
if not choice[1] is None:
 choice[0](choice[1])



-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Class instance understanding = None

2009-02-27 Thread Andre Engels
On Fri, Feb 27, 2009 at 6:06 AM, David  wrote:
> Hi Everyone,
> I go through the archived [Tutor] mail list to find programs others have
> tried to do. I found one that would keep track of a petty cash fund. please
> point out my misunderstanding.
> Here is what I started with;
> 
> #!/usr/bin/python
>
> from reportlab.lib.normalDate import ND
> #import cPickle as p
> #import pprint
>
> today = ND()
>
> class Account:
>    def __init__(self, initial):
>        self.balance = initial
>    def deposit(self, amt):
>        self.balance = self.balance + amt
>    def withdraw(self, amt):
>        self.balance = self.balance - amt
>    def getbalance(self):
>        return self.balance
> print 'The current date is: ', today.formatUS()
>
>
> data = float('100.00')
> a = Account(data)
> p = a.getbalance()
> print 'balance = ', p
> remove_data = float('50.00')
> w = a.withdraw(remove_data)
> print "withdraw = ", w
> add_data = float('50.00')
> add = a.deposit(add_data)
> print "deposit = ", add
> 
>
> results;
> The current date is:  02/27/09
> balance =  100.0
> withdraw =  None
> deposit =  None
>
> expected results;
> The current date is:  02/27/09
> balance =  100.0
> withdraw =  50.0
> deposit =  100.0

A method only returns a value if you do so explicitly, that is, end it with

return value

That's what happens in getbalance:

return self.balance

deposit and withdraw however do not return a value. If, like you do,
you still try to extract their return value, it gives None.

There are two ways to resolve this. The first gets closer to what you
are trying to do, but is considered less proper programming, because
it mixes functions of methods. In it, you add the returns to the
methods:

class Account:
  def __init__(self, initial):
      self.balance = initial
  def deposit(self, amt):
      self.balance = self.balance + amt
      return self.balance
  def withdraw(self, amt):
      self.balance = self.balance - amt
      return self.balance
  def getbalance(self):
      return self.balance

The more preferable method is to leave the class alone, and call
getbalance by hand:

data = float('100.00')
a = Account(data)
p = a.getbalance()
print 'balance = ', p
remove_data = float('50.00')
a.withdraw(remove_data)
w = a.getbalance()
print "withdraw = ", w
add_data = float('50.00')
a.deposit(add_data)
add = a.getbalance()
print "deposit = ", add

Some other things:
1. data = float('100.00') is unnecessarily clumsy - you can specify
floats directly without creating a string first by doing data = 100.0
2. You are creating a lot of variables only to use them for the one
and only time on the next line. That's not necessarily bad, it
sometimes improves readability especially if a lot is being done
(which can then be split up in more readable parts), but doing it this
much mostly causes your coding to look more complicated than it
actually is. I would either prefer something like this:

data = 100.0
remove_data = 50.0
add_data = 50.0        # first all input-like elements, so I know
where to go when I want to change something trivial
a = Account(data)
print 'balance = ',a.getbalance()
a.withdraw(remove_data)
print 'balance after withdraw = ',a.getbalance()
a.deposit(add_data)
print 'balance after deposit = ',a.getbalance()

doing away with p, w and add, or the even shorter variant where data,
remove_data and add_data are also removed:

a = Account(100.0)
print 'balance = ',a.getbalance()
a.withdraw(50.0)
print 'balance after withdraw = ',a.getbalance()
a.deposit(50.0)
print 'balance after deposit = ',a.getbalance()

--
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What is this [] construction?

2009-03-02 Thread Andre Engels
On Tue, Mar 3, 2009 at 4:54 AM, Wayne Watson
 wrote:
> What is this: d = [ int(x) for x in s.split(":") ]
> I see in the program I'm looking at, the [] construction can be much more
> complicated, as in:
>    self.recent_events = [ event for event in self.recent_events
>    if os.path.exists(event) and
>    (time.time() - os.path.getmtime(event)) <
> 3600.0 ]

That's called list comprehension. The notation
[f(x) for x in A if p(x)]
means:
Form a list in the following way:
Start with an empty list. Then go through A, and for each x in A, if
p(x) is true, add f(x) to the list.

d = [f(x) for x in A if p(x)]

is equivalent to:

d = []
for x in A:
if p(x):
d.append(f(x))

Your first example had no p(x) defined, which means that it's done for
all x, that is:

[ int(x) for x in s.split(":") ]

means:

The list, formed by taking int(x) for all x in the result of s.split(":").

It is almost English, really...

[f(x) for x in A if p(x)]

means:

f(x) for all x in A for which p(x) holds.

-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] problem with an anagram program

2009-03-09 Thread Andre Engels
Please next time, if possible, add the complete error message you get.
In this case, it tells us that the error is in this line:

 if sig == wordList[i]

You forgot the : at the end of this line (also, the next lines are not
indented extra, as they should).

On Mon, Mar 9, 2009 at 9:28 AM, jessica cruz  wrote:
> I just started learning python an I'm currently working on this program. The
> purpose of this program is to read a string of letters from user input and
> print out all the words which are anagrams of the input string. This is what
> I have and when I try to run the program it says that there is an error
> "invalid syntax" but I can't figure out where.
>
>
>
>
> #this reads all of the words in the file into a list
> infile = open('/afs/cats/courses/cmps012a-cm/pa1/wordList.txt')
> wdcount = int(infile.readline()) #first item is count of all the words
> word_list = infile.readlines()
> wordList = []
>
> # code that will be compared will be a histogram type code with frequency
> # characters
> def code(w):
>     hist = []
>     chars = list(w)
>     chars.sort()
>     for letter in chars:
>     if not letter in hist:  # when the letter is not already in hist,
>     hist.extend([letter, str(w.count(letter))])  # its added to hist
> along with its freq.
>     else:
>     continue
>     coding = "".join(hist) # then they are joined as one string
>     return coding
>
>
>
>
> # new list is made with words in word_list followed by its code
> for word in  word_list:
>     wordList.append(word)
>     wordList.append(code(word[:(len(word)-2)]))
>
>
> while True:
>     word1 = raw_input('Enter word:')
>     word = word1.lower()
>     sig = code(word)
>     i = 1
>     if sig in wordList:
>     print "Anagrams:"
>     while i <= len(wordList):  # when the sig of the inputed word is in
> the word list,
>     if sig == wordList[i]
>     print wordList[i-1]  # the corresponding words are printed
>     i += 2 # then adds two because codes are every other entry
>     else:
>     print "No anagrams"
>     choice = raw_input("Continue? (yes/no)")
>     if choice == 'y' or choice == 'yes':
>     continue
>     else:
>     break




-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How can I extract a specific sublist from a nested list?

2009-03-11 Thread Andre Engels
2009/3/11 Emad Nawfal (عماد نوفل) :

> Now I know that I did not ask the right question. What I meant was: how to
> extract a sublist from a list whose length is unknown. Let's say I have a
> hundred of these lists and each of these has an NP somewhere, it could be
> nested in nested list, which is turn nested in another one and so on. The
> bottom line is that I do not know the index.  To make things more concrete,
> this is a representative list. How can I extract all the sublists beginning
> with "NP" from it?

You'll have to do recursion - that is:
NPstart(alist) =
   if alist starts with "NP":
   alist + NPstart for all sublists of alist
   else:
   NPstart for all sublists of alist


Turning that into Python we get:

def NPstart(alist):
   if isinstance(alist, basestring): # It's ugly to do an isinstance
in Python, but any better method would be fully changing your data
structure, so I use it for now
   return []
   else:
   if alist[0] == 'NP':
   return [alist] + [NPstart(sublist) for sublist in alist]
   else:
   return [NPstart(sublist) for sublist in alist]

-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] way of dictating leading zeros

2009-03-15 Thread Andre Engels
On Mon, Mar 16, 2009 at 3:47 AM, Patrick  wrote:
> Hi Everyone
>
> I am trying to write a program that creates a bunch of svg files and
> then edits their values. I am then encoding them into a video. It's not
> encoding right because my filenames are wrong. They have to have a
> sequence. Right now they are 1.svg, 2.svg, 3.svg etc but they should be
> 001.svg, 002.svg, 003.svg. At the moment I think 12.svg is ending up
> before 2.svg because it starts with 1.
>
> Is there an easy way to dictate how many digits a number will occupy
> that also allows for leading zeros?

"%03i"%i

for example:

"%03i"%2 equals "002" and "%03i"%12 equals "012". Of course in your
case you can combine the adding of .svg at once:

"%03i.svg"%2 equals "002.svg".

Explanation of what this means:

"blabla %s bla"%something

means that the '%s' is to replaced by the string representation of
something. Changing %s to %i means that the something is read as an
integer for that, and %03i means that the integer has to be shown
padded with zeroes with a length of (minimal) 3.


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] combining Python 2.x and Python 3

2009-03-17 Thread Andre Engels
I have an open source project I have done some work on, which is
programmed in Python 2.3-2.6. I would like to change it so that it can
be run under both Python 3 and Python 2.x. Two questions for that:
* is there a place where I can find an overview of what to do to make
such a change?
* is there a way to check, on one computer, the code under both
versions (I am using Windows Vista, in case it matters)?

-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] regular expression question

2009-04-28 Thread Andre Engels
2009/4/28 Marek spociń...@go2.pl,Poland :
>> Hello,
>>
>> The following code returns 'abc123abc45abc789jk'. How do I revise the 
>> pattern so
>> that the return value will be 'abc789jk'? In other words, I want to find the
>> pattern 'abc' that is closest to 'jk'. Here the string '123', '45' and '789' 
>> are
>> just examples. They are actually quite different in the string that I'm 
>> working
>> with.
>>
>> import re
>> s = 'abc123abc45abc789jk'
>> p = r'abc.+jk'
>> lst = re.findall(p, s)
>> print lst[0]
>
> I suggest using r'abc.+?jk' instead.
>
> the additional ? makes the preceeding '.+' non-greedy so instead of matching 
> as long string as it can it matches as short string as possible.

That was my first idea too, but it does not work for this case,
because Python will still try to _start_ the match as soon as
possible. To use .+? one would have to revert the string, then use the
reverse regular expression on the result, which looks like a rather
roundabout way of doing things.



-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] finding difference in time

2009-05-15 Thread Andre Engels
On Fri, May 15, 2009 at 6:46 AM, R K  wrote:
> Gurus,
>
> I'm trying to write a fairly simple script that finds the number of hours /
> minutes / seconds between now and the next Friday at 1:30AM.
>
> I have a few little chunks of code but I can't seem to get everything to
> piece together nicely.
>
> import datetime,time
> now = datetime.datetime.now()
>
> i = 0
> dayOfWeek = datetime.datetime.now().strftime( '%a' )
> while dayOfWeek != 'Fri':
>     delta = datetime.timedelta( days = i )
>     tom = ( now + delta ).strftime( '%a' )
>     if tom != 'Fri':
>     i = i + 1
>     else:
>     print i
>     print tom
>     break
>
> So with this code I can determine the number of days until the next Friday
> (if it's not Friday already).
>
> The problem I'm having, however, is with finding the number of minutes until
> 1:30AM on Friday.
>
> nextFridayDay = int( now.strftime( '%d' ) ) + 1
> nextFridayMonth = int( now.strftime( '%m' ) )
> nextFridayYear = int( now.strftime( '%Y' ) )
>
> nextRun = datetime.datetime( nextFridayYear , nextFridayMonth ,
> nextFridayDay , 1 , 30 , 0 )
>
> What I gather is that I should be able to numerically manipulate two
> datetime objects, as seen below:
>
> In [227]: nextRun - now
> Out[227]: datetime.timedelta(0, 46155, 51589)
>
> The result, however, doesn't make sense. Take a look...
>
> In [231]: d = nextRun - now
>
> In [232]: d.seconds
> Out[232]: 46155
>
> In [233]: d.days
> Out[233]: 0
>
> Thoughts on what I may be doing wrong? Am I going about this the whole wrong
> way? Should I be using something different to calculate the number of
> minutes between now and the next Friday at 1:30AM?

Why do you think the result doesn't make sense? You basically defined
"next Friday" as tomorrow (the day in the same year on the same day
one number more), and then looked at the time until next Friday at
1:30AM. It appears that that time was 0 days and 46155 seconds (plus
some fraction of a second, which is about 12 hours and 50 minutes.


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Can't figure out why this is printing twice

2009-06-08 Thread Andre Engels
On Mon, Jun 8, 2009 at 11:57 AM, Mike Hoy wrote:
> I have the following code:
>
> import gzip
> import datetime
> date = datetime.date.today()
> name = date.strftime('%m-%d-%Y')+'.gz'
> date.strftime('%m-%d-%Y')+'.gz'
> print "The name of the file will be", name
>
> the output is:
> The name of the file will be
> The name of the file will be 06-08-2009.gz
>
>
> I can't figure out why 'The name of the file will be' is printing twice. Any
> help appreciated.

How exactly are you running this? It seems to work correctly for me.

Looking at your code, the following couple of lines look strange:

> name = date.strftime('%m-%d-%Y')+'.gz'
> date.strftime('%m-%d-%Y')+'.gz'

The first calculates a name based on the current date, and puts the
result in the variable 'name'. The second calculates the name again,
then throws the result away. Why not remove the second line?




-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help..Concatenaton Error

2009-06-11 Thread Andre Engels
On Fri, Jun 12, 2009 at 3:00 AM, Randy Trahan wrote:
> Attached is an error I cannot get to work, I was doing a print concatenation
> but it won't let me get past "+ "ibly impressive. " \
> (then to next line)

It's wrong at a few places, but the first is at the very beginning.
You need a quote mark before the first \n. The colour coding in your
interface will help you here: All the literal text that you want to
print, should be in green. The first place where it is black or
another colour denotes a place where things have gone wrong.

> Also Programming Lanquage Question:
> I have studied and an fairly proficient at XHTML and CSS, I tried Javascript
> but just didn't like it for some reason..so I am trying Python which so far
> fits my personality, needs, whatever that part is that makes you choose a
> lanquage. Will I be able to use Python in web pages as I would of used
> Javascript?  From what I have read there are Python to Javascript
> converters?...

No, Javascript is (as far as I know) the only language that can be
used _inside_ web pages. When you use Python (or some other language)
in web design, what you do is create code that _generates_ web pages.
The big difference is that the Python will be executed on the server's
machine, the Javascript on the client's machine.


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Generating Deck Combinations

2009-06-20 Thread Andre Engels
On Sat, Jun 20, 2009 at 9:49 AM, Michael Morrissey wrote:
> I need to generate all possible deck combinations given two different lists
> as input.
> The Input:
> List 1 has Card names listed inside it.
> List 2 has Maximum Quantities for each Card name.
>
> For example:
>
> List1[0] would be: "Aether Vial"
> List2[0] would be: "4"
>
> List1[1] would be: "Mountain"
> List2[1] would be: "10"
>
> List1[2] would be: "Gempalm Incinerator"
> List2[2] would be: "3"
>
> etc.

In my opinion, that's a very unpythonic way of specifying data - I
would use a dictionary for this kind of information:

maximalQuantity = {"Aether Vial": 4, "Mountain": 10, "Gempalm
Incinerator": 3 ...}

> A deck is 60 cards total (no more, no less). I need to loop over these lists
> to generate all possible combinations of 60 card decks which use up to the
> maximum quantity for each card.
> So, from the example, I need to generate decks with '1' Aether Vial' and 59
> other cards in all possible combinations (still within the maximum cap for
> each card), and then I'd need to generate decks with '2' Aether Vial' and 58
> other cards in all possible combinations
> It is vital that I create all combinations and that the maximum quantities
> are never breached.
> I am hoping that the each deck could be output as two lists:
> ListA = ['Cardname1', 'Cardname2', ...]
> ListB = ['1', '2', ...]
> These lists will have exactly 60 members.
> If you have an idea of how to do this, please share it! =) I would be most
> appreciative. I'll be testing all methods for speed because I have very
> large amount of computing to do.

Given that ListB will _always_ be ['1', '2', '3', ..., '60'], I do not
see what its use is...

For this problem I would use recursion. I define a function

possible_decks(listA, listB, number)

its input are the lists listA and listB and the number of cards in the
deck, its output is a list of lists, each of which is ListA (it is
confusing to have the same name for two different objects in your
description...) for some legal deck.

The code would be (untested):

def possible_decks(listA, listB, number):
if number < 0:
return [] # trying to put more than 60 cards in the deck
if number == 0:
return [[]] # there's exactly one deck of size 0 - the empty deck
if not listA:
return [] # out of cards, but the deck is not yet full
thiselement = listA[0]
thismaximum = int(listB[0])
returnvalue = []
for i in xrange(thismaximum):
 possible_rests_of_deck = possible_decks(listA[1:], listB[1:],
number - i)
 returnvalue += [i*[thiselement] + deck for deck in
possible_rests_of_deck]
return returnvalue

-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] intefaces in python

2009-06-29 Thread Andre Engels
On Sun, Jun 28, 2009 at 5:00 PM, Amit Sethi wrote:
> Hi , I don't suppose python has a concept of interfaces. But can somebody
> tell me if their is a way i can  implement something like a java interface
> in python.

Sure. Interfaces are just Java's compensation for not having multiple
inheritance. Python does have multiple inheritance, so that's what one
would use. Although one could also use duck typing, and then use
'nothing' as an implementation...

More specific:


Java Interface:
public interface MyInterface {
string doSomething(string line);
string doSomethingElse(string line);
}

Java Implementation:
public class MyImplementation {
   string doSomething(string line) {
   return "I did something with" + line;
   }
   string doSomethingElse(string line) {
  return "I did something else."
   }
}

==
Python Interface:

class MyInterface(object):
doSomething(line):
raise NotImplementedError
doSomethingElse(line):
raise NotImplementedError

Python Implementation:
class MyImplementation(MyInterface):
doSomething(line):
return "I did something with "+line
doSomethingElse(line):
return "I did something else."

==
Python interface using duck typing:

# Hey guys, when you call something a 'MyInterface', it needs methods
doSomething and doSomethingElse

Python Implementation using duck typing:

class MyImplementation(object):
# These things implement MyInterface
doSomething(line):
return "I did something with "+line
doSomethingElse(line):
return "I did something else."


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Replace a character by index

2009-07-16 Thread Andre Engels
On Thu, Jul 16, 2009 at 11:22 AM, Gregor Lingl wrote:

> That's simply not true in Python. Try it out!
>
 word = "cat"
 word[1] = "_"
> Traceback (most recent call last):
>  File "", line 1, in 
>   word[1] = "_"
> TypeError: 'str' object does not support item assignment

And the reason for that, undoubtedly, is that strings are immutable.


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to iterate through unicode string.

2009-09-04 Thread Andre Engels
On Fri, Sep 4, 2009 at 2:20 PM, zhang allen wrote:
> Hi All,
>
> Say i have unicode string  Büro.
> i want to iterate this string .
>
> i write this python code which doesn't work.
>
> s ='Büro'
> for ch in s:
>     print ch
>
> it seems Büro has 5 chars. ü consists of 2 bytes.
>
> so does someone has any ideas?
>
> how to iterate this string, so i can hava 4 chars, like "B, ü, r, o ".?
>
> Thanks in advance.

Try replacing
s ='Büro'
by
s = u'Büro'

The 'u' denotes that the string is to be interpretred as unicode.



-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to print the next line in python

2009-09-12 Thread Andre Engels
On Sat, Sep 12, 2009 at 10:35 AM, ranjan das  wrote:
> Hi,
>
> I am new to python and i wrote this piece of code which is ofcourse not
> serving my purpose:
>
> Aim of the code:
>
> To read a file and look for lines which contain the string 'CL'. When found,
> print the entry of the next line (positioned directly below the string 'CL')
> continue to do this till the end of the file (since there are more than
> one occurrences of 'CL' in the file)
>
> My piece of code (which just prints lines which contain the string 'CL')
>
> f=open('somefile.txt','r')
>
> for line in f.readlines():
>
>  if 'CL' in line:
>   print line
>
>
> please suggest how do i print the entry right below the string 'CL'

I would this using a boolean variable to denote whether the line
should be printed:

printline = false
for line in f.readlines():
if printline:
print line
printline = 'CL' in line

(I assume the last line does not contain 'CL', because otherwise we
have a problem with the problem definition)

-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] if n == 0 vs if not n

2009-10-06 Thread Andre Engels
On Tue, Oct 6, 2009 at 5:08 PM, Wayne  wrote:
> On Tue, Oct 6, 2009 at 9:58 AM, Dave Angel  wrote:
>>
>> 
>>
>> No, because you're not assured that all integers that are equal are the
>> same object.  Python optimizes that for small integers, but there's no
>> documented range that you can count on it.
>>
>
> But for this specific case - checking a return code against zero, should it
> still be considered unreliable? The only case that you are looking for
> correctness is 0 == 0, any other case should evaluate as false, so I guess
> the question is does python always optimize for zero? Any other optimization
> is irrelevant, AFAIK.

Never rely on optimizations like this being done, or on them not being
done. The only save way to code is having your code work in both
cases.


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] numerical problem

2009-10-15 Thread Andre Engels
On Thu, Oct 15, 2009 at 11:28 AM, Mr Timothy Hall
 wrote:
>  hi,
> i am writing a program for a runge-cutter method of solving ODE's and im
> having a problem with one part.
>
> whenever i run this part of the program, no matter what values i put in for
> vto, k1t etc... it always equals zero.
> im slightly aware of floating point numbers but im not sure why this will
> not give me a real answer.
> when i do it on my calculator the answer is 0.897 for the correct values of
> k3t etc. so its not like the result
> is extremely small.
> any help would be great.
>
> def runge_tang(vto,k1t,k3t,k4t,k5t,k6t):
>     vn = 
> vto+(16/135)*k1t+(6656/12825)*k3t+(28561/56430)*k4t-(9/50)*k5t+(2/55)*k6t
>     return vn

The problem is that Python 2 (it has changed in Python 3) uses integer
division when making the quotient of integers. 16/135 is thus
evaluated to zero, 6656/12825 as well, etcetera.

There are 2 ways to solve this:
1. At the top of your file, add the line "from __future__ import
division" - this makes the division behave as in Python 3, which uses
floating point division when dividing integers as well.
2. Change something to float before doing the division, for example through:

vn = 
vto+(float(16)/135)*k1t+(float(6656)/12825)*k3t+(float(28561)/56430)*k4t-(float(9)/50)*k5t+(float(2)/55)*k6t

or

vn = 
vto+(16.0/135)*k1t+(6656.0/12825)*k3t+(28561.0/56430)*k4t-(9.0/50)*k5t+(2.0/55)*k6t



-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Methods that return instances of their own class?

2009-10-15 Thread Andre Engels
On Thu, Oct 15, 2009 at 5:14 PM, David Perlman  wrote:
> I'm trying to figure out how to define a class so that its instances have a
> method that return a different object of the same class.
>
> In particular, I'm trying to run a simple prisoner's dilemma game, and I
> want to make a "game" object that has a method which returns the "game"
> object with the payoffs reversed; that is, the payoff matrix from the other
> player's point of view.  Basically a kind of transpose which is specific to
> this application.
>
> class Payoffs(list):
>    def __init__(self, value=None):
>        list.__init__(self)
>        if value==None: # use a default prisoner's dilemma
>            value=[[(3,3),(0,5)],
>                   [(5,0),(1,1)]]
>        self.extend(value)
>
>    def __repr__(self):
>        l1="Your Choice:   Cooperate    Defect\n"
>        l2="My choice:   -\n"
>        l3="Cooperate    | (% 3d,% 3d) | (% 3d,% 3d) |\n" % (self[0][0][0],
> self[0][0][1], self[0][1][0], self[0][1][1])
>        l4="              --- \n"
>        l5="Defect       | (% 3d,% 3d) | (% 3d,% 3d) |\n" % (self[1][0][0],
> self[1][0][1], self[1][1][0], self[1][1][1])
>        l6="             -\n"
>        return l1+l2+l3+l4+l5+l6
>
>    def transpose(self):
>
> And that's where I'm at.  How can I have the transpose method return another
> Payoffs object?  Here's the beginning of it:
>
>    def transpose(self):
>        trans=[[(self[0][0][1],self[0][0][0]),
> (self[1][0][1],self[1][0][0])],
>               [(self[0][1][1],self[0][1][0]),
> (self[1][1][1],self[1][1][0])]]
>
> But now "trans" is type list, not type Payoffs.  I don't know how to get it
> into a Payoffs object so that the transpose will have my other new methods.
>
>
> Thanks very much.  I searched for answers but I'm not sure what this would
> be called, which made it hard to find.

I may be thinking too simple, but isn't this just:

def transpose(self):
 trans=[[(self[0][0][1],self[0][0][0]), (self[1][0][1],self[1][0][0])],
   [(self[0][1][1],self[0][1][0]), (self[1][1][1],self[1][1][0])]]
 return Payoffs(trans)


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Testing for empty list

2009-10-19 Thread Andre Engels
On Mon, Oct 19, 2009 at 3:29 AM, Wayne  wrote:
> Hi, I think I recall seeing this here, but I wanted to make sure I'm
> correct.
> Is the best way to test for an empty list just test for the truth value?
> I.e.
> mylist = [1,2,3]
> while mylist:
>    print mylist.pop()

Whether it is the 'best' way depends on what you mean by 'best', but I
do think it's the most idiomatically pythonic one.

-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Being beaten up by a tuple that's an integer thats a tuple that may be an unknown 'thing'.

2009-11-03 Thread Andre Engels
On Tue, Nov 3, 2009 at 4:20 PM, Robert Berman  wrote:

>
>   In [69]: l1=[(0,0)] * 4
>
> In [70]: l1
> Out[70]: [(0, 0), (0, 0), (0, 0), (0, 0)]
>
> In [71]: l1[2][0]
> Out[71]: 0
>
> In [72]: l1[2][0] = 3
> ---
> TypeError Traceback (most recent call last)
>
> /home/bermanrl/ in ()
>
> TypeError: 'tuple' object does not support item assignment
>
> First question, is the error referring to the assignment (3) or the index
> [2][0]. I think it is the index but if that is the case why does l1[2][0]
> produce the value assigned to that location and not the same error message.
>
> Second question, I do know that l1[2] = 3,1 will work. Does this mean I
> must know the value of both items in l1[2] before I change either value. I
> guess the correct question is how do I change or set the value of l1[0][1]
> when I specifically mean the second item of an element of a 2D array?
>
> I have read numerous explanations of this problem thanks to Google; but no
> real explanation of setting of one element of the pair without setting the
> second element of the pair as well.
>
> For whatever glimmers of clarity anyone can offer. I thank you.
>

Tuples are immutable types. Thus it is not possible to change one of the
values of a tuple (or even of changing both of them). The only thing you can
do, is create a new tuple, and put that in the same place in the list. In
your example, when you do l1[2][0] = 3, you try to change the tuple l1[2],
which is impossible.

To do what you want to do, you have to create a new array with the same
second but different first value, and put that array in l1[2], that is:

l1[2] = (3, l1[2,1])




-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 'Hello world'

2010-01-01 Thread Andre Engels
On Fri, Jan 1, 2010 at 11:17 AM, Eldon L Mello Jr  wrote:
> Hi there,
>
> I must say I'm quite embarrassed about my issue. Ok, I'm a 101% newbie in
> programming and all but I honestly didn't expect I would have problems in my
> very first step which was just to print 'hello world'.
>
> Despite some idiot little thing I might be overlooking I wonder if Python
> 3.1.1 was properly installed in my machine. I got a AMD Turion X2 64
> processor and Win7 Pro-64 so I suppose the Python 3.1.1 AMD64 version I got
> was the best pick right?
>
> here it comes:
>
> Python 3.1.1 (r311:74483, Aug 17 2009, 16:45:59) [MSC v.1500 64 bit (AMD64)]
> on win32
> Type "copyright", "credits" or "license()" for more information.

 print 'hello world!'
>
> SyntaxError: invalid syntax (, line 1)

 print "hello world!"
>
> SyntaxError: invalid syntax (, line 1)

>
> Thanks a million,

This is something that has changed between Python 2 and Python 3. In
Python 2 what you tried is perfectly valid, but in Python 3 print has
become a function, so you have to write:

print("hello world!")

or

print('hello world!')

Happy New Year!



-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to open the closed file again?

2010-01-05 Thread Andre Engels
On Tue, Jan 5, 2010 at 1:46 PM, 朱淳  wrote:
> I've token a dictionary to save filenames, and write it into "constant.py".
> And I think it's a good method to create a class as Andre wrote.  Thank you
> all!
> By the way, if I close a open file object, will the closed file object still
> occupy the memory ? As I saw in a list, this kind of unusable file object
> wasn't cleaned by GC. What will happen if there's no list?

In general, when an object is not referred any more in Python code, it
will be garbage collected (and thus the memory it occupies will become
free); however, this is not robust nor fully consistent over
implementation, and it is therefore unadvisable to write code that
relies too heavily on this.


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Calling web browser from Python

2005-06-20 Thread Andre Engels
Is it possible to call a web browser from Python, opening a certain
page? Preferably the user's standard web browser.

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


Re: [Tutor] What's wrong with this code?

2005-07-04 Thread Andre Engels
>From the program::

answer = raw_input("What is the password? ")
while password != answer:
print "The password is incorrect."

If the user submits a wrong password, the while-loop will be entered.
The program prints "The password is incorrect." then tests whether the
password is still not equal to the answer, prints "The password is
incorrect." again, etcetera. I think you intended to make it so that
the program kept asking for passwords until the right one was given.
This is done with:
answer = raw_input("What is the password? ")
while password != answer:
print "The password is incorrect."
answer = raw_input("What is the password? ")

Apart from this, I would like to ask you and anyone else who submits a question:

Do NOT just say there's something wrong with your code, say WHAT is
going wrong. That is, say "if I run this program (with this-and-that
input if that's important), I would expect to get such-and-such, but I
get so-and-so instead."

Andre Engels

On 7/5/05, Nathan Pinno <[EMAIL PROTECTED]> wrote:
>
>
> What's wrong with this code? I'm using 2.2.3 if this helps.
>
> #This is for a password protected program to store passwords.
> password = "hello"
> print "The Password Program"
> print "Copywrite 2005. All Rights Reserved."
> print
> answer = raw_input("What is the password? ")
> while password != answer:
> print "The password is incorrect."
> 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 = 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
> 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."
> 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."
> elif menu_choice == 4:
> print "Login Info"
> for x in site.keys():
> print "Site: ",x," \tID: ",numbers[x]," \tPassword: ",numbers[x]
> print
> elif menu_choice == 5:
> filename = raw_input("Filename to save: ")
> save_login(list,filename)
> elif menu_choice == 6:
> filename == raw_input("Filename to load: ")
> load_login(list,filename)
> print "Have a nice day!"
>
> Thanks,
> Nathan Pinno
> Crew, McDonalds Restaurant, Camrose, AB Canada
> http://www.npinnowebsite.ca/
>
>
> ___
> 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] What's wrong with this code?

2005-07-07 Thread Andre Engels
On 7/7/05, Nathan Pinno <[EMAIL PROTECTED]> wrote:
>   Hi all,
> 
>   I meant to ask why the main part after the password is not working right.
> No one has answered that yet. When I run the code and try to load a file
> that has been saved, a TypeError appears. How do I fix the code so no more
> errors will show up. Here is the newest code so far:

I don't get a TypeError, but a NameError. Reason is the line:
filename == raw_input("Filename to load: ")
which should be:
filename = raw_input("Filename to load: ")

After correcting this, I get the TypeError. And the error clearly says
what is wrong: in_file is a file object, and those do not have the
value "len". I think what you mean is done by replacing:
if len(in_file) == 0:
by:
if len(in_line) == 0:

In general, in such cases, check the error message. In this case it
said "len() of an unsized object". There is only one len() in the line
given, so that must be it, and thus in_file must be that 'unsized
object'.

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


Re: [Tutor] Getting two files to print

2005-07-20 Thread Andre Engels
(answer at the bottom)

On 7/18/05, Philip Carl <[EMAIL PROTECTED]> wrote:
> I have no more hair to pull out, so I'm asking the group for help on a
> VERY simple question.  I have two very similar text files to read-one
> with the final letters in the name 10%.txt and the other 20%.txt.  I've
> written the following simple code to read these two files:
> 
> # Program to read and print two text fiiles
> fileNameA =
> 'c:/Python24/outputs_1ubq_alignments/output_1ubq_alignments_10%.txt'
> #text file one
> firstFile=open (fileNameA,'r')
> inFileLeftA = 1 #more file to read
> inLineA=[0]
> while inFileLeftA:
> inLineA = firstFile.readline()
> if (inLineA == ''):
> infileLeftA = 0 #if empty line end of first file
> 
> else:
> print inLineA
> firstFile.close()
> 
> fileNameB =
> 'c:/Python24/outputs_1ubq_alignments/output_1ubq_alignments_20%.txt'
> #text file two
> secondFile=open (fileNameB,'r')
> inFileLeftB = 1 #more file to read
> inLineB=[0]
> while inFileLeftB:
> inLineB = secondFile.readline()
> if (inLineB == ''):
> infileLeftB = 0 #if empty line end of second file
> 
> else:
>  print inLineB
> secondFile.close()
> 
> I realize that I probably ought to be able to code this more
> efficiently, but as a rank beginner I am less worried about efficiency
> than output.  I can't seem to get BOTH files to print  when run as
> presented, although when I split the program into two programs each file
> seems to print OK.  As written here however,  I can get the first but
> not the second textfile to print. What am I doing wrong?.

You call the variable inFileLeftA, but when you try to set it to 0,
you use the name infileLeftA instead. That's another variable, so
inFileLeftA always remains 1.


Regarding the "ought to be able to code this more efficiently": The
obvious thing to do seems to be to use a function, so you have to type
in everything once instead of twice, like this:

# start of code

def printTextFile(fn):
# Print the contents of textfile fn
file = open(fn,'r')
inFileLeft = 1
inLine=[0]
while inFileLeft:
inLine = file.readline()
if inLine == '':
inFileLeft = 0
else:
print inLine
file.close()

printTextFile('c:/Python24/outputs_1ubq_alignments/output_1ubq_alignments_10%.txt')
printTextFile('c:/Python24/outputs_1ubq_alignments/output_1ubq_alignments_20%.txt')

# end of code

There are other things that could be improved, but this is the main one by far.

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


Re: [Tutor] {Possible Spam?} How to use the import math function

2005-07-20 Thread Andre Engels
Please, be more precise. When you say "I tried many different
variations", variations of what? And what kind of variations? When you
say "to get it to work", what is "it"? When you say, "nothing
happened", what do you mean exactly - did your program end with no
output? Did it NOT end with no output? Did you get an error message?

Andre Engels

On 7/20/05, Jimmy <[EMAIL PROTECTED]> wrote:
>
>
>
> My assignment is this:
>
> 4. Read chapter 3 from "How to Think Like a Computer Scientist" (see the
> background materials.) Implement all the examples and exercises in
> Python-Eclipse and after you have successfully run them, export them to be
> combined in a zip with with the other assignments above.
>
>
>
> The course material I have read is this:
> 3.4 Math functions
>
> In mathematics, you have probably seen functions like sin and log, and you
> have learned to evaluate expressions like sin(pi/2) and log(1/x). First, you
> evaluate the expression in parentheses (the argument). For example, pi/2 is
> approximately 1.571, and 1/x is 0.1 (if x happens to be 10.0).
>
> Then, you evaluate the function itself, either by looking it up in a table
> or by performing various computations. The sin of 1.571 is 1, and the log of
> 0.1 is -1 (assuming that logindicates the logarithm base 10).
>
> This process can be applied repeatedly to evaluate more complicated
> expressions like log(1/sin(pi/2)). First, you evaluate the argument of the
> innermost function, then evaluate the function, and so on.
>
> Python has a math module that provides most of the familiar mathematical
> functions. A module is a file that contains a collection of related
> functions grouped together.
>
> Before we can use the functions from a module, we have to import them:
>
> >>> import math
>
> To call one of the functions, we have to specify the name of the module and
> the name of the function, separated by a dot, also known as a period. This
> format is called dot notation.
>
> >>> decibel = math.log10 (17.0)
>  >>> angle = 1.5
>  >>> height = math.sin(angle)
>
> The first statement sets decibel to the logarithm of 17, base 10. There is
> also a function called log that takes logarithm base e.
>
> The third statement finds the sine of the value of the variable angle. sin
> and the other trigonometric functions (cos, tan, etc.) take arguments in
> radians. To convert from degrees to radians, divide by 360 and multiply by
> 2*pi. For example, to find the sine of 45 degrees, first calculate the angle
> in radians and then take the sine:
>
> >>> degrees = 45
>  >>> angle = degrees * 2 * math.pi / 360.0
>  >>> math.sin(angle)
>
> The constant pi is also part of the math module. If you know your geometry,
> you can verify the result by comparing it to the square root of two divided
> by two:
>
> >>> math.sqrt(2) / 2.0
>  0.707106781187
>
> But I have no clue on how to make it work.  I tried many different
> variations to get it to work but in the end nothing happened.  Any help you
> guys can provide would be awesome, I am such a noob to programming it ain't
> even funny.  Thanks……….
>
>
>
>
>
> Jimmy
> ___
> 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] python instances and type

2007-04-16 Thread Andre Engels
2007/4/16, Adam Pridgen <[EMAIL PROTECTED]>:
> Hello,
>
> Sorry for the long email, but thanks in advance.
>
> I am not quite sure what is happening, so I have not been able to
> adequately seek a solution via Google, so if this answer is fairly
> easy to find on Google, let me know.  I am not sure how to produce an
> example of my problem without using the python code and classes that I
> have, so I will try to compose an effective  theoretical example
> below.  If there are any clarifications to be made please let me know.
>
> Basically the problem I am having is obtaining the proper type
> identification from a Python object.  So going through the motions,
> lets say I have 2 types:
> class foo_1:
>data = ""
> class foo_2:
>   foo_1s={}
>
> Time goes by and some assignments are performed and foo_2 is populated
> with some foo_1 objects.  Now, I am using the the function below,
> get_class_resolution to get the type of foo_1 and foo_2, and it works
> well when I don't perform any black magic voodoo and simply use after
> the object is created.
>
> It would return the string "foo_1" for the example below:
>
> x = foo_1()
> x.data = "boring"
> print type(x), type(x).mro()
>  []
> print get_class_resolution(x)
> foo_1

Would it? When I try it out, I get:

>>> class foo_1:
  data = ""

>>> x = foo_1()
>>> x.data = "boring"
>>> print type(x), type(x).mro()
 [, ]
>>> get_class_resolution(x)
[, ]

'instance'


To get your desired behaviour, you need something like:

>>> class foo_1(object):
data = ""


>>> x = foo_1()
>>> x.data = "boring"
>>> print type(x), type(x).mro()
 [, ]
>>> get_class_resolution(x)
[, ]

'__main__'
>>>
--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: how to stop a function

2007-04-24 Thread Andre Engels
-- Forwarded message --
From: Andre Engels <[EMAIL PROTECTED]>
Date: 24 apr. 2007 17:18
Subject: Re: [Tutor] how to stop a function
To: shawn bright <[EMAIL PROTECTED]>


2007/4/24, shawn bright <[EMAIL PROTECTED]>:
> hello all,
>
> i have a gui app that uses functions to respond to gui events.
>
> like
> def on_start_button_clicked(self, stuff):
> do this or that.
>
> now there is one function that i have a kinda nested if else
> conditions that i need to stop if necessary
>
> if value == 1:
> if next_val == 4:
>do this or that
> else:
>here i need the function to just die

else:
 return



--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels


-- 
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] No return statement

2007-04-24 Thread Andre Engels
My opinion is that one should not create or set a variable if its
value is not used. In the case mentioned, you know what the return
value will be, so there seems to be no reason to keep it.

2007/4/24, Cecilia Alm <[EMAIL PROTECTED]>:
> My apologies for asking a trivial question about programming practice.
>
> As mentioned in the online tutorial
> (http://docs.python.org/tut/node6.html#SECTION00670),
> functions which lack a return statement ('procedures') actually return "None".
> For such functions, I assume it's preferred to not catch "None" in a variable.
>
> Example:
> >>> def printme(x):
> print x
>
> Preferred function call:
> >>> printme(10)
> 10
>
> Alternative (where None is caught into z):
> >>> z = printme(10)
> 10
> (And then one could print None)
> >>> print z
> None
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Feeding a list into a function as arguments

2007-04-26 Thread Andre Engels
2007/4/26, Stevie Broadfoot <[EMAIL PROTECTED]>:
> I have a list... say for example
>
> list = ["hello", "there"]
>
> and i have a function
>
> def printout(firstword, secondword):
> print firstword
> print secondword
>
> and i want to call
>
> the function like this
>
> printout(list)
>
> but that doesnt work because it takes the list as an argument.
>
> How can I get around this problem?

I see two simple ways, maybe there are more:

1. simply use
printout(list[0],list[1])

2. Change the definition of printout to:

def printout(firstword, secondword = None):
if secondword is None:
    (firstword,secondword) = firstword
print firstword
print secondword


--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Finding an object by ID

2007-05-02 Thread Andre Engels
It seems to me that this is is an issue that is not resolved in
Python, but in your database's language. Every database language
that's word the name has a command like "get the record that has
such-and-such value for this-and-that property". What command it is,
depends on the database. Or am I now completely misunderstanding your
meaning of the word 'database'?

2007/5/2, Dj Gilcrease <[EMAIL PROTECTED]>:
> I was wondering if it was possible to find and object by it's ID.
>
> what I want to do is something like
>
> def incomingConnection(self, stuff):
> (incSock, incAdder) = self.__sock.accept()
>
> #Add the adder socket ID and other info to a DB
>
> def sendMessage(self, adder, message):
> #query the DB and get the socket ID stored there
>
> sock = getSocketByID(sockID)
>
> #do my send data
>
>
>
> The reason I want to do this is right now I store all the data in a
> dict of class
>
> eg
> class connections:
> def __init__(self, *args, **kwargs):
> self.sock = args[0]
> self.myotherdata = stuff
> ...
>
>
> def incomingConnection(self, stuff):
> (incSock, incAdder) = self.__sock.accept()
> self.conns[incAdder] = connections(incSock, ...)
>
>
> This takes up about 20 megs per person connecting, which is very high
> IMHO, and I am hoping by storing all the data in the database and only
> retrieving it when I need it will help reduce the memory footprint of
> my server
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Working with error messages

2007-05-06 Thread Andre Engels
2007/5/6, Alan Gilfoy <[EMAIL PROTECTED]>:
> I have a number-to-Roman numeral program that churns out ValueError
> messages with a few improper input cases:
>
> 1. not an integer
> 2. larger than 3999
> 3. smaller than 0
>
> When I run the program via IDLE, and I give one of these improper
> inputs, the interpreter closes down the program and then displays the
> appropriate ValueError message.
>
> I would like the appropriate ValueError message to be displayed before
> the program shuts down, or at least a generic ValueError message.
>
> Is looking at my specific pieces of code necessary to help with this?
>
> I want this because if the program's being run as an application, the
> application window closes down as soon as the program closes, and the
> user doesn't get to see the message. [When I doubleclick on the .py
> file in Windows Explorer, it runs as a .exe, for example.]

You could try something like:

try:
   
except ValueError:
   raw_input("I got a ValueError. Press enter to end the program.")
   raise

Of course, the more appropriate thing to do would be to catch the
error at a lower level than the whole program - check where you get
the ValueError, put that line in a try, and take an appropriate action
in the except.

-- 
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Newbie Question on Exceptions...

2007-05-08 Thread Andre Engels
2007/5/8, [EMAIL PROTECTED] <[EMAIL PROTECTED]>:
> I'm working my way through the book "beginning python" and I came across an 
> exercise that suggests using Exception trapping to see if a value is in a 
> dictionary:
>
> fridge={"apple":"A shiny red apple","pear":"a nice ripe 
> pear","grapes":"seadless grapes"}
> food_sought="apple"
> fridge_list=fridge.keys();
> try:
> print "The fridge contains %s" %fridge[food_sought]
> except (KeyError):
> print "The fridge does not contain %s"%food_sought
>
> I'm fairly certain the book is in error in calling this a "short-cut" since 
> the has_key method is much less verbose to use,

Is it?

if fridge.has_key(food_sought):
foo
else:
bar

doesn't look much less verbose than:

try:
foo
except (KeyError):
bar

> but it brings up a question about exceptions in general:
>
> In Java using exceptions in the way shown above is a classic anti-pattern 
> since Exceptions should only be used for..well exceptional conditions.
>
> Is the same true of Python? Or is ok to use Exception handling like the book 
> suggests?

Exceptions are in general much more freely used in Python than in most
other languages, it's called the "EAFP" (It's easier to ask
forgiveness than to get permission) style, instead of the "LBYL" (look
before you leap) style most other languages use.


-- 
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Repeating an action

2007-05-12 Thread Andre Engels
2007/5/12, Alan Gilfoy <[EMAIL PROTECTED]>:
> How do you 'tell' Python to repeat a certain action X amount of times,
> and then stop.
>
> I could use a 'counter' (see below), but that seems kind of clunky.
>
>
>
> counter = 0
> example = True
> while example:
>
>  print "Do something"
>  counter += 1
>
>  if counter == 100:
>  example = False

You can use a for loop:

for i in range(100):
print "Do something"

Your own code is unnecessary wordy too, by the way. The same thing can
be done with:

counter = 0
while counter < 100:
print "Do something"
counter += 1

but of course the 'for' solution is still shorter than this.

-- 
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] trouble with "if"

2007-05-23 Thread Andre Engels
The problem is with types. The outcome of raw_input is a string. But
if you give the line:

if shape == 1:

you are comparing it with a number. The text "1" is not equal to the
number 1, so this evaluates to False.

Instead you should do:

if shape == "1":

To also be able to type 'circle' instead of '1', you can do:

if shape == "1" or shape == "circle":

or alternatively:

if shape in ["1","circle"]:



Andre Engels

2007/5/23, adam urbas <[EMAIL PROTECTED]>:
>
> Hi all,
>
> I've been working with this new program that I wrote.  I started out with it
> on a Ti-83, which is much easier to program than python.  Now I'm trying to
> transfer the program to python but its proving to be quite difficult.  I'm
> not sure what the whole indentation thing is for.  And now I'm having
> trouble with the if statement things.
>
> #"Circle Data Calculation Program:"
> print "Welcome to the Circle Data Calcuation Program."
> print
>
> #"Menu 1:"
> print "Pick a shape:"
> print "(NOTE: You must select the number of the shape and not the shape
> itself)"
> print "1 Circle"
> print "2 Square"
> print "3 Triangle"
>
> #"User's Choice:"
> shape=raw_input("> ")
>
> #"Select Given:"
> if shape == 1:
> print "Choose the given value:"
> print "1 radius"
> print "2 diameter"
> print "3 circumference"
> print "4 area"
>
> #"User's Choice:"
> given=raw_input("> ")
>
> if given == 1:
> radius=raw_input("Enter Radius:")
> diameter=(radius*2)
> circumference=(diameter*3.14)
> area=(radius**2*3.14)
> print "Diameter:", diameter
> print "Circumference:", circumference
> print "Area:", area
>
> if given == 2:
> diameter=raw_input("Enter Diameter:")
> radius=(diameter/2)
> circumference=(diameter*3.14)
> area=(radius**2*3.14)
> print "Radius:", radius
> print "Circumference:", circumference
> print "Area:", area
>
> if given == 3:
> circumference=raw_input("Enter Circumference:")
> radius=(circumference/3.14/2)
> diameter=(radius*2)
> area=(radius**2*3.14)
> print "Radius:", radius
> print "Diameter:", diameter
> print "Area:", area
>
> if given == 4:
> area=raw_input("Enter Area:")
> radius=(area/3.14)
>
> This is the whole program so far, because I haven't quite finished it yet.
> But I tried to get it to display another list of options after you select a
> shape but it just does this.
>
> Pick a shape:
> 1 Circle
> 2 Square
> 3 Triangle
> >1
> >1
> >>>
>
> I'm not sure why it does that but I do know that it is skipping the second
> list of options.
>
> Another of my problems is that I can't figure out how to get it to accept
> two different inputs for a selection.  Like I want it to accept both the
> number 1 and circle as circle then list the options for circle.  It won't
> even accept words.  I can only get it to accept numbers.  It's quite
> frustrating actually.
>
> Any advice would be greatly appreciated.
> Thanks in advance,
> Adam
>
>
>
>
>
> I tried to get it to display ano
>
> 
> Add some color. Personalize your inbox with your favorite colors. Try it!
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] [Fwd: Re: trouble with "if"]

2007-05-30 Thread Andre Engels
2007/5/30, Brian van den Broek <[EMAIL PROTECTED]>:
> Another fwd, folks.
>
> Brian vdB
>
>  Original Message 
> Subject: Re: [Tutor] trouble with "if"
> Date: Tue, 29 May 2007 23:28:46 -0500
> From: Adam Urbas <[EMAIL PROTECTED]>
> To: Brian van den Broek <[EMAIL PROTECTED]>
> References: <[EMAIL PROTECTED]>
> <[EMAIL PROTECTED]>
> <[EMAIL PROTECTED]>
>
> I'm having trouble with the parentheses after the def thing().  IDLE
> says that there is something wrong with it.  If I type something
> between them, it says that there is something wrong with the quotation
> marks.  If I just leave it like (), then it says that something is
> wrong with what is after the parentheses.  Unless my code is supposed
> to go between the parentheses.  I'll try that.

Between the parentheses should go the variables you use (if any) when
calling the function. For example:

def sayhello():
print "Hello"

You don't have any parameters here, so there's nothing between the brackets

def say(word):
print word

Now there is one parameter, namely word.

def sayboth(word1,word2):
print word1
print word2

Here there are two parameters, word1 and word2.

The number of parameters should be the same as the number of
parameters you use when calling the function:

sayhello()
say("One text")
sayboth("One text","Another text")

There is a much used method to make some of the parameters optional,
but we'll not go into that.

To know what is going wrong with your program, I would have to see the
program (or a simplified version of it that still goes wrong) and
preferably also the exact error message you are getting.


-- 
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Multiple Simultaneous Loops

2005-09-15 Thread Andre Engels
On 9/15/05, Ed Singleton <[EMAIL PROTECTED]> wrote:
> I roughly want to be able to do:
> 
> for x, y in bunch_of_files, range(z):
> 
> so that x iterates through my files, and y iterates through something else.
> 
> Is this something I can do?

It's not fully clear to me what you want to do. Do you want to go
through each pair x,y with x in bunch_of_files and y in range(z)? Then
you can do:

for x in bunch_of_files:
for y in range(z):

Or do you want to have one value of y for each value of x? In that
case I think you'd want:
for y in range(len(bunch_of_files)):
x = bunch_of_files[y]

> If so, what would be the best way to create a range of indeterminate length?

I don't think such a thing exists. Either it has some length or it
does not. There's nothing in between.

> If not, is there a nice way I can do it, rather than than incrementing
> a variable (x = x + 1) every loop?
> 
> Or maybe can I access the number of times the loop has run?  ('x = x +
> 1' is so common there must be some more attractive shortcut).

See my second example above?

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


Re: [Tutor] Will the following code ever exit?

2005-09-17 Thread Andre Engels
On 9/17/05, Nathan Pinno <[EMAIL PROTECTED]> wrote:
> Thanks, but when I run the code, even after that change it always just
> prints the questions, correct questions(which is always 0), and percent
> right(always 0). How do I make it enter the quiz.
> Thanks,
> Nathan Pinno

Your program has:

q = random.choice(range(15,31)
cq = 1
while cq >= q:

q has a value between 15 and 31, cq equals 1. 1 is not greater than or
equal to any number between 15 and 31, so cq >= q is always false. I
think you meant to write:

while q >= cq:

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


Re: [Tutor] if-else statements

2005-10-14 Thread Andre Engels
2005/10/14, [EMAIL PROTECTED] <[EMAIL PROTECTED]>:
> Hello
>
> I'm having some trouble with my if, else statements. For some reason, the
> months that have 31 days work fine, but the months that have 28/30 do not
> work. Am I doing something wrong? it is supposed to take a date as an
> input like 9/31/1991 and then say that the date is not valid because
> september only has 30 days.

First hint:
Where is 'month' used in your program? The answer is: nowhere. It
should be used. Why?

Second hint:
Currently, the program checks each date first for validity with
respect to January, then throws the outcome away to do the same with
February, etcetera upto December. Thus, the final outcome says whether
the date is correct in December, not whether it is correct in the
given month.

(actual code below)

> import string
>
> def main():
> # get the day month and year
> month, day, year = input("Please enter the mm, dd, : ")
> date1 = "%d/%d/%d" % (month,day,year)
>
> months = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
>
> if day <= months[1]:
> d = "valid"
> else:
> n = "not valid"
>
> if day <= months[2]:
> d = "valid"
> else:
> d = "not valid"
>
> if day <= months[3]:
> d = "valid"
> else:
> d = "not valid"
>
> if day <= months[4]:
> d = "valid"
> else:
> n = "not valid"
>
> if day <= months[5]:
> d = "valid"
> else:
> d = "not valid"
>
> if day <= months[6]:
> d = "valid"
> else:
> d = "not valid"
>
> if day <= months[7]:
> d = "valid"
> else:
> d = "not valid"
>
> if day <= months[8]:
> d = "valid"
> else:
> d = "not valid"
>
> if day <= months[9]:
> d = "valid"
> else:
> d = "not valid"
>
> if day <= months[10]:
> d = "valid"
> else:
> d = "not valid"
>
> if day <= months[11]:
> d = "valid"
> else:
> d = "not valid"
>
> if day <= months[12]:
> d = "valid"
> else:
> d = "not valid"
>
> print "The date you entered", date1, "is", d +"."
>
> main()

Correct and shortened code:

Instead of the whole line "if day <= months[1]"... series of
if-then-else statements, use only one statement, namely:

if day <= months[month]:
d = "valid"
else:
d = "not valid"

--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] password protection in httplib

2006-03-01 Thread Andre Engels
I am active in pywikipediabot, which is programmed in Python and is
used to edit wikis (based on MediaWiki, such as Wikpedia). It uses
httplib to connect to the site and get the HTML data.

I now want to use it on another site, but this site is password
protected (we want to first improve it before releasing it to the
public). Is it possible with httplib to connect to password protected
sites (given that I know the login and password of course), and if so,
how is this done? If not, is there an alternative?

--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] password protection in httplib

2006-03-02 Thread Andre Engels
Thanks for your help; it brought me quite a bit farther, but not as
far as I wanted to come. The authentication is basic authentication,
and I have been able to adapt the programs so that I now get my pages
correctly.

However, the program uses not only 'GET' operations, but also 'PUT'
operations. These are done using httplib rather than urllib, and I
cannot see at this point how I can mimick those using urllib2.

Andre Engels

2006/3/1, Kent Johnson <[EMAIL PROTECTED]>:
> Andre Engels wrote:
> > I am active in pywikipediabot, which is programmed in Python and is
> > used to edit wikis (based on MediaWiki, such as Wikpedia). It uses
> > httplib to connect to the site and get the HTML data.
> >
> > I now want to use it on another site, but this site is password
> > protected (we want to first improve it before releasing it to the
> > public). Is it possible with httplib to connect to password protected
> > sites (given that I know the login and password of course), and if so,
> > how is this done? If not, is there an alternative?
>
> What kind of authentication is used? Basic and digest authentication
> will pop up a dialog in the browser asking for your credentials. The
> browser then remembers the credentials and includes them in subsequent
> requests. With form-based authentication, a page displays in the browser
> with a login form; the web site authenticates and usually sends a cookie
> to the browser which must be included in subsequent requests.
>
> urllib2 has good built-in support for basic and digest authentication of
> web sites. For form-based authentication you have to do a bit more work
>   - install a cookie manager and post to the form yourself.
>
> See http://www.voidspace.org.uk/python/articles/authentication.shtml for
> examples of basic auth. Digest auth works pretty much the same way. Make
> sure you read to the section "Doing It Properly" - the author likes to
> show you the hard way first.
>
> The article http://www.voidspace.org.uk/python/articles/cookielib.shtml
> shows how to use cookies, though again the presentation makes it look
> harder than it really is, at least in Python 2.4 that has CookieLib
> built in. You have to post to the login form yourself, but that is just
> another urllib2 request.
>
> Kent
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] password protection in httplib

2006-03-03 Thread Andre Engels
2006/3/2, Kent Johnson <[EMAIL PROTECTED]>:
> Andre Engels wrote:
> > Thanks for your help; it brought me quite a bit farther, but not as
> > far as I wanted to come. The authentication is basic authentication,
> > and I have been able to adapt the programs so that I now get my pages
> > correctly.
> >
> > However, the program uses not only 'GET' operations, but also 'PUT'
> > operations. These are done using httplib rather than urllib, and I
> > cannot see at this point how I can mimick those using urllib2.
>
> The docs don't spell it out, but if you pass the 'data' parameter to
> urllib2.urlopen(), it will make a POST request instead of a GET. The
> data has to be formatted as application/x-www-form-urlencoded;
> urllib.urlencode() will do this for you.
>
> So for example:
>
> import urllib, urllib2
> data = dict(param1='foo', param2='bar')
> data = urllib.urlencode(data)
>
> # set up your basic auth as before
> result = urllib2.urlopen('http://some.server.com', data).read()

Thanks, I've gotten some further again, but the following problem is
that I am using this connection to get some cookies, which are read
from the page headers. As far as I can see, urllib2 puts the page
headers into a dictionary, which is not what I need, because there are
4 different set-cookie headers sent out by the site, and I get only
one "set-cookie" value. Am I right in this, and is there a way around
it?


--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] password protection in httplib

2006-03-03 Thread Andre Engels
2006/3/3, Kent Johnson <[EMAIL PROTECTED]>:

> Have you tried using a CookieManager as shown in the first example here:
> http://docs.python.org/lib/cookielib-examples.html
>
> Once you set up your opener with a CookieJar the cookies should be
> handled automatically - if a server sets a cookie it will be remembered
> and returned back to the server on subsequent requests.
>
> This page has more examples though again IMO they are overly complex:
> http://www.voidspace.org.uk/python/articles/cookielib.shtml

I had looked at it yes, but I don't know how to combine the two
handlers (the one for authentication and the one for cookies). Apart
from that I hoped that because the program already has cookie handling
programmed in, reusing that code might be less trouble than splitting
the authenticated and the non-authenticated case everywhere.

--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] password protection in httplib

2006-03-03 Thread Andre Engels
Thanks for your answers! It is working now!

2006/3/3, Kent Johnson <[EMAIL PROTECTED]>:
> Andre Engels wrote:
> > 2006/3/3, Kent Johnson <[EMAIL PROTECTED]>:
> >
> >
> >>Have you tried using a CookieManager as shown in the first example here:
> >>http://docs.python.org/lib/cookielib-examples.html
> >>
> >>Once you set up your opener with a CookieJar the cookies should be
> >>handled automatically - if a server sets a cookie it will be remembered
> >>and returned back to the server on subsequent requests.
> >>
> >>This page has more examples though again IMO they are overly complex:
> >>http://www.voidspace.org.uk/python/articles/cookielib.shtml
> >
> >
> > I had looked at it yes, but I don't know how to combine the two
> > handlers (the one for authentication and the one for cookies). Apart
> > from that I hoped that because the program already has cookie handling
> > programmed in, reusing that code might be less trouble than splitting
> > the authenticated and the non-authenticated case everywhere.
>
> The call to urllib2.build_opener() accepts multiple arguments, just list
> both handlers.
>
> Kent
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] pyexpat

2006-04-18 Thread Andre Engels
I am working for the Python Wikipediabot Framework
(http://www.sourceforge.net/pywikipedia). A user noted me to an
apparent deadlock in the XML parsing. I tried to get to the actual
parsing code to see what went wrong. The furthest I get, however, is
in the feed() method of the class ExpatParser in expatreader.py. There
is a line there:

self._parser.Parse(data, isFinal)

self._parser, as I have found, is an object of the class
pyexpat.xmlparser, but I have no idea about where to fine pyexpat. Can
anyone help me further?



--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pyexpat

2006-04-18 Thread Andre Engels
2006/4/18, Kent Johnson <[EMAIL PROTECTED]>:
> Andre Engels wrote:
> > I am working for the Python Wikipediabot Framework
> > (http://www.sourceforge.net/pywikipedia). A user noted me to an
> > apparent deadlock in the XML parsing. I tried to get to the actual
>
> That's pretty surprising, I wouldn't expect the parser to use any locks.
> Can you say more about the deadlock?

I have found some more, and there is not a deadlock... Just the thing
is going damn slow on this specific text, not sure why. Thanks anyway.

--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pyexpat

2006-04-19 Thread Andre Engels
2006/4/18, Danny Yoo <[EMAIL PROTECTED]>:

> H Can you send a link to the text that's causing performance
> issues?  It might be possible that someone here might isolate the
> performance problem.  (Hey, it happened before with BeautifulSoup...
> *grin*)

I have sent the text (and another text that did not cause problems) to
Danny; sending it to this list was disallowed because of length (about
1.5M for the 'slow' case and about half of that for the 'fast' one).

--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Object defined by initialization parameters

2006-04-24 Thread Andre Engels
Is it possible to define a class in such a way, that if twice an
object is made with the same initialization parameters, the same
object is returned in both cases?

More specifically, suppose I have the following program:

class myObj(object):
def __init__(self,a):
self._a = a
self._seen = 0
def touch(self):
self._seen += 1
def count(self):
return self._seen

x = myObj("a")
y = myObj("a")
z = myObj("b")
x.touch()

After this, x._seen will return 1, but y._seen and z._seenwill return
0. I would like the definition of the myObj class to be such that
after these definitions x and y refer to the same object, but z to a
different one.

If there is not such possibility, does anyone have a better or more
elegant workaround than the one I am using, which is:

class myObj(object):
def __init__(self,a):
self._a = a
self._seen = 0
def touch(self):
self._seen += 1
def count(self):
return self._seen

def obj(a):
try:
return objects[a]
except KeyError:
objects[a] = myObj(a)
return objects[a]

objects = {}
x = obj("a")
y = obj("a")
z = obj("b")
x.touch()



--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] decimal floating point?

2006-05-02 Thread Andre Engels
2006/5/2, michel maho <[EMAIL PROTECTED]>:
>
> To all
> I have the following calculation:
>
> "Je Body Mass Index is",gewicht/lengte**2
>
> The result is a (digital?)floating point figure with with 10 decimal
> numbers. For =
> example 27.2345678487
> Did I mis something? I would like to reduce it to one or two decimal =
> numbers.(27.2) but round(_,1) does not work.
> Is there any other way?
> Thank You
> Michel Maho
> Sorry if this is a second mail.
> Something went wrong

You can use string formatting here:
"Je Body Mass Index is %.1f"%gewicht/lengte**2

The % inside the string says that one should format the thing
following the % after the string here. ".2f" specifies how it should
be formatted - f says that we will have a floating-point value, shown
in decimal (not exponentional form), and the .1 means that there
should be 1 digit after the decimal dot.

--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] decimal floating point?

2006-05-02 Thread Andre Engels
> You can use string formatting here:
> "Je Body Mass Index is %.1f"%gewicht/lengte**2

Actually, I'm not sure this word work correctly. Better:

"Je Body Mass Index is %.1f"%(gewicht/lengte**2)

that should definitely owrk



--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] what %s=%s means?

2006-07-05 Thread Andre Engels
2006/7/6, 韩宪平 <[EMAIL PROTECTED]>:
> I realy new to python.I try on learning it by code examples.The
> following one from "Dive into python":
>
> def buildConnectionString(params):
> """Build a connection string from a dictionary of parameters.
>
> Returns string."""
> return ";".join(["%s=%s" % (k, v) for k, v in params.items()])

> Whant ";"means

";" simply means the string consisting of the one character ;

> %s=%s?

You'll have to look at the more complete expression here:
"%s=%s" % (k, v)

%s then means, in this string replace me by the next element in the
tuple following the %. Thus, the above will evaluate to the string
consisting of the string representation of k followed by the character
= followed by the string representation of v.

Some examples to make it clearer:
"I am %s"%("John")
will evaluate to:
"I am John"

"%s is a number"%(7)
will evaluate to:
"7 is a number", because the stuff in the tuple doesn't need to be a string

If x equals 1 and y equals 2, "%s+%s=%s"%(x,y,x+y)
will evaluate to:
"1+2=3"

> join?

Join is a method of a string. Its syntax is:
x.join(y)
where x must be a string and y a sequence of strings. It denotes a
string, consisting of the strings in y, with x between each pair.
Again, a few examples will make it more clear:

" ".join(["I","am","a","boat"])
evaluates to:
"I am a boat"

"-abc-".join(["I","am","a","boat"])
evaluates to:
"I-abc-am-abc-a-abc-boat"

and
"".join(["I","am","a","boat"])
evaluates to:
"Iamaboat"

-- 
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] [Fwd: guess]

2006-10-04 Thread Andre Engels
2006/10/4, Kent Johnson <[EMAIL PROTECTED]>:

> hey i added another guessing feature that shuld guess the number in the
> most
> effective  way
> but i keep getting into endless loops thought you might want it
> any help with the loops would be great

What's the value of number? Where is it defined? If number is not an
integer or number > ran, then you will indeed end up in an infinite
loop.


--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Can my code be optimized any further (speed-wise)?

2006-10-08 Thread Andre Engels
2006/10/7, Geoframer <[EMAIL PROTECTED]>:
> Hi everyone,
>
> The last few days i've been learning python and have been doing this by
> trying to solve problems for a programming competition.
> One particular problem is bugging me. I have already solved it but my
> solution does not compute in the set time-condition. I know
> for a fact that this particular problem is solvable in the time-limit using
> Python, so i was wondering if my solution is maybe inefficitient code-wise.
> If my code can't be optimized for speed any more i must be missing something
> and should labor hard to find a new algorithm ;-).
>
> The problem is to compute the number of trailing zero's in factorials (n! =
> 1*2*3*4*...*n). with n <= 10
>
 > My solution is as follows (a = times to read a number (b) to process) :
>
> ---
>
> a = input()
> for i in range(a):
> lst = (5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
> 48828125, 244140625)
> ans = 0
> b = input()
> for i in lst:
> if i <= b:
>  ans += b//i
> print ans
>
> 
>
> Please, if you have suggestions to improve the speed of this algorithm give
> an argumentation as to why a certain something is faster.
> That would allow me to learn to program faster algorithms in Python al
> together instead of just in this problem.

The program as you have shown it, skims to incorrectness. Please don't
use the same variable (i) for two nested loops!

Regarding speed, I see some small improvements:

* lst is created each time you go through the loop; creating it once
would suffice as well
* If we have found that some i is larger than b, then definitely the
next one will be

a = input()
lst = (5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
48828125, 244140625)
for i in range(a):
ans = 0
b = input()
for j in lst:
if j <= b:
ans += b//i
else:
break
print ans

The first thing (moving the lst= out of the loop) will definitely make
a (tiny) improvement on speed; it also improves the logic of your
code. The second (the else: break) I am not sure whether it will
improve things (because often you will go into the else at the last
time or not at all).

Your program goes wrong for large values of b. This should be avoided
- the program should have as little chance as possible for the user to
give 'wrong' input, either by forbidding it or by dealing with it.
Here the latter is easily done:

The way I would do this (although it would make the program slower
rather than faster because it would make the check each time that b is
set:

replace

lst = (5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625,
48828125, 244140625)

by

lst = [5]

and after b=input()
add:
while lst[-1]*5 < b:
lst.append(lst[-1]*5)

And finally I wonder why on Earth you would worry about the speed of
this program, given that the running time over 1 number is just a
fraction of the time it costs you to type in that number.



-- 
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question on joining out of order dictionary elements

2007-01-11 Thread Andre Engels

2007/1/11, raghu raghu <[EMAIL PROTECTED]>:


>>> print "\\".join((config["val2"],config["val1"],config["val3"]))
elem2\elem1\elem3

or

>>> print "%s\\%s\\%s" % (config["val2"],config["val1"],config["val3"])
elem2\elem1\elem3

but this seems somehow uneligent.

Are there a more efficient/compact ways of doing this kind of
operation or is this it?



Maybe you like:
print "\\".join([config[val] for val in ["val2","val1","val3"]])

--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Clustering?

2007-01-16 Thread Andre Engels

2007/1/16, Carlos <[EMAIL PROTECTED]>:


Hello to everybody,

I have a question that I think is a little related to clustering, I have
a list of lists, like this:

List = [[1,5],[6,8],[48,10],[99,56]]

The list is composed by a large number of lists not just four, and each
'interior' list contains two numbers that are the location of an object
in a plane, so they are X and Y coordinates, my question is:

Can I use this list to evaluate how many points are in a given range?
Thats is taking the highest and lowest values for X an Y and, lets say
divide that range in 10 regions, then get the number of objects on each
region. Is this possible? and if yes, how canI do it? I ask this because
as you know my python skills are not that great :)



First, this feels like a list of tuples rather than a list of lists;
however, tuples and lists don't differ that much in their behaviour, so
there's nothing really lost.

And yes, it is possible. An inline if would be the way I would resolve that:

def withinrange(list,xmin,xmax,ymin,ymax):
   # Get the elements of list for which the first part of the pair is
between xmin and xmax
   # (inclusive) and the second between ymin and ymax.
   return [c for c in list if xmin <= c[0] <= xmax and ymin <= c[1] <=
ymax]

The longer but clearer method of doing the same would be:

def withinrange(list,xmin,xmax,ymin,ymax):
   templist = []
   for c in list:
   if xmin <= c[0] <= xmax and ymin <= c[1] <= ymax:
       templist.append(c)
   return templist

--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] possible import locations

2007-01-17 Thread Andre Engels

Is it possible to see from a python program where it searches for possible
imports? Is it possible to import from another location than those? (Of
course with an "if so, how" attached).

The issue is that the company I work for is switching providers. With the
old provider (as well as in my local setting), Python automatically searched
for imports in the current directory (the one where the program was run).
With the new one, this does not seem to be the case, so I am getting
ImportErrors all over the place.

--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Redirect from a CGI script

2007-01-18 Thread Andre Engels

2007/1/18, Paulino <[EMAIL PROTECTED]>:


How can i redirect to another URL from a python CGI script.

Is's suposed to be as simply as:

print "Location : http://newurl "
It's not working.

this simple code does't work - 
'print "Content-Type:text/html\n\n"
'print "Location : /cgi-bin/ecodiv.pyw "
'print

I use CGIHTTPServer, the server script is as follows:

'from BaseHTTPServer import HTTPServer
'from CGIHTTPServer import CGIHTTPRequestHandler
'HTTPServer(("localhost", 80), CGIHTTPRequestHandler).serve_forever()

instead of redirecting, it only prints 'Location : /cgi-bin/ecodiv.pyw'
inthe
browser




I haven't tested it, but I think I had a similar error recently, and that
was solved by removing the \n\n at the end of the Content-Type line. You
could try that.




--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about *args and functions

2007-01-26 Thread Andre Engels

2007/1/26, shawn bright <[EMAIL PROTECTED]>:


lo there all,

if i have a function that sometimes needs a value passed to it and
sometimes not, is this where i use *args ?



No. *args is used if there are arguments that could occur more than once.

like this


def some_function(req_var, req_var2, un_req_var):
do some stuff
return value

how would i use this if sometimes i need to process un_req_var and
sometimes not ?



Use:
def some_function(req_var, req_var2, un_req_var = None):
   do some stuff
   return value

Now, the function can be called both with and without un_req_var, and if it
is called without un_req_var, within the function body un_req_var is
considered to be None.


--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Range of float value

2007-02-08 Thread Andre Engels

2007/2/8, Johan Geldenhuys <[EMAIL PROTECTED]>:


 Hi all,

I have a value that ranges between 48.01 and 48.57. a Float value in other
words.

I want to look at changes in the value. If my normal range is between
48.35 and 48.45, how will I identify the value below 48.35 and above 48.45
?

Something I tried was:

for a in range(48.35, 48.45):
print a

It gives me a value of 100.

Is it possible to get a range of a float value?



It depends. What would you like it to be? All numbers in that range? They're
uncountably infinite, so no way we could ever get that out of the computer.
All actual float values? Depends too much on the implementation of the
specific machine you're working on to be workable.

Identifying values below 48.35 and above 48.45 is simply done by:
if value < 48.35 or value > 48.45 then...

No need to first create the range of values

--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Replying to the tutor-list

2007-02-15 Thread Andre Engels

2007/2/14, Alan Gauld <[EMAIL PROTECTED]>:


Because hitting Reply and sending to a list would only be
consistent if the list was the originator of the message.
Some mailing lists do implement this bizarre and
non-standard email behaviour but thankfully the Python
community doesn't! This behaviour has been standard
in email tools for over 25 years, let's not try to change
it now!



It's getting to be the majority of mailing lists that do it the other way,
and I find it quite irritating that this list does not - I have had several
times that I sent a mail, and after sending it, sometimes long after sending
it, I realize I sent it to the sender instead of the list, so I send a
second message after it. Who knows how often I have failed to do that?

--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Replying to the tutor-list

2007-02-15 Thread Andre Engels

2007/2/15, ALAN GAULD <[EMAIL PROTECTED]>:


 > realize I sent it to the sender instead of the list,
> so I send a second message after it.

So do you find it odd when dealing with normal email
and you hit reply and it only goes to the sender?



No, because it is sent by the sender to me, not to some list.

Or do you not use email beyond one to one and list

membership? Surely you are introducing inconsistent
behaviour between your private mail and your list mail??



No, in my private mail I hit 'reply' and I reply. In my mailing lists I hit
'reply' and reply.

I seriously cannot fathom why anyone would want a tool

that makes things operate two differenmt ways, one for
normal email and one for mailing lists. They all come into
the same mailbox, I want them all to work the same way!



Well, what is the 'same way'? When I reply, I reply. When I get something
from a person, and reply it goes to that person. When I read something on a
newsgroup and reply, it goes to that newsgroup. When I read something on a
forum and reply, it goes to that forum.

As a matter of interest, what happens if you hit ReplyAll

on the other style lists? I assume that would work as I
would expect and send to the list and sender?
If so how do you send to the sender only?



Change the address by hand. That's hard to do, it's true, but the number of
times I want to reply in person to a message on a list is so low that that's
no problem at all.


--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What is the augmented assignment operator "^="

2007-02-19 Thread Andre Engels

2007/2/19, Dick Moores <[EMAIL PROTECTED]>:


The docs list it at <http://docs.python.org/ref/augassign.html>, and
send you to <http://docs.python.org/ref/primaries.html#primaries>,
which seems a dead end.

I've tried "^=" out a bit:

>>> n = 5
>>> n ^= 8
>>> n
13
>>> n ^= 8
>>> n
5
>>> n ^= 8
>>> n
13
>>> n ^= 8
>>> n
5

and get that strange alternating behavior. Can someone explain?  And
while at it, please also explain "&=" and "|=".



To understand these operators, you will have to think of the numbers as
binary numbers. Look at the digits. For two numbers x and y, x^y is the
effect of doing an exclusive or on all digits (that is, 0^1 = 1^0 = 1 and
0^0 = 1^1 = 0), & of doing an and (1&1 = 1, 1&0=0&1=0&0=0) and | is an or on
all digits (1|1=1|0=0|1 = 1, 0|0 = 0).

So 5^8 = 110 ^ 1000 = 0110 ^ 1000 = 1110 = 13
and 13^8 = 1110 ^ 1000 = 0110 = 5



--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What is the augmented assignment operator "^="

2007-02-19 Thread Andre Engels

2007/2/19, Dick Moores <[EMAIL PROTECTED]>:


At 02:17 AM 2/19/2007, Andre Engels wrote:

>To understand these operators, you will have to think of the numbers
>as binary numbers. Look at the digits. For two numbers x and y, x^y
>is the effect of doing an exclusive or on all digits (that is, 0^1 =
>1^0 = 1 and 0^0 = 1^1 = 0), & of doing an and (1&1 = 1,
>1&0=0&1=0&0=0) and | is an or on all digits (1|1=1|0=0|1 = 1, 0|0 = 0).
>
>So 5^8 = 110 ^ 1000 = 0110 ^ 1000 = 1110 = 13
>and 13^8 = 1110 ^ 1000 = 0110 = 5

Thanks, Andre! I've got it for the three operators, for non-negative
integers. But I'm not sure I understand how negative integers work.
For example, is 3 & -3 = 1
because it is 11 & -11 = 01, and that's because one of the first
digits of 11 and -11 is not 1, and both of their 2nd digits ARE 1, Q.E.D.?



This has to do with the internal representation of negative numbers: -1 is
represented as 111111, with one 1 more than maxint. -2 is 111...110 and
-3 is 111...101. Thus 3 & -3 is 11 & 111...101 = 1

Also, of what practical use are these things?




I guess they have their uses for people accustomed to dealing with hardware.
Apart from that, you can get a very space-efficient representation for
multiple boolean variables. If you have what looks like an array of
booleans, you could also represent it as a single natural number, for
example [true, true, false, false, true, false] would then be 1*1 + 1*2 +
0*4 + 0*8 + 1*16 + 0*32 = 19. Using such a representation and the above
operators would enable one to write

z = x & y

instead of

z = [x[i] and y[i] for i in range(len(x))]

when modelling the same using lists.

Of course this does come at the price of complicating

x[i] = true

to

x |= 2 ** i

which though not really longer does definitely look harder to understand.

--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] breaking the 'while' loop

2007-03-20 Thread Andre Engels

2007/3/20, Alexander Kapshuk <[EMAIL PROTECTED]>:


 Dear All,



I have been learning computer programming with Python only for a short
while. I have a question to do with breaking the *while loop*.



I have attached the source code of a program called 'Guess my number' with
the *while loop* running until the right number is guessed.



I want to limit the number of tries to 5. To do that, I have tried the *if
structure* along with the *break statement* immediately below the

'tries += 1' line:



if tries > 5:

  break

 print "Wrong guess!"



Which still did not result in the *while loop* breaking after attempt No
5.



I would appreciate being explained what I am doing wrong.


It would have helped if you had given the code *with* the extra lines in it.
My first guess is that you did a wrong indentation, but without the actual
code I cannot be sure.

--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Another string question

2007-03-23 Thread Andre Engels

2007/3/22, Jay Mutter III <[EMAIL PROTECTED]>:


I wanted the following to check each line and if it ends in a right
parentheses then write the entire line to one file and if not then
write the line to anther.
It wrote all of the ) to one file and the rest of the line (ie minus
the ) to the other file.



The line:
print "There are ", count, 'lines to process in this file'
should give you a hint - don't you think this number was rather high?

The problem is that if you do "for line in text" with text being a string,
it will not loop over the _lines_  in the string, but over the _characters_
in the string.

The easiest solution would be to replace
text = in_file.read()
by
text = in_file.readlines()

in_filename = raw_input('What is the COMPLETE name of the file you

would like to process?')
in_file = open(in_filename, 'rU')
text = in_file.read()
count = len(text.splitlines())
print "There are ", count, 'lines to process in this file'
out_filename1 = raw_input('What is the COMPLETE name of the file in
which you would like to save Companies?')
companies = open(out_filename1, 'aU')
out_filename2 = raw_input('What is the COMPLETE name of the file in
which you would like to save Inventors?')
patentdata = open(out_filename2, 'aU')
for line in text:
 if line[-1] in ')':
 companies.write(line)
 else:
 patentdata.write(line)
in_file.close()
companies.close()
patentdata.close()

Thanks

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





--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Another string question

2007-03-23 Thread Andre Engels

2007/3/23, Jay Mutter III <[EMAIL PROTECTED]>:



On Mar 23, 2007, at 5:30 AM, Andre Engels wrote:

2007/3/22, Jay Mutter III < [EMAIL PROTECTED]>:
>
> I wanted the following to check each line and if it ends in a right
> parentheses then write the entire line to one file and if not then
> write the line to anther.
> It wrote all of the ) to one file and the rest of the line (ie minus
> the ) to the other file.


The line:
 print "There are ", count, 'lines to process in this file'
should give you a hint - don't you think this number was rather high?

The problem is that if you do "for line in text" with text being a string,
it will not loop over the _lines_  in the string, but over the _characters_
in the string.

The easiest solution would be to replace
 text = in_file.read()
by
 text = in_file.readlines()


Thanks for the response
Actually the number of lines this returns is the same number of lines
given when i put it in a text editor (TextWrangler).
Luke had mentioned the same thing earlier but when I do change read to
readlines  i get the following


Traceback (most recent call last):
  File "extract_companies.py", line 17, in ?
count = len(text.splitlines())
AttributeError: 'list' object has no attribute 'splitlines'




Ah, yes, there you DO split in lines, but later you don't. You'll have to do
the same thing twice, that is either:

text = in_file.readlines()
count = len(text) # (instead of count = len(text.splitlines())

OR

text = in_file.read()
for line in text.splitlines(): # (instead of for line in text:)

in_filename = raw_input('What is the COMPLE

>
 TE name of the file you
> would like to process?')
> in_file = open(in_filename, 'rU')
> text = in_file.read()
> count = len(text.splitlines())
> print "There are ", count, 'lines to process in this file'
> out_filename1 = raw_input('What is the COMPLETE name of the file in
> which you would like to save Companies?')
> companies = open(out_filename1, 'aU')
> out_filename2 = raw_input('What is the COMPLETE name of the file in
> which you would like to save Inventors?')
> patentdata = open(out_filename2, 'aU')
> for line in text:
>  if line[-1] in ')':
>  companies.write(line)
>  else:
>  patentdata.write(line)
> in_file.close()
> companies.close ()
> patentdata.close()
>
> Thanks
>
> jay
> ___
> Tutor maillist  -   Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels






--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Unicode in List Object

2007-03-26 Thread Andre Engels

2007/3/26, Roman Kreuzhuber <[EMAIL PROTECTED]>:


Thanks for the quick response!
I see! Oh I didn't realize that it's not the list which raises an error.
For a test I tried to insert a string containing a unicode character as
follows:

ListObject = []
ListObject.insert(0,u"Möälasdji")

which raises: "SyntaxError: Non-ASCII character '\xfc' in file C:\python
proj\lists\main.py on line 48, but no encoding declared; see
http://www.python.org/peps/pep-0263.html for details"



At the top of your Python file, below the line which might be there that
reads

#!/usr/bin/python

but above any other line, add:

# -*- coding: utf-8  -*-

This tells the parser that this file should be read as unicode.

--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need help with a regular expression

2008-06-28 Thread Andre Engels
On Sat, Jun 28, 2008 at 11:15 AM, Kelie <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I'm trying to write a regular expression to filter strings that meet the
> following criteria:
>
> 1. Starts with 0-3 underscores;
> 2. Followed by one letter;
> 3. Then followed by 0 or more letters or digits or hyphens('-'),
> 4. Ends with one letter or digit; and
> 5. There should not be more than one continuous hyphens.
>
> This is what I have so far. I think it meets all the criteria except for the
> last one. Haven't figured out the answer yet.
>
> re.compile(r'_{0,3}[A-Z][A-Z0-9\-]*[A-Z0-9]')

I think

_{0,3}[A-Z](\-?[A-Z0-9])+

will do what you are looking for.


-- 
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644 -- Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need help with a regular expression

2008-06-28 Thread Andre Engels
On Sat, Jun 28, 2008 at 3:21 PM, Lie Ryan <[EMAIL PROTECTED]> wrote:

> > I think
> >
> > _{0,3}[A-Z](\-?[A-Z0-9])+
> >
> > will do what you are looking for.
>
> That, doesn't allow single hyphen, which his requirement allowed as long
> as it (the hypehn) is not as the first or last character.

The \-? allows a hyphen, doesn't it?



-- 
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644 -- Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is "var = None" in Python equivalent to "Set var = Nothing"in VB?

2008-06-30 Thread Andre Engels
On Mon, Jun 30, 2008 at 11:26 AM, Kelie <[EMAIL PROTECTED]> wrote:
> wesley chun  gmail.com> writes:
>> one question i'd like to ask is, in what context is such a line part
>> of your code? altho alan is correct in that syntactically, they're
>> very similar, i'm wondering what you're using it for.
>
> Wesley,
>
> Thanks for your reply (also thanks to others who replied). I was trying to
> translate a VBA sample in this page http://tinyurl.com/3hvj3j to python. The 
> VBA
> sample has a line "Set objDbx = Nothing".

I don't know about Visual Basic, but in Python these statements are unnecessary.



-- 
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644 -- Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


  1   2   >