Re: [Tutor] new to python

2017-07-25 Thread Andre Engels
The problem here is that you have doubled the "for line in f:" line.
Given that you say you know some programming, I'll just cut to the
technical name of the problem you are having: You are changing the
value of a loop variable (by starting an inner loop with the same loop
variable) inside a loop. Doing that in Python leads to behaviour that
is hard to understand and almost never what you intended.


On Tue, Jul 25, 2017 at 5:58 AM, N6Ghost  wrote:
>
>
> On 7/23/2017 1:03 AM, Alan Gauld via Tutor wrote:
>>
>> On 23/07/17 07:26, N6Ghost wrote:
>>
>>> f = open("C:\coderoot\python3\level1\inputfile.txt", 'r')
>>> for line in file:
>>
>> Note that you have no variable called 'file'.
>> So this line doesn't make sense.
>>
>>>   for line in f:
>>>   print(line.rstripe())
>>
>> This bit will work if you omit the line above and
>> fix the indentation. (and remove the 'e' from strip()
>>
>>>   f.close()
>>
>> This should be outside the loop, you don't want
>> to close the file after every line.
>>
>> Finally, there is another way to do this which
>> is considered 'better'/more Pythonic:
>>
>> with open("C:\coderoot\python3\level1\inputfile.txt", 'r') as f:
>>   for line in f:
>>   print(line.strip())
>>
>> Notice with this construct the closing of the file is
>> handled for you.
>>
>>> any idea why that does not work?
>>
>> When posting questions always include the full error text.
>> Although apparently cryptic it actually contains a lot of
>> useful detail which saves us from making guesses.
>>
>
>
> this code works
> f = open("C:/coderoot/python3/level1/inputfile.txt", 'r')
> for line in f:
> for line in f:
> #print(line.rstrip())
> print(line)
>
> f.close()f = open("C:/coderoot/python3/level1/inputfile.txt", 'r')
> for line in f:
> for line in f:
> #print(line.rstrip())
> print(line)
>
> f.close()
>
> the out put skips the first line of the inputfile and puts a blank line
> inbetween
>
> inputfile is:
> tom
> jerry
> make
> windows
> linux
>
> -N6Ghost
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor



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


Re: [Tutor] (no subject)

2011-11-17 Thread Andre Engels
On Thu, Nov 17, 2011 at 2:14 PM, Nidian Job-Smith wrote:

>  Hi all,
>
> I'm new to programming (thus Python), so after reading the
> basics, I wanted to practise what I've learnt . I've come across a
> beginners exercise which is to programme rot13.
>
> I've written some code but it doesn't seem to work
>
> Here it is:
>
>
> def rot13(s):
> char_low = ()
> result = ""
> if not s.isalpha():
> return char
> char_low = char_low.lower()
> if char_low <= 'm':
> dist = 13
> else:
> dist = -13
> char = chr(ord(char) + dist)
>
> def rot13_char(ch):
>   return ''.join( rot13(s) for char in ch )
>
>
> Any idea where i'm wrong?
>


Please, when posting a program that has problems to this list, do not just
say that "it doesn't work". Tell us what is wrong:
* If you get a syntax error, tell us that, and tell us where it is claimed
the syntax error is
* if you get an error message, give the error message as well as the stack
trace provided with it, or at least the last part of that stack trace
* If the program does not crash, but behaves different from what you
expected, tell us what you expected to get, and what you actually got (for
example, "After giving the input 5 and 3 I had expected the program to
output 8 and ask for a new pair of numbers, but instead it showed 8 lines
of 8 stars, printed 'Thank you for using my program' and ended.

Having said that, using your program gave me various problems. The first
was in return ''.join( rot13(s) for char in ch ) - I got an error message
that the name 's' was not defined. Reason: the variable before the for
should be the same as after, so you should either say 'rot13(s) for s in
ch' or 'rot13(char) for char in ch'

Most of your other problems had the same cause: If you want to use
something (a thing, a number, a letter, whatever), use the same name as you
used when you defined that thing.


-- 
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] IndentationError:

2011-11-16 Thread Andre Engels
On Wed, Nov 16, 2011 at 9:21 AM, lina  wrote:

> it still complaining. I set the gedit, use space not tab,
> Now I even typed space by space, avoid using tab, it still has the same
> problem.
>
> How can I fixed it?
>

The line

if list1[i][j] != list1[i][j+1]:

still contains a tab, thus it is now indented negative 3 spaces plus a tab
plus 3 spaces compared to the encompassing loop, which is problematic both
because there is a negative number in there and because it differs from the
rest of the lines in the same loop (6 spaces)

-- 
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] making lists of prime numbers

2011-09-14 Thread Andre Engels
On Thu, Sep 15, 2011 at 4:01 AM, c smith wrote:

> hi list, i am trying the MIT opencourseware assignments.
> one was to find the 1000th prime.
> since this isn't actually my homework, I modified the solution as I would
> like to collect lists of primes and non-primes up to N, also some log()
> ratio to one comparison.
> here is what I came up with on paper:
> #!/usr/bin/env python
> import sys, os, math
>
> def main(a):
> notprime = []
> primelist = [2,3]
> nprime = sys.argv[1]
> numcheck = 4
> while len(primelist) < nprime:
> for i in range(2,numcheck-1):
> if numcheck % i == 0:
> print numcheck,'is not prime'
> notprime.append(numcheck)
> numcheck += 1
> break
> if i == numcheck and numcheck % i !=0:
> print numcheck, 'is prime'
> primelist.append(numcheck)
> numcheck += 1
> break
> TwotoN = 0
> for j in primelist:
> TwotoN += log(j)
> print 'sum of logs of primes from 2 to', nprime,'is',TwotoN
> print 'the ratio of this sum to 1 is' %f % (float(TwotoN)/nprime)
> if __name__=='__main__':
> main(sys.argv[1])
>
> my questions would be:
> am I passing arguments from the command line correctly?
> this seems to count by twos (going through both 'if statements' maybe?)
> I thought the 'break' would send control back to the 'while'
> basically, is there an obvious problem here or is it just completely wrong?
>

I'd say the obvious problem is your second if statement. Its guard will
never be true. i goes through range(2,numcheck-1). The highest number in
that range in numcheck-2, so i==numcheck will never be true. Even if you'd
get i to equal numcheck somehow, numcheck % i would then ber equal to
numcheck % numcheck, which equals 0, so numcheck % i != 0 would not be true.

The obvious thing to do seems to be to get this code out of the for loop,
without and if statement guarding it.

Another thing that goes wrong is:

nprime = sys.argv[1]

You use nprime as an integer, but sys.argv[1] is a string. You should thus
change this into

nprime = int(sys.argv[1])

However, for the sake of reusability, it's better to have a function that
gets the first n primes for n decided by the caller than to have a function
that gets the first n primes for n always being the first argument, thus I
would change it to:

nprime = int(a)

-- 
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 quick Q: what does the "collapse" mean?

2011-09-08 Thread Andre Engels
On Thu, Sep 8, 2011 at 4:16 PM, lina  wrote:

> On Thu, Sep 8, 2011 at 9:59 PM, Alan Gauld 
> wrote:
> > On 08/09/11 14:02, lina wrote:
> >>
> >> Hi,
> >>
> >> I failed to understand the "collpase" meaning in a string.
> >>
> >> can someone give me a simple example?
> >
> > Can you give us some context?
> > Its not a method of a string object so far as I can tell?
> > Where did you read about it?
>
> >From "dive into python",
>
> http://diveintopython.org/
>
> one example:
>
> def info(object, spacing=10, collapse=1):
>"""Print methods and docs strings.
>
>Take modules, class, list, dictionary, or strong."""
>methodList = [e for e in dir(object) if callable(getattr(object, e))]
>processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s:
> s)
>print "\n".join(["%s %s" %
>(method.ljust(spacing),
>processFunc(str(getattr(object, method).__doc__)))
>for method in methodList])
>
> if __name__ == "__main__":
>print info.__doc__
>
> I felt so hard to understand the collapse,
>
> Please don't discourage me telling me it's an old book,
> To me I started reading till 42 pages. let me finish it.
>
> I used to study python on and off,
> sometimes give a whole week, but due to not using it,
> so
> it's frustrating that when I really needed it, I barely could complete one.
>

Reading this, it seems that 'collapse' is a variable defined somewhere else
in the code.

-- 
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] Finding the differences between two lists

2011-08-25 Thread Andre Engels
On Thu, Aug 25, 2011 at 9:08 PM, Justin Wendl wrote:

> Hi John,
>
> Thanks for the quick response.  Unfortunately it is returning the same
> result..
>
>
This is caused by the

else:
break

part of the the code. Break breaks out of the loop, thus you skip all
following elements if you go through the 'else' part once. What you probably
meant was:

else:
continue

This skips only the remainder of the current traversion of the loop, and
goes on with the next one.

In this case it's even simpler: There is no remainder of the current run of
the loop to skip, so you should be allright if you remove the else part
altogether.

-- 
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] Syntax error with if statement

2011-08-24 Thread Andre Engels
On Wed, Aug 24, 2011 at 7:40 PM, Ray Parrish  wrote:

> Hello,
>
> I haven't been programming for a while and today I am working on something
> and have encountered an error I cannot figure out.
>
> Here is my code:
>
>  thisFile = column[6]
>  if thisFile == "/Images/My%20Face.JPG"
>   CallCount += 1
>   print CallCount
>
> And here is the error message:
>
> ray@RaysComputer:~$ python /home/ray/EmailCount/**CountEmails.py
>  File "/home/ray/EmailCount/**CountEmails.py", line 41
>if thisFile == "/Images/My%20Face.JPG"
>  ^
> SyntaxError: invalid syntax
>
> Any help you can be will be much appreciated.
>

There has to be a : at the end of an if statement, or more generally, any
statement that is to be followed by an indented block.

-- 
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 have I transgressed??

2011-08-21 Thread Andre Engels
On Sun, Aug 21, 2011 at 7:25 PM, Emile van Sebille  wrote:

> On 8/21/2011 10:08 AM Lisi said...
>
>  I have just received the following.*  In what way have I transgressed?  I
>> apologise to you all - but as I mentioned, I had been stuck for weeks and
>> am
>> running out of time.  And I certainly tried to help myself - I just didn't
>> succeed! Anyhow, if someone will tell me in what way I have transgressed,
>> I'll try harder in future.
>>
>> Thanks,
>> Lisi
>>
>> *Your message for tutor@python.org, the Python programming tutor list,
>> has been received and is being delivered.  This automated response is
>> sent to those of you new to the Tutor list,
>>
>
> The sender's email address is verified and those 'new to the list' get this
> message -- do you have multiple email accounts or possibly typoed in your
> email address on the message that evoked the 'new' response?
>

I have gotten it several times on this address; It seems the reaction is
also given if you send a message after having been absent for a while.

-- 
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] Puzzled again

2011-08-02 Thread Andre Engels
On Wed, Aug 3, 2011 at 8:07 AM, Richard D. Moores wrote:

> On Tue, Aug 2, 2011 at 21:59, Dave Angel  wrote:
>
> > When I paste that from your email into a file and run Python 2.7 on it,
> it
> > behaves fine with no errors.  That's in Linux.
>
> I should have said that I'm using Wing IDE Professional 4.0.3-1 (rev
> 24721), Windows Vista, and Python 3.2.1.
>
> > But the easiest explanation is that you perhaps used a funny character
> for
> > your triple-quotes.  And when you retyped them on a new line, you typed
> > regular ones.
> >
> > For example, I've seen that sort of thing when someone wrote code in a
> > Windows word processor that had "smart quotes."
>
> No, no funny characters with Wing.
>
> Thanks for your guess, Dave.
>
> But here's a try using the regular command line:
>
> C:\Windows\System32>python
> Python 3.2.1 (default, Jul 10 2011, 20:02:51) [MSC v.1500 64 bit
> (AMD64)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> from mycalc import convertPath
> Traceback (most recent call last):
>   File "", line 1, in 
>  File "C:\Python32\lib\site-packages\mycalc.py", line 36
>"""
> SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes
> in position 149-151: truncated \UXXX
> X escape
> >>>
>

That says that there is some character in that line that is not valid
Unicode. Remove the line (and perhaps the ones above and below it at the
same time, in case it's around the line feed character(s)) and type it in
again. It's likely to be as easy as that.

-- 
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] List problem

2011-07-24 Thread Andre Engels
On Mon, Jul 25, 2011 at 4:19 AM, David Merrick  wrote:


> def append(self,item):
>  '''Adds an item to the end of the List'''
>
>  current = self.head
>  previous = None
>  while current.getNext() != None:
>  previous = current
>  current = current.getNext()
>  if current.getNext() == None:
>  previous  = previous.setNext(current)
>  current = current.setNext(item)
>

current is here the first element of your list. This element does not have a
getNext() method. Instead, if you want to use this system, you'll have to
use a (probably re-defined) getNext() method of your list class itself.

-- 
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] NameError: is defined

2011-07-19 Thread Andre Engels
On Wed, Jul 20, 2011 at 4:37 AM, brandon w  wrote:

> **
> Hi
> I am running Linux with Python 2.6.6. I have done lists, tuples,
> dictionaries, etc. Now I want to move on to creating a "class". I keep
> getting an error for everything I try. Here is the error: *
>
> NameError: name 'MyClass' is not defined*
>
> I had originally tried to create my own class by watching some video
> tutorials. Nothing worked. Then from the python2.6-doc documentation I just
> decided to copy and paste from the documentation.
>
>  *class MyClass:
> """A simple example class"""
> i = 12345
> def f(self):
> return 'hello world'*
>
>
> *>>> MyClass
> Traceback (most recent call last):
>   File "", line 1, in 
> NameError: name 'MyClass' is not defined*
>
> Still the same error. What am I doing wrong?
> I tried this in gnome-terminal in a Python shell and using IDLE.
>
> First I do: *import myscript.py
> *(no errors)*
> *
> Then I run: *MyClass*
> (error)
>
> I try:  n = *MyClass()*
> (error)
>
> I try:
> *MyClass.n
> n.MyClass
> i.MyClass
> MyClass.i
> i.MyClass()
> f.MyClass
> f.MyClass()*
>
> (nothing but errors)
>

You have to specify where MyClass lives. In this case it's in myscript.py.
So you have to do:

import myscript#Note: without .py
n = myscript.MyClass()

or:

from myscript import MyClass
n = MyClass()

-- 
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] getting error while solving a series that estimates the value of pi

2011-07-18 Thread Andre Engels
On Mon, Jul 18, 2011 at 6:10 PM, surya k  wrote:

> Hi,
>
> The problem is to estimate the value of pi using the following series.
>  *1 / pi  = (( 2 * sqrt(2) )/ 9801 )  * SIGMA of k[ (4k)! (1103 + 26390*k)
> / (k!^ 4 ) * 396^(4k)  ]*
> *where k is [0, infinity)*
> * Problem is located at : ThinkPython Book, www.thinkpython.org
>*Pg 89, Exercise 7.5, Think Python Book. *
> *
> *
> the series should be considered till the last term of the sigma must be <
> 1e-15
> I have written the below code :
>
> *# program estimates the value of pi*
> *# Ramanujan's series... *
> *import math*
> *
> *
> *def fact(n) : # def of factorial function.*
> *if n > 0 :*
> *   return n * fact(n-1)*
> *if n == 0 :*
> *   return 1*
> *
> *
> *k = 0*
> *tot = 0*
> *temp1 = 0*
> *while k >= 0 and temp1 == 0 :*
> *
> *
> *  a = ( 2 * math.sqrt(2) ) / 9801 # first term before sigma *
> *  nu = fact (4*k) * (1103 + (26390*k) )  # numerator of series*
> *  de = pow( fact(k), 4 ) * pow ( 396, 4*k )  # denominator of series*
> *  *
> *  if de / nu > 1e-15 : *
> *temp = nu / de*
> *tot = tot + temp*
> *temp1 = 0 *
> *k = k + 1 *
> *  elif de / nu  == 1e-15 :*
> * series = a * tot  *
> * k = k + 1*
> * temp1 = 0*
> *  elif de / nu < 1e-15 :*
> * print series*
> * temp1 = 1*
>
>
> I am getting the following error : which is completely surprising!
>
> *Traceback (most recent call last):*
> *  File "pi.py", line 30, in *
> *print series*
> *NameError: name 'series' is not defined*
>
> *
> *
> Thus I have removed name 'series' and replaced with  *a*tot, *
> now I am getting this error
>
> *Traceback (most recent call last):*
> *  File "pi.py", line 30, in *
> *print 1 / (a * tot)*
> *ZeroDivisionError: float divisio*n
>
>
>
> Thus I changed the first highlighted lines to
>
>  *nu = float (fact (4*k) * (1103 + (26390*k) ) )*
> *  de = float (pow( fact(k), 4 ) * pow ( 396, 4*k )) *
>
>
> now I am getting
>
> * Traceback (most recent call last):*
> *  File "pi.py", line 18, in *
> *de = float (pow( fact(k), 4 ) * pow ( 396, 4*k ) )*
> *OverflowError: long int too large to convert to float*
>
> *help me out of this problem, how could I fix this*
>
>
You have the definitions of numerator and denominator switched.

-- 
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] Blackjack Betting

2011-07-01 Thread Andre Engels
On Fri, Jul 1, 2011 at 9:29 AM, Vincent Balmori wrote:

>
> Here is the other one that occurs when I lose
>
> Traceback (most recent call last):
>  File
>
> "/Users/vincentbalmori/Desktop/Python/py3e_source/chapter09/blackjackbetting.py",
> line 240, in 
>main()
>  File
>
> "/Users/vincentbalmori/Desktop/Python/py3e_source/chapter09/blackjackbetting.py",
> line 236, in main
>game.play()
>  File
>
> "/Users/vincentbalmori/Desktop/Python/py3e_source/chapter09/blackjackbetting.py",
> line 211, in play
>player.lose()
>   File
>
> "/Users/vincentbalmori/Desktop/Python/py3e_source/chapter09/blackjackbetting.py",
> line 124, in lose
>bet.stash -= bet.wager
> NameError: global name 'bet' is not defined
>

That error message is really quite expressive, it would much more help you
to learn to read it yourself than to run to us every time something goes
wrong. The most interesting part of an error message are its last few lines,
they say what went wrong, and where it happened. The rest tells you how it
got there, which also is important to know sometimes, but many errors can
already be solved without looking at it.

In this case, the error message says:

NameError: global name 'bet' is not defined

That means, at some time at the program, it is told to do something with
'bet', but there is no variable bet. And when does that happen? That too is
told: at line 124, which says:

bet.stash -= bet.wager

Go to that line and read your code yourself - what is this 'bet' of which
the stash is to be lessened by its wager? Have you told your program that
this is the value of the variable 'bet'? Where and how?

-- 
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] Trivia

2011-06-24 Thread Andre Engels
On Fri, Jun 24, 2011 at 8:56 AM, Vincent Balmori
wrote:

>
> <<
> point = int(next_line(the_file))
>
> If x is a string that can be interpreted as an integer number, int(x) is
> that integer number; if the string is not the representation of an integer,
> this will lead to a ValueError.
>
> --
> André Engels, andreeng...@gmail.com>>>
>
>
> It's working fine now with the scoring, but now at the end of the program
> for some reason I get this error message:
>
> Traceback (most recent call last):
>  File
>
> "/Users/vincentbalmori/Desktop/Python/py3e_source/chapter07/trivia_challenge2.py",
> line 83, in 
>main()
>  File
>
> "/Users/vincentbalmori/Desktop/Python/py3e_source/chapter07/trivia_challenge2.py",
> line 76, in main
>category, point, question, answers, correct, explanation =
> next_block(trivia_file)
>  File
>
> "/Users/vincentbalmori/Desktop/Python/py3e_source/chapter07/trivia_challenge2.py",
> line 27, in next_block
> point = int(next_line(the_file))
> ValueError: invalid literal for int() with base 10: ''
>
>
The important thing in such a case is reading the error message and the last
line in the error trace. In this case the error message is:

ValueError: invalid literal for int() with base 10: ''

This means that the int() function is being called with something that is
not an integer - it even says what that something is, namely '' - that is,
the empty string. Apparently at some time you come to the line

point = int(next_line(the_file))

when next_line(the_file) is the empty string.

-- 
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] Using class methods

2011-06-21 Thread Andre Engels
On Tue, Jun 21, 2011 at 10:12 AM, David Merrick  wrote:
> I need help using Class methods in another class. I have a class called
> Critter and I want to create two critters in a farm  Class Farm and use
> Class Critter's methods

Could you please specify where your current code does not suffice -
where does it something different than you want, or where do you want
to do something (and why) that you don't know how to do?

-- 
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] Step Value

2011-06-17 Thread Andre Engels
On Fri, Jun 17, 2011 at 11:03 PM, Alan Gauld  wrote:
>
> "Vincent Balmori"  wrote
>
>> Here is my updated code. As simple as this may be, I am a little lost
>> again.
>
> I'm not sure why you are lost because that's pretty much it.
>
>> ... at this point (especially after one week) this is when me being
>> given the answer with an explanation will help me much more, so I can
>> understand how it works better.
>
> The answer is:
>
>> def ask_number(question, low, high, step = 1):
>>   """Ask for a number within a range."""
>>   response = None
>>   while response not in range(low, high, step):
>>       response = int(input(question))
>>   return response
>
> With the only comment being that you don't really need the
> response=None line because response always gets set
> inside the loop.

But the value of response is used in starting the loop (it is needed
to test whether the loop should be gone through a first time), so one
_does_ need that line.


-- 
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 statement

2011-06-07 Thread Andre Engels
On Tue, Jun 7, 2011 at 11:26 PM, Matthew Brunt  wrote:
> i'm very new to python (currently going through a python for beginners
> book at work to pass the time), and i'm having trouble with an if
> statement exercise.  basically, i'm creating a very simple password
> program that displays "Access Granted" if the if statement is true.
> the problem i'm having is that no matter what i set the password to,
> it seems like it's ignoring the if statement (and failing to print
> "Access Granted").  the code is copied below.  i'm pretty sure it's my
> own programming ignorance, but i would greatly appreciate any
> feedback.

Actually, no, this case it's not your ignorance. What is probably
going on is that you are using Python 2, but the book is going with
Python 3. I won't get into the details, but the function that does
what input() does in Python 3, is called raw_input() in Python 2 (and
the Python 2 input() function is advised against using for security
reasons). Probably if you change input to raw_input in your program,
it does do what you want it to do.

> # Granted or Denied
> # Demonstrates an else clause
>
> print("Welcome to System Security Inc.")
> print("-- where security is our middle name\n")
>
> password = input("Enter your password: ")
>
> if password == "a":
>   print("Access Granted")
>
> input("\n\nPress the enter key to exit.")
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
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] Python Variables Changing in Other Functions

2011-05-24 Thread Andre Engels
On Wed, May 25, 2011 at 6:14 AM, Rachel-Mikel ArceJaeger
 wrote:

> I am having trouble with determining when python is passing by reference and 
> by value and how to fix it to do what I want:
>
> I am writing a program that will take in a list of book titles and will allow 
> many people to rank them in terms of popularity and will export the results 
> to Excel. I'll include the whole code below, but the function I'm having 
> trouble with is rankRandom(). I want it to take in a list of titles, 
> randomize the list (so that I can be certain the order isn't influencing the 
> results of the rankings), get a person's rankings, and then resort the order 
> of the rankings to match the original order of title list (that way I can 
> match up different people's rankings to the correct title).
>
> The issue is this: random.shuffle() mutates the list in place, rather than 
> creating a new copy. This is fine, but rather than modifying just the local 
> copy of my titles, it is modifying it in the other functions, too. For 
> instance, rankRandom() is called by main(), which passes it listOfTitles. 
> When rankRandom() returns, listOfTitles has been changed to the randomized 
> version of titles.
>
> To fix this, I tried copying the original title list and then assigning it to 
> the mutated version right before the rankRandom() function returns. The local 
> version of titles in rankRandom() does indeed regain its original value, but 
> listOfTitles in main() is still being assigned to the randomized version, and 
> not to the original version. This boggles me, since it seems like shuffle is 
> mutating the titles as if it were a global variable, but assignment is 
> treating it only as a local.
>
> What exactly is going on here, and how do I avoid this problem?

You should not think of 'pass by reference' or 'pass by value'. That's
how things work in the C world. In Python, the data model is that
variables are a name for an object. What you are providing when
calling an argument with a function is not the variable itself, be it
by reference or by value, but the object that the variable refers to.

Thus, in your code, when calling rank_random(), "title" becomes
(within the function) a name of the object that also has the name
listOfTitles in main(). This object is then changed by
random.shuffle(). The assignment

titles = origTitles

gives the object referred to by origTitles a new name, 'titles'. This
does _not_ change the object that originally had the name titles,
which thus still has the shuffled value.

As for how to do what you wanted to do, do make a copy like you do,
but then _do the shuffling on the copy_. You could also change the
call to the function to have a copy rather than the original variable
as its argument, but that solution is not as useful for re-use of the
function.

Oh, and one more remark: copying a list objects is often done using

objects[:]

rather than

copy.copy(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] Data conversion

2011-05-19 Thread Andre Engels
On Thu, May 19, 2011 at 8:15 AM, Joe Aquilina  wrote:

> I realised after I read your response that I probably hadn't included enough
> information, partly due to my  inexperience in Python and partly due to
> haste on my part.
>
> AFter my original post, I had a little play in Python and was able to create
> this tuple:
>
> [1, 2, 3, 4, 5]
>
> from which I was able to extract any item I wanted as an integer and work
> with as I wanted. I am guessing that this is a 1-tuple.

No, this is an array. However, an array and a tuple work similarly in
many cases. A 1-tuple is a tuple with one element, so this is
definitely not a 1-tuple.

> It is when I do the fetchall() from the table, that I get the following:
>
> [(1,), (2,), (3,)]
>
> I don't know enough to know whether this is a 1-tuple or not. It is from
> this tuple that I want to extract the 3 as an integer so that I can
> increment it and save as an integer into the next row in the table.

This again is an array, but this time the elements are tuples (indeed
1-tuples). To show you how to get the value 3 from this:

>>> A = [(1,), (2,), (3,)]
>>> A[2]
(3,)
>>> A[-1]
(3,)
>>> B = A[-1]
>>> B
(3,)
>>> B[0]
3
>>> A[-1][0]
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] Data conversion

2011-05-18 Thread Andre Engels
On Thu, May 19, 2011 at 6:36 AM, Joe Aquilina  wrote:

> I am new to this list and very much a beginner to Python. Please excuse me
> if this is a silly question, but in all my searches this morning I have not
> been able to find an answer.
>
> I have a (single table) database file (SQLite3). It has one table, call it
> literature, with an integer, autoincrement primary key field. I have created
> a data entry form in Python that I want to use to enter new rows into this
> database file. On the data entry form I will enter the values for a new
> table row - all except the primary key field.
>
> What I want to be able to do is to have my data entry form autoincrement
> this primary key field for me, with no ability to change the contents on the
> data entry form, and save this incremented value as the value of the num
> field when I save the new row.
>
> So for example, if the last row in the table has a value of 256 in the num
> field, I want the value of 257 to be saved as the value of the num field
> into the new row I am adding, without having to see or or enter this new
> value (or indeed the previous value) on the data entry screen.
>
> I hope this makes sense. But how do I do this?
>
> I thought about doing a
>
> SELECT num FROM literature;
>
> from the table, then getting the contents of the num field of the last row
> in the data that a fetchall() retrieves and incrementing it to save with the
> new row.
>
> However, the fetchall() returns the data as tuples, not integers and I don't
> know how to convert from a tuple data type to an integer to make this work.
>
> Is this possible? Or can I achieve my objective in some other way?
>
> Any advice/assistance would be appreciated. Thanks in advance.

l assume the tuple is a 1-tuple?

Anyway, let fetch be the name of your tuple, then

fetch[0]

will be the first element of the tuple,

fetch[1]

the second element, and so on.


-- 
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] Please help, the program is not behaving as I want

2011-05-17 Thread Andre Engels
I am not able to check your code (I get an error message about the
usage of urllib, but that might be a difference in Python
installations); however, my first guess is that you neglected to take
case into account: The page contains the text "Water", not "water", so
if you input "water", halal_haram_status will be -1.

As another remark, find() will give the value of the _beginning_ of
the match, thus when all goes right, what is returned will contain
part of the text sought rather than "Halal" or "Haram" - you will get
"er Ha" for water, "anol " for ethanol and "k cho" for pork chops
(also, ethanol is the same as alcohol, so I guess it should be haram).

On Tue, May 17, 2011 at 5:20 PM, I. Dooba  wrote:
> I'm new to programming and have decided to start with Python following the
> advice of experts including Eric S. Raymond.
> So far I've learnt quite a lot from this list.
> However, I've the following problem.
> The program was designed (as part of my practice with Head First
> Programming) to check whether an ingredient is Halal or Haram.
> I've a simple table online where some ingredients are either halal or
>  haram.
> For example, if the user enters "water" the program is supposed to tell him
> that it's halal;
> but it's returning ">" and other characters I don't want to see.
> What am I doing wrong?
> import urllib.request
> page =
> urllib.request.urlopen("http://halalingredients.theparleyonline.com/";)
> text = page.read().decode("utf8")
>
> halal_haram_status = text.find(input("Enter the ingredient:  "))
> begin_final_status = halal_haram_status + 3
> end_final_status = begin_final_status + 5
> status = text[begin_final_status:end_final_status]
> print(status)
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>



-- 
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 read two files and substitute

2011-05-17 Thread Andre Engels
First read file1, and keep the result in a useful data structure (for
this simple case it can be nothing more than a dictionary with the
value in column 1 as key and the value in column 4 as value, but
perhaps it's better to find something else if you want to do more with
the data). Then go through file2, check your data structure for every
value, and ready.

André

On Tue, May 17, 2011 at 3:42 PM, lina  wrote:
> Hi,
>
> For file1:
>
>  5007  O28 CHO   173      35.300  99.430  65.810  1.00  0.0
>  5008  H29 CHO   173      35.680 100.290  66.150  1.00  0.00
>  5009  C1  CHO   174      59.060  12.440  58.680  1.00  0.00
>  5010  C2  CHO   174      59.460  12.480  60.160  1.00  0.00
>  5011  C3  CHO   174      59.590  11.120  60.830  1.00  0.00
>  5012  C4  CHO   174      60.780  10.430  60.160  1.00  0.00
>
> For file2:
>
> 5008 5010 5011
>
> I want to get the $4(column 4) value which has  the $1 value. for
> values in file2
>
> such as the results is 173 174 174
>
> Thanks for any suggestions,
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
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] Python Hard_way 40

2011-05-11 Thread Andre Engels
On Wed, May 11, 2011 at 5:24 PM, Robert .  wrote:
> Hi all,
>
> My first post ever! :)
> I'm following the guide "Learn Python the Hard Way" and have reached a point
> where I am struggling to understand the code and unfortunately the authors
> guide hasn't cleared it up for me. (excercise 40 for reference)
>
> The main confusion is coming from 'cities['_find'] = find_city' I'm not sure
> what this is really doing.
>
> From my learning, this should add an extra item to the dict with the index
> name of "_find" and the value which is returned from "find_city" function.

No, that would be
cities['_find'] = find_city()

When you use
cities['_find'] = find_city

the value of the extra item is _the function find_city itself_.

And thus later
city_found = cities['_find'](cities,state)

will be equivalent to
city_found = find_city(cities,state)

-- 
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] assigning a variable a value

2011-05-05 Thread Andre Engels
On Thu, May 5, 2011 at 2:19 AM, Kyle Benak  wrote:

> I am learning python and I am trying to write a simple "guess the number"
> game. I wrote the program in the IDLE, and I set the variable tries=1 to
> keep up with the number of tries it takes to guess the number, but when I
> try to run the program it gives the error message "improper syntax" and
> highlights the word tries.  So, I assigned the variable tries the value 1 in
> the python shell window and it works fine there.  Can you tell me why it
> won't work in the program? A copy of my code is below for clarification.

If the parser tells you there's a syntax error, it is often in the
line it shows, but also often in the line preceding that. In this
case, it is the latter: You have two opening brackets there, but only
one closing bracket.

-- 
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] triple-nested for loop not working

2011-05-05 Thread Andre Engels
I have not checked the rest of your code, but:

> for line in seqalign:
>     for i in len(finalmotif_seqs):      # for item in finalmotif_seqs:
>         for i in len(finalmotif_annot):     # for item in finalmotif_annot:

I see two problems here:
1. You are using the same loop variable in both loops here. That's
likely to cause problems
2. You let the loops go over len(finalmotif_seqs).
len(finalmotif_seqs) is a number, and you can't loop over a number.
You should use the form as you write after the #.

-- 
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] Combining two Dictionaries

2011-04-30 Thread Andre Engels
On Sun, May 1, 2011 at 5:49 AM, Ryan Strunk  wrote:

> When I initialize the class which holds these dictionaries, though, I need
> to make sure that all the keys contained in d2 match the keys of d1. Thus I
> tried:
> d1 = {'a': 0, 'b': 0, 'c': 0}
> d2 = d1
> My understanding was that d2 looked at d1 once, grabbed its keys and values,
> and went off to do its own thing.  Just as if you typed:
> x = 3
> y = x
> x = 6
> y still holds the value 3.
> This turns out not to be the case with dictionaries, and I'm not sure why
> this is so. Why when you change a dictionary's keys in place does a copied
> dictionary take on the new values?
> Thanks for any help you can provide.

To answer your question, we have to look at Python's data model, which
differs from that in other languages. What

y = x

does, is to calculate the object x and give it the name y, apart from
whatever names it may or may not have already. Thus, it does _not_
make a copy, but x and y are two different names of the _same_ object.
What happens in your example, is that you give the object 3 the name
x, then give the object 3 (the outcome of the 'calculation' x) the
name y, then give the object 6 the name x. After that y is still a
name for 3. But if you're working with dictionaries, you're probably
doing something like this:

d1 = {'a': 0, 'b': 0, 'c': 0}  # You create a dictionary and give it the name d1
d2 = d1 # You give _the same_ dictionary the name d2
d1['c'] = 1 # You _change_ the dictionary by changing its value for
the key c. d1 and d2 still are names for the _same_ dictionary

Just like in the integer situation, d2 is still a name for the same
object as it was before, but this time _the object itself has
changed_. And d2 'sees' the change of the object.


-- 
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 Dictionary question

2011-04-11 Thread Andre Engels
On Mon, Apr 11, 2011 at 1:01 PM, Sophie DeNofrio wrote:

> Hi Everyone,
>
> I am a super beginner and am little muddled right now. So I apologize for
> the low level question but I am trying to write a function that will return
> a dictionary of a given list of strings containing two coordinates separated
> by a space with the first numbers as a key and the second numbers as its
> corresponding value. I thought maybe a set might be helpful but that didn't
> seem to work at all. I am pretty much as confused as they come and any help
> would be very much appreciated. Thank you so much for your time.
>

def createDictionary(data):
result = {}
for datapiece in data:
# Code here to make coordinate1 and coordinate2 the values you want
# Leaving that part to you, but feel free to ask again if you fail
result[coordinate1] = coordinate2
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] Help needed

2011-04-08 Thread Andre Engels
On Fri, Apr 8, 2011 at 3:57 AM, Aaron Brown  wrote:
> I am in an online python class and am failing badly.  I am not sure where
> the problem is here but any insight would be great.
>
> def main():
>     while (True):
>     allowed = int(input("Please enter minutes allowed between 100 and
> 700: "))
>     used = int(input("How many minutes were used: "))
>     totalOver = used - allowed
>     totalDue = (64.95 + (0.15*totalOver))
>     if(totalOver > 0):
>     print("You were over your minutes by " + str(totalOver))
>     else:
>     totalOver = 0
>     print("You were not over your minutes for the month")
>     print ("Do you want to end program? Enter yes or no:")
>     toEnd = raw_input()
>     if toEnd == "yes":
>     print("MONTHLY USE REPORT")
>     print("Minutes allowed were " + str(allowed))
>     print("Minutes used were " + str(used))
>     print("Minutes over were " + str(totalOver))
>     print("Total due is $ " + str(totalDue(totalOver))
>
> I keep getting a syntax error in a blank line at the bottom.  I have tried
> to end it with main() but it errors on the main as well?

If you get a syntax error, the problem almost always is in the line
shown or the line directly above it. A blank line at the end is not a
syntax error, so in this case it is the line above it:

print("Total due is $ " + str(totalDue(totalOver))

This line has three left brackets but only two right brackets. Add one
right bracket and your program should run (however, it will not work
correctly - in the above line you try to call totalDue, but it is a
number, not a function or method).

-- 
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] (sqlite3) Testing if a table has been created.

2011-04-06 Thread Andre Engels
On Wed, Apr 6, 2011 at 4:06 PM, michael scott  wrote:

>  Is this really a python tutor question?  Oh, well, try this:
> http://lmgtfy.com/?q=sqlite+test+if+table+exists
>
> --
> Joel Goldstick
>
>
> My apologies, I was not aware that there were questions I could and could
> not ask. I understand now that this is an unnacceptible question. But could
> you tell me why? Was it too simple in nature? Too difficult? Did I violate
> some rule in my question formatting?  This was not homework or anything like
> that. I went back to the tutor website to make sure I did not blatantly
> break one of the rules. I only found this regarding participation.
>


I think Joel's objection is that your question is not really about Python at
all, but about SQLite,

-- 
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] Passing a Variable

2011-04-04 Thread Andre Engels
On Mon, Apr 4, 2011 at 7:27 AM, Ryan Strunk  wrote:
>> I've read your code. Frankly I don't understand your problem. I also don't
> see any occurrence of "health".
> There isn't a reference to health here. My goal is to have this code act as
> a checker for health, fatigue, time_remaining, or any other sort of
> statistic you'd like to throw into it. My problem is that when I try:
> instance = Statistic(stat=health, sound=spam, low=1, mid=15, high=30)
> health can change elsewhere in the program, but the instance of statistic
> class won't automatically see it.

My proposal would be to wrap the stats in an object:

Class stat:
 __init__(self, name, value)
 self.type = name
 self.value = value

Then in the player object change the initialisation

health = startvalue

to

health = stat("health", startvalue)

and change every other reference to health to a reference to health.value.

Then you can use the current code if you replace self.stat outside the
__init__ by self.stat.value

You could even consider merging the stats and Statistics classes.

==

Another possibility would be to use a getter method and the fact that
methods are objects:

In the player object add:

def get_health(self):
return self.health

change the call to:

instance = Statistic(stat=get_health, sound=spam, low=1, mid=15, high=30)

and replace self.stat by self.stat() everywhere in the Statistics code

-- 
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] Removing values from a dictionary if they are present in a list

2011-04-01 Thread Andre Engels
On Fri, Apr 1, 2011 at 9:52 AM, ranjan das  wrote:
> I have the following information
>
> A={'g2': [4,5,3], 'g1': [1, 3]}
>
> B=[2,3,5]
>
> Now I want to remeove the elements in B if they are present (as values) in
> dictionary A.
>
> My expected solution is
>
> A= {'g2': [4], 'g1': [1] }
>
> I wrote the following piece of code which gives me thhe right code, but I am
> sure there must be a much shorter and more elegant way of doing it. Please
> suggest
>
> reject_list=[]
>
> for element in B:
>
>     for key in A.keys():
>
>     for i in range(len(A[key])):
>
>     if element==A[key][i]:
>
>     reject_list.append((key,A[key][i]))
>
>
>
> print reject_list
>
>
> for i in range(len(reject_list)):
>
>     print (reject_list[i][0],reject_list[i][1])
>
>     Index=A[reject_list[i][0]].index(reject_list[i][1])
>
>     print (reject_list[i][0],reject_list[i][1],Index)
>
>     del A[reject_list[i][0]][Index]


First, your loops are distinctly unpythonic. In many other languages
one does indeed go over a list or similar object by having a numeric
loop variable i, and then using list[i], but in Python we loop over
the list itself instead. Applying that to your code, and removing the
in-between prints, we get:


reject_list=[]

for element in B:
for key in A.keys():
for Aelement in A[key]:
if element == Aelement:
reject_list.append(key, Aelement)

for deleteelement in reject_list:
index = A[deletelement[0]].index(deleteelement[1])
del A[deleteelement[0]][index]


Next, realize that we are comparing each element in B with each
element in A, and then add information only on the element of A to the
list. Also, there is no need to add something twice if it occurs twice
in B. Thus, we can simplify this by just checking for each element of
A whether it is in B:


reject_list = []

for key in A.keys():
for element in A[key]:
if element in B:
reject_list.append(key, element)

for deleteelement in reject_list:
index = A[deletelement[0]].index(deleteelement[1])
del A[deleteelement[0]][index]


However, when working this way, we will have all elements from one key
in A together. We could also work with a separate list for each key,
and do those in turns:


for key in A.keys():
reject_list = []
for element in A[key]:
if element in B:
 reject_list.append(element)
for element in reject_list:
index = A[key].index(element)
del A[key][index]


Still, we can go further. Why first create a list of things to do and
then do it? We can do it immediately; however, then we have to change
the loop variable, because things go wrong if you remove elements from
a list while looping over that same list.


for key in A.keys():
copy = A[key][:]
for element in copy:
 if element in B:
  index = A[key].index(element)
  del A[key][index]


A further small shortening is done by realizing that the default way
of looping over a dictionary is to loop over its keys:


for key in A:
copy = A[key][:]
for element in copy:
 if element in B:
  index = A[key].index(element)
  del A[key][index]


A following step is to see that we only use the keys to get to the
values. Why not use the values directly?

for value in A.values():
copy = value[:]
for element in copy:
 if element in B:
  index = value.index(element)
  del value[index]



Can this still be shortened? Definitely. However, for the most obvious
shortening I have to make an assumption, namely that the values in A
are _not_ used elsewhere. Upto now we have removed elements from those
values; we now will replace the value instead. This means that in

Z = [0, 1]
A = {"Hello": Z, "Goodbye: [0,2]}
B = [0]
# The previous code

Z will have changed to [1]

whereas in

Z = [0, 1]
A = {"Hello": Z, "Goodbye: [0,2]}
B = [0]
# The upcoming code

Z will have remained [0,1]

With this proviso, we have:


for key in A:
newvalue = []
for element in A[key]:
 if element not in B:
  newvalue.append(element)
A[key] = newvalue


This on itself is not shorter than the previous forms, but it can be
used in a list expression like this:

for key in A:
 A[key] = [element for element in A[key] if element not in B]


-- 
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] Recursively flatten the list

2011-03-24 Thread Andre Engels
2011/3/24 Rafael Durán Castañeda :
> I can do it with two list comprehensions:
>
 list_ = [1, 2, [3, 4], 5, [6, 7, 8], 9]
 [x[i] for x in list_ if isinstance(x, list) for i in range(len(x))] + [x
 for x in list_ if not isinstance(x, list)]
> [3, 4, 6, 7, 8, 1, 2, 5, 9]

>
> But i loose original order, Can anyone do it with just one list
> comprehension and/or keeping the order?

A more important problem is that it is flattening only one level.
Multi-level flattening is I think not possible without using some kind
of recursion.


-- 
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] what is it mean--- File "", line 1

2011-03-20 Thread Andre Engels
On Mon, Mar 21, 2011 at 1:58 AM, sihong lin  wrote:

> Hi,
>
>  I just write a simplest file test.py with only one line--print "hello",
> when I run it in command line:
> >>> python test.py
>
> the follow message comes out:
>
> File "" , line 1
>  python test
>
> SyntaxError: invalid syntax
>
> but, the file can run in shell, also in the command line, I put
>
> >>> print "hello"
>
> output is fine, "Hello"
>

In the shell you can run shell commands, in the Python command line you can
run Python code. "python test.py" is a shell command, not Python code, so
you can run it in the shell, but not on the Python command line. "print
"hello"" is Python code, so you can run it on the Python command line, but
not in the shell.


-- 
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] Efficiency of while versus (x)range

2011-03-17 Thread Andre Engels
On Thu, Mar 17, 2011 at 8:45 AM, Stefan Behnel  wrote:

> Note that a web application involves many things outside of your own code
> that seriously impact the performance and/or resource requirements. Database
> access can be slow, excessively dynamic page generation and template engines
> can become a bottleneck, badly configured caching can eat your RAM and slow
> down your response times.

Yes, that has been my experience too back when I did web applications
in Python. I had several cases where the page took too long to load;
in all but one cases the issue was resolved by getting a database
access out of a loop, thus changing many database accesses into one.
The remaining case was also resolved in the area of database access,
this time by checking whether a particular database result was one
that we needed in the database request instead of afterward in Python.

> You shouldn't be. Optimising at that level is clearly the wrong place to
> start with.

The three rules of optimisation in Python:
1. Only optimise if your system is actually too slow
2. Only optimise the thing that is actually causing the slowness
3. If you are of the opinion that should break one of these rules, you
are using the wrong language.

> Optimisation is
> something that you should start to apply when your test suite is large
> enough to catch the bugs you introduce by doing it.

That's a quote to remember :-)


-- 
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] Static Variable in Functions

2011-03-14 Thread Andre Engels
On Mon, Mar 14, 2011 at 9:56 AM, Alan Gauld  wrote:
> "Yasar Arabaci"  wrote
>
>> >>> a=["a"]
>> >>> b=[a]
>> >>> a.append("c")
>> >>> b
>> [['a', 'c']]
>>
>> Apperantly, I can change something (which is mutable) inside  a list
>> without even touching the list itself :)
>
> But the point is that you *are* touching the list.
> In this case you have two names referring to the same list.
> You can modify that list (because it is mutable) via either name, it
> makes no difference because they both refer to the same list.
>
> So a.append() is exactly the same operation as b.append()

No, they are not the same list. b is (a name of) a list with one
element, that one element being the list (denoted by) a. That's not
the same as a itself.

-- 
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 help with dates in Python

2011-03-09 Thread Andre Engels
On Wed, Mar 9, 2011 at 9:21 AM, nookasree ponamala  wrote:
> Hi,
>
> I need help in finding the minimum date and maximum date in a file.
> Here is my test file:
> s.no:   dt1     amt     id1     id2
> 452     2010-02-20      $23.26      059542        06107
> 452     2010-02-05      $20.78      059542        06107
> 451     2010-02-24      $5.99       059542        20151
> 452     2010-02-12      $114.25     839745        98101
> 452     2010-02-06      $28.00      839745        06032
> 451     2010-02-12      $57.00      839745        06269
>
> I want to get the minimum and maximum dt1 for each id1
>
> Required result:
>
> id1 mindate maxdate
> 059542  2010-02-24      2010-02-20
> 839745  2010-02-06      2010-02-12
>
> Code: The code I tried. It doesn't work though.
>
> import sys
> import os
> t = ()
> tot = []
> maxyr = 2012
> minyr = 2008
> maxday = 31
> minday = 1
> maxmon = 12
> minmon = 1
>
> for line in open ('test2.txt','r'):
>        data = line.rstrip().split()
>        a = data[3]
>        b = data[1]
>        (year, month, day) = b.split('-')
>        year = int(year)
>        month = int(month)
>        day = int(day)
> if year > maxyr:
>        maxyr = year
> elif year < minyr:
>        minyr = year
> if month > maxmon:
>        maxmon = month
>        elif month < minmon:
>        minmon = month
>        if day > maxday:
>        maxday = day
>        elif day < minday:
>        minday = day
>        max = (maxyr,maxmon,maxday)
>        min = (minyr,minmon,minday)
>        t = (a,b,max,min)
>        tot.append(t)
>        print t
>
> Could you pls. help me with this.

I see several things go wrong. Here a list, which may well not be complete:

* You want the mindate and maxdate for each id1, but you remember only
a single minyr, maxyr etcetera. There's no way that that is going to
work.
* You initialize minyr etcetera to a date before the first date you
will see, nd maxyr etcetera to a date after the last date. This means
that you will never find an earlier respectively later one, so they
would never be changed. You should do it exactly the other way around
- minyr etcetera should be _later_ than any date that may occur, maxyr
etcetera _earlier_.
* You move "if year > maxyr" back to the left. This means that it is
not part of the loop, but is executed (only) once _after_ the loop has
been gone through
* year < minyear should be "if", not "elif": it is possible that the
new date is both the first _and_ the last date that has been found
(this will be the case with the first date)
* You change maxyear, maxmonth and maxday independently. That is not
what you are trying to do - you want the last date, not the highest
year, highest month and highest day (if the dates were 2001-12-01,
2011-11-03 and 2005-05-30, you want the maximum date to be 2011-11-03,
not 2011-12-30). You should thus find a way to compare the *complete
date* and then if it is later than the maxdate or earlier than the
mindate change the *complete date*
* At the end you show (well, in this case you don't because it is
under "if month > maxmon") a quadruple consisting of id1, current
date, lowest date and highest date - EACH time. You want only the
triple and only after the last date of some value of id1 has been
parsed (best to do that after all lines have been parsed)
* The code as shown will lead to a syntax error anyway because you did
not indent extra after "elif month < minmon:", "if day > maxday:" and
"elif day < minday:".




-- 
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] Does try-except "lock out scope" or similar?

2011-03-07 Thread Andre Engels
On Tue, Mar 8, 2011 at 5:40 AM, Benjamin Serrato
 wrote:
> I wrote a short script to clean up a csv file but had trouble when
> date_time = time.strptime(date_string, "%m/%d/%y")
>  would choke on intermittent Null characters in the file.  I put it into a
> try-except, but then I found I couldn't do
> del row
> because I receive a "row is not defined" complaint or similar.  So, how do I
> run time.strptime() without locking myself out. And, what is the pretty way
> to do all of this, because a couple hours later it looks pretty ugly. I mean
> it turns out I'm rewriting the file anyway so no need to delete the row.
> http://pastebin.ws/e0prlj
> Regards,
> Benjamin Serrato
> 682.472.8650

To see the problem with your code, think about the following: Suppose
that you go into the 'except' branch. What is the program going to do
_after_ the code in the except branch has been run? The code will go
on with the part after the try...except, and there will 'need' the
variable row again. You will have to add 'continue' to the except, or
put the code below it in an 'else'.

Another issue I see is the 'del row' code itself - it has no real
function, you are deleting something that will be deleted on the next
execution step anyway.


-- 
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] Convert string to long

2011-02-24 Thread Andre Engels
On Thu, Feb 24, 2011 at 3:03 PM, tee chwee liong  wrote:
 '0x' + hex(543)[2:].zfill(5)
> '0x0021f'
>
> this is a good way but it's still in string format. but if i convert it to
> long, then the leading 0s will be truncated. i guess can't have it both way.

A long is just a number. You cannot say that a number has or does not
have leading zeroes. Only _a representation of_ that number has. The
numbers 3, 1+2 and 3 are all the same number, so you
cannot say that the first does not have leading zeroes whereas the
last one has. To make the concept of 'leading zeroes' a meaningful
one, you _first_  have to re-convert the number to a string. Whether
or not there are leading zeroes depends on how that conversion is
done. If you use Python's standard conversion method, the result will
be a string representation without leading zeroes, but there are other
conversion methods that do give leading zeroes.

-- 
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

2011-02-24 Thread Andre Engels
On Thu, Feb 24, 2011 at 5:15 AM, Chris Schiro  wrote:
> Hi,
>
> I am completely new to programming aside from working with basic many years
> ago. I purchased a Python book for beginners so I could start from scratch
> which has been walking me through just fine until: writing a program to
> interact with user for feedback:
>
>
>
> name=input(“What is your name? “)
>
>
>
> I have found that this line will return an error every time while running
> the completed program, unless I enter a number. If I enter a numeric value
> the program will continue on as written.
>
>
>
> I have followed the code exactly per the book. What is the proper coding in
> this scenario?

What is going on is that you are presumably running some version of
Python 2, whereas the book you are using is intended for Python 3. In
Python 2, to get the same result as input() in Python 3, you have to
use raw_input instead.

name=raw_input(“What is your name? “)

Alternatively, you could of course install Python 3.1 instead of
Python 2.7 (or whatever version you are running).

-- 
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] Composing lists from both items and other lists

2011-02-01 Thread Andre Engels
On Tue, Feb 1, 2011 at 9:40 PM, John Simon  wrote:
> I'm looking for a way to flatten lists inside a list literal, kind of like
> this:
>
 start = '('
 end = ')'
 items = ['abc', '+', 'def']
 [start, *items, end]
> ['(', 'abc', '+', 'def', ')']
> Of course, the star doesn't work there. Is there any easy,
> syntactically-lightweight way to get that output?

Is:

[start] + items + [end]

lightweight enough?


-- 
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] age program

2010-11-29 Thread Andre Engels
We will not make your homework for you. However, we may well give you hints
and perhaps solve small parts that you are unable to do yourself. For that,
however, we need to know *what* it is that you are having problems with.

Thus: You said that you have tried everything you can. What have you tried?
What part(s) of the problem are you able to solve? What part(s) of the
problem are you not able to solve?

On Mon, Nov 29, 2010 at 3:29 PM, Andre Jeyarajan
wrote:

> Write a short program that will perform the following:
>
> It will ask the user for his age,
>
> it will then present the user with a menu, with 4 choices:
>
>1. Tell the user whether his age is an even or an odd number
>2. Tell the user his age squared
>3. Tell the user how many years until he’s 100 years old, or tell him
>that he’s alerady over 100!  If the user is exactly 100 years old,
>congratulate him for being a centurion.
>
>
> I have tried everything i can. Can you please explain it to me?
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
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] noob

2010-11-29 Thread Andre Engels
On Mon, Nov 29, 2010 at 6:57 AM, Mary  wrote:
> Dear Tutors:
>
> Thank you for your time.I am trying to do first assignment (ps1a+b) onMIT
> open study, finding the 1000th prime in part a and doing something with
> import.math and logs in part b, but I'm not there yet. The little build i
> did to find primes does fine until, for some reason, 95 shows up, and later
> other multiples of 5 jump into the mix without being invited.I end up almost
> 200 primes off by the 1000 count. Is it me? Have uninstalled and reinstalled
> 2.7 twice. Here is code:

Your primality tester is incorrect. When you find a divisor you go on
to check the number that is 2 more, but you start with the same
divisor. If the new number you check is not a prime number, but only
has divisors smaller than the checked divisor, your program will
falsely recognize it as prime.

To make it more clear what I mean, I will show how your program finds
95 to be prime:

89 was a prime, and next the program checks 91.
91 is not divisible by 2.
91 is not divisible by 3.
91 is not divisible by 4.
91 is not divisible by 5.
91 is not divisible by 6.
91 is divisible by 7 - not prime! check 93 instead
93 is not divisible by 7.
93 is not divisible by 8.
...
93 is not divisible by 30.
93 is divisible by 31 - not prime! check 95 instead
95 is not divisible by 31.
...
95 is not divisible by 90.
Checked all numbers smaller than 91, so 95 is prime.




-- 
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] 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] 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] 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] 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] 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] 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] (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] 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] 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] 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-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] 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] 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] 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] 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] 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] 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] 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] 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] 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] 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] 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] 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] 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


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] 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] 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] 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] 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] 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] 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] 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] 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] 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] 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] 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] 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] 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] 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


[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] 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


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] 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] 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] 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] 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] 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-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] 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] 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] reading file, adding to each line, writing file

2009-02-04 Thread Andre Engels
On Wed, Feb 4, 2009 at 3:30 PM, David  wrote:
> Hello everybody,
>
> I have easily spent some four hours on this problem, and I am now asking for
> rescue.
>
> Here is what I am trying to do: I have a file ("step2", with some 30 or so
> lines. To each line I would like to add " -d" at the end. Finally, I want to
> save the file under another name ("pyout".
> So far I have managed to read the file, line by line, and save it under
> another name:
>
> 
>
> # add " -d" to each line of a textfile
>
> infile = open("step2", 'r') # open file for appending
> outfile = open("pyout","a") # open file for appending
>
> line = infile.readline()# Invokes readline() method on file
> while line:
>outfile.write(line),# trailing ',' omits newline character
>line = infile.readline()
>
> infile.close()
> outfile.close()
>
> 
>
> As I said, before writing to file "pyout" I would like to append the string
> " -d" to each line. But how, where? I can't append to strings (which the
> lines gained with infile.readline() seem be), and my trial and error
> approach has brought me nothing but a headache.

You cannot append to strings, but you can add to them!

So the first step would be:

> # add " -d" to each line of a textfile
infile = open("step2", 'r') # open file for reading
outfile = open("pyout","a") # open file for appending

line = infile.readline()# Invokes readline() method on file
while line:
   outfile.write(line+" -d"),# trailing ',' omits newline character
   line = infile.readline()

infile.close()
outfile.close()


However, that doesn't work fine, because the newline is at the end of
the line, and thus the -d is coming at the beginning. To work that
out, we use string.strip() which allows us to remove certain
characters from the beginning and end of a string:

# add " -d" to each line of a textfile

infile = open("step2", 'r') # open file for reading
outfile = open("pyout","a") # open file for appending

line = infile.readline()# Invokes readline() method on file
while line:
  outfile.write(line.strip("\n")+" -d\n")
  line = infile.readline()

infile.close()
outfile.close()


By the way, a somewhat more elegant method (in my opinion at least) is
to use readlines(), which gives a generator of the lines in a file,
rather than readline():

# add " -d" to each line of a textfile

infile = open("step2", 'r') # open file for appending
outfile = open("pyout","a") # open file for appending

for line in infile.readlines():
  outfile.write(line.strip("\n")+" -k\n")

infile.close()
outfile.close()


Yet another method would be a combination of read and replace:

# add " -d" to each line of a textfile

infile = open("step2", 'r') # open file for appending
outfile = open("pyout","a") # open file for appending

outfile.write(infile.read().replace("\n"," -d\n"))

infile.close()
outfile.close()


However, this is sensitive to the presence or absence of a newline
after the last line.


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


Re: [Tutor] transforming an integer to a list of integers

2009-02-03 Thread Andre Engels
On Tue, Feb 3, 2009 at 4:24 PM, Andre Engels  wrote:
> On Tue, Feb 3, 2009 at 4:17 PM, H.G. le Roy  wrote:
>> Hi,
>>
>> recently I learned about Project Euler (http://projecteuler.net/) and now
>> I'm trying to work me through. At the moment I'm thinking about
>> http://projecteuler.net/index.php?section=problems&id=8
>>
>> One step for my solution should be transforming this big integer to a list
>> of integers. I did:
>>
>> import math
>>
>> bignr = 12345
>> bignrs =[]
>>
>> for i in xrange(math.ceil(math.log10(bignr)):
>>   rem = bignr % 10
>>   bignrs.append(rem)
>>   bignr /= 10
>>
>> However this "feels" a bit complicated, Do you know a better (more simple,
>> nice etc.) way to do this?
>
> One way could be to represent the number as a string; a string can be
> treated as a list, so you get what you want quite quickly that way:
>
> bignr = 12345
> bignrs =[]
>
> for char in str(bignr):
>bignrs.append(int(char))

Or as a one-liner:

bignr = 12345
bignrs =[int(char) for char in str(bignr)]


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


Re: [Tutor] transforming an integer to a list of integers

2009-02-03 Thread Andre Engels
On Tue, Feb 3, 2009 at 4:17 PM, H.G. le Roy  wrote:
> Hi,
>
> recently I learned about Project Euler (http://projecteuler.net/) and now
> I'm trying to work me through. At the moment I'm thinking about
> http://projecteuler.net/index.php?section=problems&id=8
>
> One step for my solution should be transforming this big integer to a list
> of integers. I did:
>
> import math
>
> bignr = 12345
> bignrs =[]
>
> for i in xrange(math.ceil(math.log10(bignr)):
>   rem = bignr % 10
>   bignrs.append(rem)
>   bignr /= 10
>
> However this "feels" a bit complicated, Do you know a better (more simple,
> nice etc.) way to do this?

One way could be to represent the number as a string; a string can be
treated as a list, so you get what you want quite quickly that way:

bignr = 12345
bignrs =[]

for char in str(bignr):
bignrs.append(int(char))




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


Re: [Tutor] re division problem

2009-02-03 Thread Andre Engels
On Tue, Feb 3, 2009 at 2:46 PM, prasad rao  wrote:
> hi
>>Right now you skip by x+((len(v))/columns)
>>which will be different for each row.
> How is it possible. len(v)=98.A constant.
> Is it not.
> Does len(v) changes with each iteration?

No, but x does.


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


Re: [Tutor] weird bool

2009-02-03 Thread Andre Engels
On Tue, Feb 3, 2009 at 11:40 AM, prasad rao  wrote:
> hi
 a=2.1
 a%1==True
> False
 a%1==False
> False
 b=3.8
 b%1==True
> False
 b%1==False
> False
> If it gives correct bool, it could be put to good use.

== gives a high degree of equality. In your idea, it would not be a
kind of equality at all, because you would have:

>>> 1 == True
True
>>> 2 == True
True
>>> 1 == 2
False

It would also be confusion as to when '==' would mean logical equality
and when real equality:

 1 == ((0 == 0) or not (0==0))
True
 1 == ((0 + 0) * (0 + 0))
False
 True == 1
???

Finally, it is rarely necessary:
>>> a=2.1
>>> bool(a%1)==True
True

That's a few characters more, but to me that's more than compensated
by the gains in clarity and consistency (== is an equivalence
relationship, at least unless you have redefined it for your own class
in a less practical way)

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


Re: [Tutor] newton's square root formula

2009-02-03 Thread Andre Engels
On Tue, Feb 3, 2009 at 3:59 AM, WM.  wrote:
> # program to find square root
> square = float(raw_input ("Please enter a number to be rooted, "))
> guess = input("Please guess at the root, ")
> i = 0
> while guess**2 != square:
>i+=1
># Newton's formula
>guess = guess - (guess * guess - square) / (guess * 2)
>print i
> print "\n\n\n%s is the square root of %s" % (guess, square)
> print "\n%s loops were run." % (i)
> print "\n\n\nbye"
> #
>
>
> Here is my program, enhanced by Alan's good advice. The reason I wanted to
> re-write the other program was, it had a limited number of loops and I felt
> accuracy should be the measure. So, just now, I added a loop counter here
> and found that the formula is a little buggy. Make 'square = 7' and you will
> be in the 'i = 500' area before you can find ControlC.

The problem is the loop guard:

while guess**2 != square

There probably is no number guess for which Python has guess**2 == 7
exactly. You'll have to choose a certain precision, and look for a
number for which this closer than your chosen precision rather than a
number for which it is true exactly.

Change the guard to:

while abs(guess*guess-square) > 0.1:

and (choosing 1 as my initial guess) I got an answer after 6 iterations.

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


[Tutor] Re : Is instance of what?

2009-01-31 Thread Andre Engels
On Sat, Jan 31, 2009 at 5:57 PM, Tim Johnson  wrote:
> Using python 2.5.1
>
> If I create a class a
>
> class a:
>
> pass
>
> initialize o as:
>
> o=a
>
> and call
>
> isinstance(o,a)
>
> the return value is True.

Actually, it is false. To make it true, you have to do o=a() rather than o=a

> Is there a function that takes one
>
> argument and returns the class?
>
> Example:
>
> class = whatclass(o)
>
>>> "a"
>
> Since I'm hoping the answer to this question will help me
>
> answer some bigger questions, pointers to relevant docs
>
> and discussions is invited.

o.__class__ (or rather o.__class__.__name__) will work.



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


  1   2   >