[Tutor] unicode: % & __str__ & str()

2009-10-30 Thread spir
[back to the list after a rather long break]

Hello,

I stepped on a unicode issue ;-) (one more)
Below an illustration:

===
class U(unicode):
def __str__(self):
return self

# if you can't properly see the string below,
# 128

¶ÿµ ¶ÿµ ¶ÿµ
¶ÿµ ¶ÿµ ***
¶ÿµ *** ***


The last line shows that a regular unicode cannot be passed to str() (more or 
less ok) nor __str__() (not ok at all).
Maybe I overlook some obvious point (again). If not, then this means 2 issues 
in fact:

-1- The old ambiguity of str() meaning both "create an instance of type str 
from the given data" and "build a textual representation of the given object, 
through __str__", which has always been a semantic flaw for me, becomes 
concretely problematic when we have text that is not str.
Well, i'm very surprised of this. Actually, how comes this point doesn't seem 
to be very well known; how is it simply possible to use unicode without 
stepping on this problem? I guess this breaks years or even decades of habits 
for coders used to write str() when they mean __str__().

-2- How is it possible that __str__ does not work on a unicode object? It seems 
that the method is simply not implemented on unicode, the type, and __repr__ 
neither. So that it falls back to str().
Strangely enough, % interpolation works, which means that for both types of 
text a short circuit is used, namely return the text itself as is. I would have 
bet my last cents that % would simply delegate to __str__, or maybe that they 
were the same func in fact, synonyms, but obviously I was wrong!

Looking for workarounds, I first tried to overload (or rather create) __str__ 
like in the U type above. But this solution is far to be ideal cause we still 
cannot use str() (I mean my digits can write it while my head is 
who-knows-where). Also, it is really unusable in fact for the following reason:
===
print c1.__class__
print c1[1].__class__
c3 = c1 ; print (c1+c3).__class__
==>




Any operation will return back a unicode instead of the original type. So that 
the said type would have to overload all possible operations on text, which is 
much, indeed, to convert back the results. I don't even speak of performance 
issues.

So, the only solution seems to me to use % everywhere, hunt all str and __str__ 
and __repr__ and such in all code.

I hope I'm wrong on this. Please, give me a better solution ;-)



--
la vita e estrany


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


Re: [Tutor] How to manipulate a variable whose value depends on next values of list using LC or reduce()

2009-10-30 Thread Dave Angel

Shashwat Anand wrote:

Shashwat Anand to Bangalore
show details 5:31 AM (2 minutes ago)


I wrote an LCM function of mine as follows:

import fractions
def lcm(mylist):
# lcm by defination is Lowest Common Multiple
# lcm (a*b) = a*b / gcd(a*b)
# lcm (a, b, c) = lcm(lcm(a, b), c)
# the function lcm() returns lcm of numbers in a list
# for the special case of two numbers, pass the argument as lcm([a, b])
sol = 1
for i in mylist:
sol = sol * i / fractions.gcd(sol, i)
return sol

print lcm(range(1, 11))  #gives lcm of numbers (1, 2, 3,9 ,10)
print lcm([2, 3]) #gives lcm of two numbers, a special case
print lcm([2, 5, 6, 10])   #gives lcm of a random list


However I also did a dirty hack as an alternate approach :

import fractions
l = [1]
print max( ( l[i-2], l.append(l[-1] * i / fractions.gcd(l[-1], i ) ) ) for i
in range(2, 12) )[0]
# prints the LCM of list (1, 10)

However to shorten the code i made it totally unpythonic.
Can reduce( ) or any other function be of help ?

Let me take a test-case as an example:
I want to multiple all the content of a given list,
now say my list is lst = [2, 3, 9]
I can do:

sol = 1
for i in lst:
sol *= i
print sol

However this can also be done as:

  

reduce( operator.mul, lst)



Can it be done via List Comprehension or we have to do dirty hacks as
mentioned above :(
Can the LCM function be reduced ?

*The point is if we insert a variable( sol here in both test case and LCM
case), which changes its values dynamically depending upon the next values
of the list, how can I calculate so without going through the long way of
using for-construct*, which makes me feel as though i'm coding in C. reduce(
) or even sum( ) does helps in some cases but it constrains me as per my
requirement. Any pointers ?

  

Starting where Alan left off,

def lcm(mylist):
   def lcm2(a, b):
   return a*b / fractions.gcd(a, b)
   return reduce(lcm2, mylist)

or, if you feel the need to get rid of the extra name,

def lcm(mylist):
   return reduce(lambda a,b : a*b/fractions.gcd(a,b), mylist)

DaveA
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to manipulate a variable whose value depends on next values of list using LC or reduce()

2009-10-30 Thread Shashwat Anand
Got it !!

@Alan, @DaveA:  Hontoni Arigato :)

On Fri, Oct 30, 2009 at 9:55 PM, Dave Angel  wrote:

> Shashwat Anand wrote:
>
>> Shashwat Anand to Bangalore
>> show details 5:31 AM (2 minutes ago)
>>
>> 
>>
>> I wrote an LCM function of mine as follows:
>>
>> import fractions
>> def lcm(mylist):
>># lcm by defination is Lowest Common Multiple
>># lcm (a*b) = a*b / gcd(a*b)
>># lcm (a, b, c) = lcm(lcm(a, b), c)
>># the function lcm() returns lcm of numbers in a list
>># for the special case of two numbers, pass the argument as lcm([a, b])
>>sol = 1
>>for i in mylist:
>>sol = sol * i / fractions.gcd(sol, i)
>>return sol
>>
>> print lcm(range(1, 11))  #gives lcm of numbers (1, 2, 3,9 ,10)
>> print lcm([2, 3]) #gives lcm of two numbers, a special case
>> print lcm([2, 5, 6, 10])   #gives lcm of a random list
>>
>>
>> However I also did a dirty hack as an alternate approach :
>>
>> import fractions
>> l = [1]
>> print max( ( l[i-2], l.append(l[-1] * i / fractions.gcd(l[-1], i ) ) ) for
>> i
>> in range(2, 12) )[0]
>> # prints the LCM of list (1, 10)
>>
>> However to shorten the code i made it totally unpythonic.
>> Can reduce( ) or any other function be of help ?
>>
>> Let me take a test-case as an example:
>> I want to multiple all the content of a given list,
>> now say my list is lst = [2, 3, 9]
>> I can do:
>>
>> sol = 1
>> for i in lst:
>>sol *= i
>> print sol
>>
>> However this can also be done as:
>>
>>
>>
>>> reduce( operator.mul, lst)
>
>

>> Can it be done via List Comprehension or we have to do dirty hacks as
>> mentioned above :(
>> Can the LCM function be reduced ?
>>
>> *The point is if we insert a variable( sol here in both test case and LCM
>> case), which changes its values dynamically depending upon the next values
>> of the list, how can I calculate so without going through the long way of
>> using for-construct*, which makes me feel as though i'm coding in C.
>> reduce(
>> ) or even sum( ) does helps in some cases but it constrains me as per my
>> requirement. Any pointers ?
>>
>>
>>
> Starting where Alan left off,
>
> def lcm(mylist):
>   def lcm2(a, b):
>   return a*b / fractions.gcd(a, b)
>   return reduce(lcm2, mylist)
>
> or, if you feel the need to get rid of the extra name,
>
> def lcm(mylist):
>   return reduce(lambda a,b : a*b/fractions.gcd(a,b), mylist)
>
> DaveA
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Sorting points on a 2D plane

2009-10-30 Thread Shashwat Anand
The problem belongs to 'Convex Hull' superset.
look into : http://en.wikipedia.org/wiki/Convex_hull_algorithms


On Thu, Oct 29, 2009 at 6:05 PM, Robert Berman  wrote:

>
> Kent and Alan,
>
> Thank you both for providing me with tools I can use to develop the sort
> portion of my algorithm. They are invaluable. I really appreciate Luke's
> willingness to examine and advise on the full algorithm and once it is
> written (only the function that determines distance between two points
> is written and working) I will definitely add it to pastebin and ask for
> your suggestions as well as the suggestions and comments from the group.
>
> Again, thank you for your help.
>
> Robert
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Sorting points on a 2D plane

2009-10-30 Thread Robert Berman
Hello Shashwat,

I have saved the web page for a much more detailed review after I work
through the suggestions given by Alan et all. It is obvious that a
casual read is not going to be enough.

Thank you for the information.

Robert


On Fri, 2009-10-30 at 23:49 +0530, Shashwat Anand wrote:

> The problem belongs to 'Convex Hull' superset.
> look into : http://en.wikipedia.org/wiki/Convex_hull_algorithms
> 
> 
> 
> On Thu, Oct 29, 2009 at 6:05 PM, Robert Berman 
> wrote:
> 
> 
> Kent and Alan,
> 
> Thank you both for providing me with tools I can use to
> develop the sort
> portion of my algorithm. They are invaluable. I really
> appreciate Luke's
> willingness to examine and advise on the full algorithm and
> once it is
> written (only the function that determines distance between
> two points
> is written and working) I will definitely add it to pastebin
> and ask for
> your suggestions as well as the suggestions and comments from
> the group.
> 
> Again, thank you for your help.
> 
> Robert
> 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Sorting points on a 2D plane

2009-10-30 Thread Shashwat Anand
@Robert:

You can look for a similar problem here :
https://www.spoj.pl/problems/BSHEEP/
For algorithm I suggest you to go for Graham's scan or Quick hull.



On Sat, Oct 31, 2009 at 1:39 AM, Robert Berman  wrote:

>  Hello Shashwat,
>
> I have saved the web page for a much more detailed review after I work
> through the suggestions given by Alan et all. It is obvious that a casual
> read is not going to be enough.
>
> Thank you for the information.
>
> Robert
>
>
>
> On Fri, 2009-10-30 at 23:49 +0530, Shashwat Anand wrote:
>
> The problem belongs to 'Convex Hull' superset.
> look into : http://en.wikipedia.org/wiki/Convex_hull_algorithms
>
>
>  On Thu, Oct 29, 2009 at 6:05 PM, Robert Berman 
> wrote:
>
>
> Kent and Alan,
>
> Thank you both for providing me with tools I can use to develop the sort
> portion of my algorithm. They are invaluable. I really appreciate Luke's
> willingness to examine and advise on the full algorithm and once it is
> written (only the function that determines distance between two points
> is written and working) I will definitely add it to pastebin and ask for
> your suggestions as well as the suggestions and comments from the group.
>
> Again, thank you for your help.
>
> Robert
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Accessing variables in main from functions in a module

2009-10-30 Thread Robert Lummis
I want to move some functions from my "main" program file to a module
file because the main file is getting too big for convenience. The
functions access arrays (lists of lists) that are defined and
initialised in the main file. How do I reference the main file arrays
from statements within the module file?

The overall program solves a game by a recursive method. The arrays
are the game data. Functions in the main file and also functions in
the module need to read and write them. The program works when all the
functions are in the main file but now I want to develop it further
and the presence of a bunch of unchanging housekeeping functions in
the main file makes it cumbersome to read and edit.

With everything in the main file a function like the following works
as expected:

def functionA (row, col, x):
 grid[row][col] = 

where grid[] is initialised outside of any functions (i.e. in the main).

So how do I write that function when I move it to a module file? I
thought I read somewhere that the main routine has the name "__main__"
so I tried:

 __main__.grid[row][col] = <...>

 but that gives "NameError: name '__main__' is not defined".

I understand that it is best to minimize cross-file references but I
feel it is warranted in this case. Even if you think it isn't good
practice I would like to understand how to do it (or else why it can't
be done). Is there some other way to keep files from getting too big?

-- 
Robert Lummis
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Accessing variables in main from functions in a module

2009-10-30 Thread Alan Gauld

"Robert Lummis"  wrote


I want to move some functions from my "main" program file to a module
file because the main file is getting too big for convenience.


Good idea!


functions access arrays (lists of lists) that are defined and
initialised in the main file. How do I reference the main file arrays
from statements within the module file?


In  general you don't. You pass the data into the function.
Thats the only (sane) way to make the functions reusable,
by passing in all the data they need to do their job. Its also
the only sane way to avoid the debugging nightmare of
global variables changing under your feet due to hidden
function side effects.

So when you move the functions, rewrite them from

def f(...)
   # stuff
to

def f(...grid)
   #stuff
   return grid

And when you call them do

grid = mymod.f(...,grid)

That keeps the functions independant and avoids any
mysteries about where your main function variables are
getting changed.


The overall program solves a game by a recursive method.


In that case even more reason to pass the data in. Recursive
functions opertating on global variables are one of the hardest
things to debug in the programming universe, only beaten by
multiple threads modifying unsynchronised global variables!


and the presence of a bunch of unchanging housekeeping functions in
the main file makes it cumbersome to read and edit.


Yes thats one reason to move functions out. But an even better
reason is to logically partition the code into whats reusable
and what is specific to the problem. So consider whether its
really the housekeeping that wants moving or the core algorithms...


def functionA (row, col, x):
grid[row][col] = 

where grid[] is initialised outside of any functions (i.e. in the main).

So how do I write that function when I move it to a module file? I


As above

def functionA (row, col, x, grid):
grid[row][col] = 
return grid

and call it with

grid = module.function(row,col,x, grid)


thought I read somewhere that the main routine has the name "__main__"


A module that is being run directly has the name __main__ not a function.


I understand that it is best to minimize cross-file references but I
feel it is warranted in this case.


I doubt it.


Even if you think it isn't good practice I would like to understand how
to do it (or else why it can't be done).


You can probably do it by inspecting the call stack using the traceback
module or somesuch, but there'sd really no need.


Is there some other way to keep files from getting too big?


You can use classes. You could have a Grid class with all the functions
that modify the grid as methods. Then you can create grid objects and
operate on them and each will have its own internal grid. You can then
easily move the class into a separate module as required.

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


Re: [Tutor] Accessing variables in main from functions in a module

2009-10-30 Thread Kent Johnson
On Fri, Oct 30, 2009 at 6:39 PM, Robert Lummis  wrote:
> I want to move some functions from my "main" program file to a module
> file because the main file is getting too big for convenience. The
> functions access arrays (lists of lists) that are defined and
> initialised in the main file. How do I reference the main file arrays
> from statements within the module file?

A couple of solutions:
- Put the arrays into some kind of structure that you can pass as an
argument. The structure could be a list, dict or custom class.
- Create a class (or possibly more than one class) to hold both the
data and the functions that operate on it.

> With everything in the main file a function like the following works
> as expected:
>
> def functionA (row, col, x):
> grid[row][col] = 
>
> where grid[] is initialised outside of any functions (i.e. in the main).
>
> So how do I write that function when I move it to a module file? I

That might make a good method of a grid class. Then it would become
something like
def functionA(self, row, col, x):
  self.grid[row][col] = ...

> So how do I write that function when I move it to a module file? I
> thought I read somewhere that the main routine has the name "__main__"
> so I tried:
>
>  __main__.grid[row][col] = <...>
>
>  but that gives "NameError: name '__main__' is not defined".

You can
  import __main__
and the above will work but that is *not* the best solution.

> I understand that it is best to minimize cross-file references but I
> feel it is warranted in this case.

Cross-file references are not bad by themselves but circular
references (module A uses module B and B uses A) are a bad idea.

> Even if you think it isn't good
> practice I would like to understand how to do it (or else why it can't
> be done). Is there some other way to keep files from getting too big?

Yes. Object-oriented design is the most common way of dealing with
this. Think about decomposing your code into cooperating objects.

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] problem adding Tkinter

2009-10-30 Thread Kristin Wilcox
I apologize in advance for asking such a simple question! I first
tried looking through Google, and through the last couple months of
this list's archives, and I found some talk about my issue out there
but not a detailed enough answer to help someone as new as me.

This is my first programming language, so most explanations of this
stuff go way over my head!

[This is my problem:] I've been using IDLE successfully to do very
very simple exercises in Python, and now I wanted to start on some
very simple exercises including the Tkinter library. But it looks like
it's not set up right and I don't know how to do what I need to do to
adjust.. whatever needs to be adjusted.

I did the tests listed here: http://wiki.python.org/moin/TkInter

I failed at step 2:
-
Step 2 - can Tkinter be imported?

Try the following command at the Python prompt:

>>> import Tkinter # no underscore, uppercase 'T'

* If it works, go to step 3.
* If it fails with "No module named Tkinter", your Python
configuration need to be changed to include the directory that
contains Tkinter.py in its default module search path. You have
probably forgotten to define TKPATH in the Modules/Setup file. A
temporary workaround would be to find that directory and add it to
your PYTHONPATH environment variable. It is the subdirectory named
"lib-tk" of the Python library directory (when using Python 1.4 or
before, it is named "tkinter").
--
I could do import _tkinter but not import Tkinter

This is what I received back from the Shell:
>>> import _tkinter
>>> import Tkinter
Traceback (most recent call last):
  File "", line 1, in 
import Tkinter
ImportError: No module named Tkinter
>>>


Unfortunately, the instructions they gave on what to do if Step 2
fails read like Greek to me. I don't know what a PYTHONPATH is, I
don't remember doing anything with a Modules/Setup file, and I don't
know what an environment variable is, or what to do with
subdirectories.

I am running Windows XP. Installed Python 3.1, and IDLE seems to be
working okay...

When I go to C:\Python31 I see these folders:
DLLs
Doc
include
Lib
libs
tcl
Tools

There are 3 .exe files:
python.exe
pythonw.exe
w9xpopen.exe

I see something called _tkinter.lib in the folder C:\Python31\libs
There is a folder called tkinter inside the folder Lib (C:\Python31\Lib\tkinter)

Would someone be able to spell out to me in every detailed steps
exactly what I should do, assuming I know pretty much nothing about
programming or installing a programming language, so that when I put
import Tkinter it doesn't error?

Thank you very much for reading!

-Kristin
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] problem adding Tkinter

2009-10-30 Thread Kristin Wilcox
SORRY TO ALL: PLEASE DISREGARD MY LAST EMAIL.

I kept searching through the Tutor archives and found an answer in the
Feb archives. (In Python 3 you have to type tkinter in all lower
case.)

Thanks all,
Kristin

On Fri, Oct 30, 2009 at 5:21 PM, Kristin Wilcox  wrote:
> I apologize in advance for asking such a simple question! I first
> tried looking through Google, and through the last couple months of
> this list's archives, and I found some talk about my issue out there
> but not a detailed enough answer to help someone as new as me.
>
> This is my first programming language, so most explanations of this
> stuff go way over my head!
>
> [This is my problem:] I've been using IDLE successfully to do very
> very simple exercises in Python, and now I wanted to start on some
> very simple exercises including the Tkinter library. But it looks like
> it's not set up right and I don't know how to do what I need to do to
> adjust.. whatever needs to be adjusted.
>
> I did the tests listed here: http://wiki.python.org/moin/TkInter
>
> I failed at step 2:
> -
> Step 2 - can Tkinter be imported?
>
> Try the following command at the Python prompt:
>
 import Tkinter # no underscore, uppercase 'T'
>
>    * If it works, go to step 3.
>    * If it fails with "No module named Tkinter", your Python
> configuration need to be changed to include the directory that
> contains Tkinter.py in its default module search path. You have
> probably forgotten to define TKPATH in the Modules/Setup file. A
> temporary workaround would be to find that directory and add it to
> your PYTHONPATH environment variable. It is the subdirectory named
> "lib-tk" of the Python library directory (when using Python 1.4 or
> before, it is named "tkinter").
> --
> I could do import _tkinter but not import Tkinter
>
> This is what I received back from the Shell:
 import _tkinter
 import Tkinter
> Traceback (most recent call last):
>  File "", line 1, in 
>    import Tkinter
> ImportError: No module named Tkinter

>
>
> Unfortunately, the instructions they gave on what to do if Step 2
> fails read like Greek to me. I don't know what a PYTHONPATH is, I
> don't remember doing anything with a Modules/Setup file, and I don't
> know what an environment variable is, or what to do with
> subdirectories.
>
> I am running Windows XP. Installed Python 3.1, and IDLE seems to be
> working okay...
>
> When I go to C:\Python31 I see these folders:
> DLLs
> Doc
> include
> Lib
> libs
> tcl
> Tools
>
> There are 3 .exe files:
> python.exe
> pythonw.exe
> w9xpopen.exe
>
> I see something called _tkinter.lib in the folder C:\Python31\libs
> There is a folder called tkinter inside the folder Lib 
> (C:\Python31\Lib\tkinter)
>
> Would someone be able to spell out to me in every detailed steps
> exactly what I should do, assuming I know pretty much nothing about
> programming or installing a programming language, so that when I put
> import Tkinter it doesn't error?
>
> Thank you very much for reading!
>
> -Kristin
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] unicode: % & __str__ & str()

2009-10-30 Thread Dave Angel

spir wrote:

[back to the list after a rather long break]

Hello,

I stepped on a unicode issue ;-) (one more)
Below an illustration:

class U(unicode):
def __str__(self):
return self

# if you can't properly see the string below,
# 128


==
Any operation will return back a unicode instead of the original type. So that 
the said type would have to overload all possible operations on text, which is 
much, indeed, to convert back the results. I don't even speak of performance 
issues.

So, the only solution seems to me to use % everywhere, hunt all str and __str__ 
and __repr__ and such in all code.

I hope I'm wrong on this. Please, give me a better solution ;-)



--
la vita e estrany



  
I'm not the one to help with this, because my unicode experience is 
rather limited.  But I think I know enough to ask a few useful questions.


1) What version of Python are you doing this on, what OS, and what code 
page is your stdout using?


2) What coding declaration do you have in your source file?  Without it, 
I can't even define those literals.  I added the line

#-*- coding: utf-8 -*-
as line 2 of my source file to get past that one.  But I really don't 
know much about this literal string that I pasted from your email.


3) Could you give us the hex equivalent of the 3 character string you're 
trying to give us in the email.  The only clue you gave us was that the 
bytes were between
129 and 254, which they aren't, on my machine, at least with a utf-8 
coding declaration.

repr(u"¶ÿµ") -->  u'\xb6\xff\xb5'   length= 3
repr(c0) -->  '\xc2\xb6\xc3\xbf\xc2\xb5'  length = 6

You say that __str__() isn't defined on Unicode objects, but that's not 
the case, at least in 2.6.2.   Works fine on ASCII characters, but 
something causes an exception for your strings.  Since you're eating the 
exception, all you know is something went wrong, not what went wrong.  
And since my environment is probably totally different, ...   I get the 
exception text: 'ascii' codec can't encode characters in position 0-2: 
ordinal not in range(128)


Incidentally, you'll probably save yourself a lot of grief in the long 
run if you change your editor to always expand tabs to spaces (4-per).  
It's dangerous, and not recommended to mix tabs and spaces in the same 
file, and it's surprising how often spaces get mixed in by accident.  In 
Python3.x it's illegal to mix them.


DaveA


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


Re: [Tutor] problem adding Tkinter

2009-10-30 Thread Dave Angel

Kristin Wilcox wrote:

I apologize in advance for asking such a simple question! I first
tried looking through Google, and through the last couple months of
this list's archives, and I found some talk about my issue out there
but not a detailed enough answer to help someone as new as me.

This is my first programming language, so most explanations of this
stuff go way over my head!

[This is my problem:] I've been using IDLE successfully to do very
very simple exercises in Python, and now I wanted to start on some
very simple exercises including the Tkinter library. But it looks like
it's not set up right and I don't know how to do what I need to do to
adjust.. whatever needs to be adjusted.

I did the tests listed here: http://wiki.python.org/moin/TkInter

I failed at step 2:
-
Step 2 - can Tkinter be imported?

Try the following command at the Python prompt:

  

import Tkinter # no underscore, uppercase 'T'



* If it works, go to step 3.
* If it fails with "No module named Tkinter", your Python
configuration need to be changed to include the directory that
contains Tkinter.py in its default module search path. You have
probably forgotten to define TKPATH in the Modules/Setup file. A
temporary workaround would be to find that directory and add it to
your PYTHONPATH environment variable. It is the subdirectory named
"lib-tk" of the Python library directory (when using Python 1.4 or
before, it is named "tkinter").
--
I could do import _tkinter but not import Tkinter

This is what I received back from the Shell:
  

import _tkinter
import Tkinter


Traceback (most recent call last):
  File "", line 1, in 
import Tkinter
ImportError: No module named Tkinter
  



Unfortunately, the instructions they gave on what to do if Step 2
fails read like Greek to me. I don't know what a PYTHONPATH is, I
don't remember doing anything with a Modules/Setup file, and I don't
know what an environment variable is, or what to do with
subdirectories.

I am running Windows XP. Installed Python 3.1, and IDLE seems to be
working okay...

When I go to C:\Python31 I see these folders:
DLLs
Doc
include
Lib
libs
tcl
Tools

There are 3 .exe files:
python.exe
pythonw.exe
w9xpopen.exe

I see something called _tkinter.lib in the folder C:\Python31\libs
There is a folder called tkinter inside the folder Lib (C:\Python31\Lib\tkinter)

Would someone be able to spell out to me in every detailed steps
exactly what I should do, assuming I know pretty much nothing about
programming or installing a programming language, so that when I put
import Tkinter it doesn't error?

Thank you very much for reading!

-Kristin

  
You're looking at websites describing Python 2.x, but you're using 3.1.  
The Tkinter module was renamed tkinter.


So change
  import  Tkinter
to
 import tkinter

and see if it starts working better

DaveA
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Accessing variables in main from functions in a module

2009-10-30 Thread Dave Angel

Kent Johnson wrote:

On Fri, Oct 30, 2009 at 6:39 PM, Robert Lummis  wrote:
  

I want to move some functions from my "main" program file to a module
file because the main file is getting too big for convenience. The
functions access arrays (lists of lists) that are defined and
initialised in the main file. How do I reference the main file arrays
from statements within the module file?



A couple of solutions:
- Put the arrays into some kind of structure that you can pass as an
argument. The structure could be a list, dict or custom class.
- Create a class (or possibly more than one class) to hold both the
data and the functions that operate on it.

  

With everything in the main file a function like the following works
as expected:

def functionA (row, col, x):
grid[row][col] =a value that depends on x and other values in grid>

where grid[] is initialised outside of any functions (i.e. in the main).

So how do I write that function when I move it to a module file? I



That might make a good method of a grid class. Then it would become
something like
def functionA(self, row, col, x):
  self.grid[row][col] =..

  

So how do I write that function when I move it to a module file? I
thought I read somewhere that the main routine has the name "__main__"
so I tried:

 __main__.grid[row][col] =...>

 but that gives "NameError: name '__main__' is not defined".



You can
  import __main__
and the above will work but that is *not* the best solution.

  

I understand that it is best to minimize cross-file references but I
feel it is warranted in this case.



Cross-file references are not bad by themselves but circular
references (module A uses module B and B uses A) are a bad idea.

  

Even if you think it isn't good
practice I would like to understand how to do it (or else why it can't
be done). Is there some other way to keep files from getting too big?



Yes. Object-oriented design is the most common way of dealing with
this. Think about decomposing your code into cooperating objects.

Kent

  
Listen to everything Kent tells you.  He knows more about Python than I 
probably ever will.  But I have been programming for a long time, and 
sometimes I have to be pragmatic on the way to becoming correct.  So 
take this next suggestion as a stop-gap while you debug some of these 
concepts.


Make a brand new module just to hold these global variables.  Call it   
constants.py


In that module, give your initial values for all these globals, but 
don't do anything else.  If absolutely necessary, make a single function 
in the module that'll be called at the very beginning of the script to 
do further initialization.  Above all, don't put any imports in this 
module, except for the obvious stdlib ones, such as os and sys.  But not 
to any other module of your own code.


Now, add an import of that module everywhere you need access to these, 
including from your script.  So if you need access to the constant grid, 
you reference it withconstants.grid


Now I deliberately called the module constants because good practice 
says you'd only use this approach for things which do not change while 
the program is running.  Things like flags passed in from the command 
line, or environmental things like the directory in which files are to 
be stored.


So if you followed my advice to call it constants.py, then you'd be 
reminded each time that this is a temporary hack.


Personally, I like the class approach, where related data is grouped 
together, so a single parameter can be added to each function.  And many 
times, this can lead to generalizations where you suddenly realize that 
instead of one grid, you need to operate on more than one, and the same 
functions could deal with either one. Passing grid (or a class object 
containing grid) would then be a fortunate choice.  And realize that 
object-orientation isn't an all-or-nothing approach.  Make objects out 
of those groups of things that you think there's ever going to be a 
chance of multiple usage, and leave the rest separate values.


And in addition to instance attributes, you can create methods, but you 
could start by doing just the lowest level ones.  For example if your 
grid is implemented as a list of lists, maybe you want accessor methods 
that give it a different appearance, like a single vector.  Or if there 
are two attributes that are interrelated, you can use methods to keep 
them in synch, instead of counting on everyone following the rules.


DaveA

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


[Tutor] python zlib problem

2009-10-30 Thread Amit Sethi
Hi , For some weird reason or a huge screw up I did my python zlib library
has been removed . This is part of standard lib(i think!!!) and it is used
by setuptools and many other libraries .What is the safe way in which I can
recover this library on ubuntu. My previous try somehow lead to removal of
ubuntu-desktop...


If this is not the list I should be asking this I am sorry

-- 
A-M-I-T S|S
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] class attribute to initiate more classes

2009-10-30 Thread Vincent Davis
I have a program that generates many instances of a class with an attribute
self.x = random.gauss(10, 2). So each instance has a different value for
self.x. This is what I want. Now I want to make a class that starts my
program and sets the attributes.
class people:
def __init__(self, size)
self.size = size

class makepeople:
def __init__(self, randomsize)
self.rsize = randomsize
self.allpeople = []
def makethem():
for x in range(1,100):
p+str(x) = people(self.rsize)
allpeople.append(p+str(x))

so what I would like to have work is set the attribute of makepeople so that
when it is used to make instances of people each will have a different size.

listofp = makepeople(random.guass(100, 2))
listofp.makethem()

I would then what listofp.allpeople to be a list of people with different
sizes. The above code does not work, I don't think it does anyway.

I hope this makes sense, I am sure there is a term for what I am trying to
do but I don't know it.

Thanks
Vincent Davis
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] class attribute to initiate more classes

2009-10-30 Thread Michiel Overtoom


On 31 Oct 2009, at 06:01 , Vincent Davis wrote:

I hope this makes sense, I am sure there is a term for what I am  
trying to do but I don't know it.


What a strange program. But at least it compiles:

import random

class people:
def __init__(self, size):
self.size = size

class makepeople:
def __init__(self, randomsize):
self.rsize = randomsize
self.allpeople = []
def makethem(self):
for x in range(self.rsize):
self.allpeople.append(people(self.rsize))

listofp = makepeople(int(random.gauss(100, 2)))
listofp.makethem()


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


Re: [Tutor] Accessing variables in main from functions in a module

2009-10-30 Thread spir
Le Fri, 30 Oct 2009 18:39:42 -0400,
Robert Lummis  s'exprima ainsi:

> I want to move some functions from my "main" program file to a module
> file because the main file is getting too big for convenience. The
> functions access arrays (lists of lists) that are defined and
> initialised in the main file. How do I reference the main file arrays
> from statements within the module file?

It seems to me you're inverting the logic of your program. Actually, the grid 
represents the game state (right?) and is /input/ for the game logic. So what 
is to be exported, if you like, is the grid.
So, you would have for instance a "game_state.py" module defining eg a "grid" 
object imported into main program.
While maybe the funcs you call "housekeeping" actually hold core logic of the 
system. If not, it they are really utilities, then have a "housekeeping.py" 
module that also imports the grid, and itself imported by the main program.

But I guess this would not be the simplest solution. Better make your funcs 
real funcs (in a sense close to math funcs) by feeding them with all their 
input as parameters and letting them return their result, as Alan suggests (I'm 
fan of this point of view, too). Instead of having them wildly read and/or 
write things here and there.
Or make your game state an object that holds its own modifying methods as 
suggested by Kent. Take the opportunity to learn this way of designing an 
application if you don't know it (well). It would certainly be great in your 
case; even more if the game is logically structured enough for you to easily 
split its global state into consistent smaller objects (representing "elements" 
of the game).

Denis
--
la vita e estrany


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