Re: [Tutor] question about listing variables defined since session started

2012-04-30 Thread Steven D'Aprano

Comer Duncan wrote:

Hi,

I have a newbie type question.  Say I have started a python (or
ipython) session and have done some imports and have also defined some
new variables since the session started.  So, I have in my current
namespace a bunch of things. Suppose I  want to list just those
variable  names which have been defined since the session started but
not include the names of the objects that who and whos will return.


What's "who and whos"?



How to do that?  In matlab, this is what the who returns, but in
python I seem to always get a raft of things since I typically do
import a bunch of things.


That depends on what you are doing.

If you are using dir(), then you will get a list of all the currently existing 
objects in your session. There's no way to show only "names defined since the 
session started". Maybe iPython does something like that, but I doubt it.


Taken literally, I don't think you want is possible in Python. When objects 
are created, they aren't timestamped with the moment of when they were 
created, or who created them, or anything else. So there's no way to tell the 
difference between "x = 1" done during system startup and "x = 1" done after 
system startup.


But why do you care? If you explain in more detail what you are hoping to 
accomplish, perhaps we can think of an alternative way to do so.



--
Steven

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


Re: [Tutor] question about listing variables defined since session started

2012-04-30 Thread Alan Gauld

On 30/04/12 22:25, Comer Duncan wrote:


I have a newbie type question.  Say I have started a python (or
ipython) session and have done some imports and have also defined some
new variables since the session started.  So, I have in my current
namespace a bunch of things. Suppose I  want to list just those
variable  names which have been defined since the session started


You could save the initial startup state then later do a delta.
Saving startup state only needs doing once since it should be
the same each time - unless you define local startup commands - in 
whioch case you will need to regenerate the startup state..



not include the names of the objects that who and whos will return.


What are who and whos?
They are not defined in my version of Python...


How to do that?  In matlab, this is what the who returns,


No idea what Matlab does, sorry.


python I seem to always get a raft of things since I typically do
import a bunch of things.


So I'm guessing you don't want any of the imported stuff?
What if you define a variable in an imported module?
Should that be listed or not?

But basically I think you want locals() - startup()
[where you define startup as described above]


--
Alan G
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] question about listing variables defined since session started

2012-04-30 Thread Robert Sjoblom
On 30 April 2012 23:25, Comer Duncan  wrote:
> Hi,
>
> I have a newbie type question.  Say I have started a python (or
> ipython) session and have done some imports and have also defined some
> new variables since the session started.  So, I have in my current
> namespace a bunch of things. Suppose I  want to list just those
> variable  names which have been defined since the session started but
> not include the names of the objects that who and whos will return.
> How to do that?

Not entirely sure, but something like this might work (untested):
for name in dir():
myvalue = eval(name)
print name, "is", type(name), "and is equal to ", myvalue

There's also global(), local() and vars().
-- 
best regards,
Robert S.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] question about listing variables defined since session started

2012-04-30 Thread Comer Duncan
Hi,

I have a newbie type question.  Say I have started a python (or
ipython) session and have done some imports and have also defined some
new variables since the session started.  So, I have in my current
namespace a bunch of things. Suppose I  want to list just those
variable  names which have been defined since the session started but
not include the names of the objects that who and whos will return.
How to do that?  In matlab, this is what the who returns, but in
python I seem to always get a raft of things since I typically do
import a bunch of things.

Thanks for your suggestions.

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


Re: [Tutor] Question about login=''.join(choice(lc) for j in range(llen))

2012-04-03 Thread wesley chun
On Tue, Apr 3, 2012 at 10:50 AM, Peter Otten <__pete...@web.de> wrote:
> Alan Gauld wrote:
>> On 03/04/12 15:54, Khalid Al-Ghamdi wrote:
>>
>>>      dom="".join(choice(lc) for j in range (dlen))
>>>
>>> how does the interpreter know what "j" is supposed to refer to when it
>>> was not mentioned prior?


+1 everyone else's replies so far. i'll add the following: you create
variables by assigning things to them. in this example, no prior code
used the variable 'x':

>>> x = 10
>>> print x
10

similarly, when used in a for-loop, it's like you had an "invisible"
assignment at the "top" of the loop. here's an example:

>>> for i in range(5):
...  print i
...
0
1
2
3
4
>>> print i
4

notice that the 'i' variable is still there even after the loop has
ended. it's as if you did the following:

>>> i = 0
>>> print i
0
>>> i = 1
:
>>> i = 4
>>> print i  # 1st time, part of the "loop"
4
>>> print i  # 2nd time, "outside" of the loop
4

hope this helps!
--wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"A computer never does what you want... only what you tell it."
    wesley chun : wescpy at gmail : @wescpy/+wescpy
    Python training & consulting : CyberwebConsulting.com
    "Core Python" books : CorePython.com
    Python blog: wescpy.blogspot.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about login=''.join(choice(lc) for j in range(llen))

2012-04-03 Thread Peter Otten
Alan Gauld wrote:

> On 03/04/12 15:54, Khalid Al-Ghamdi wrote:
> 
>>  dom="".join(choice(lc) for j in range (dlen))
>>
>> how does the interpreter know what "j" is supposed to refer to when it
>> was not mentioned prior?
> 
> In Python variables are defined by using them.
> 
> In the code below you have i used in a for loop, even though not
> mentioned before. j is similarly being used in the generator expression
> for loop:
> 
> choice(lc) for j in range (dlen)
> 
> unwraps to:
> 
> dummy = []
> for j in range(dlen):
> dummy.append(choice(lc))

An interesting aspect of these "generator expressions" is that they are 
"lazy", they deliver only as many items as necessary.

>>> numbers = (n for n in range(1000))
>>> next(numbers)
0
>>> next(numbers)
1
>>> any(n>10 for n in numbers)
True
>>> next(numbers)
12
>>> any(n<10 for n in numbers)
False
>>> next(numbers)
Traceback (most recent call last):
  File "", line 1, in 
StopIteration

The StopIteration hints that we have consumed all numbers. We were already 
at 13 when we asked for a number < 10; therefore the complete rest from 13 
to 999 was scanned in vain.

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


Re: [Tutor] Question about login=''.join(choice(lc) for j in range(llen))

2012-04-03 Thread Alan Gauld

On 03/04/12 15:54, Khalid Al-Ghamdi wrote:


 dom="".join(choice(lc) for j in range (dlen))

how does the interpreter know what "j" is supposed to refer to when it
was not mentioned prior?


In Python variables are defined by using them.

In the code below you have i used in a for loop, even though not 
mentioned before. j is similarly being used in the generator expression 
for loop:


choice(lc) for j in range (dlen)

unwraps to:

dummy = []
for j in range(dlen):
   dummy.append(choice(lc))

Which effectively creates a list of dlen choice items.



from random import randrange, choice
from string import ascii_lowercase as lc
from sys import maxsize
from time import ctime

tlds = ('com', 'edu', 'net', 'org', 'gov')

for i in range(randrange(5,11)):
 dtint=randrange(maxsize)#pick a random number to use to


HTH
--
Alan G
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] Question about login=''.join(choice(lc) for j in range(llen))

2012-04-03 Thread Emile van Sebille

On 4/3/2012 7:54 AM Khalid Al-Ghamdi said...

Hi,

The following code tries to generate some dummy data for regex
exercises. My question is in reference the line before last:

 dom="".join(choice(lc) for j in range (dlen))

how does the interpreter know what "j" is supposed to refer to when it
was not mentioned prior?



Prior value or not, j is the loop variable that steps over range(dlen) 
and refers to the numbers 0 to dlen-1 in turn.


Did you mean to ask something about the code below as well?

Emile





from random import randrange, choice
from string import ascii_lowercase as lc
from sys import maxsize
from time import ctime

tlds = ('com', 'edu', 'net', 'org', 'gov')

for i in range(randrange(5,11)):
 dtint=randrange(maxsize)#pick a random number to use to
generate random date in next line
 dtstr=ctime(dtint)  #date string
 llen=randrange(4,8) #login is shorter
 login=''.join(choice(lc) for j in range(llen))
 dlen=randrange(llen,13) #domain is longer
 dom="".join(choice(lc) for j in range (dlen))

print('{}::{}@{}.{}::{}-{}-{}'.format(dtstr,login,dom,choice(tlds),dtint,llen,dlen))



___
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] Question about login=''.join(choice(lc) for j in range(llen))

2012-04-03 Thread Khalid Al-Ghamdi
Hi,

The following code tries to generate some dummy data for regex exercises.
My question is in reference the line before last:

dom="".join(choice(lc) for j in range (dlen))

how does the interpreter know what "j" is supposed to refer to when it was
not mentioned prior?


from random import randrange, choice
from string import ascii_lowercase as lc
from sys import maxsize
from time import ctime

tlds = ('com', 'edu', 'net', 'org', 'gov')

for i in range(randrange(5,11)):
dtint=randrange(maxsize)#pick a random number to use to generate
random date in next line
dtstr=ctime(dtint)  #date string
llen=randrange(4,8) #login is shorter
login=''.join(choice(lc) for j in range(llen))
dlen=randrange(llen,13) #domain is longer
dom="".join(choice(lc) for j in range (dlen))

print('{}::{}@{}.{}::{}-{}-{}'.format(dtstr,login,dom,choice(tlds),dtint,llen,dlen))
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about input

2012-03-25 Thread Joel Goldstick
On Sun, Mar 25, 2012 at 11:52 AM, Asif Kazmi  wrote:
> The odd thing is that the same code runs perfectly in the Mac terminal, but
> incorrectly in Komodo Edit. In the latter, the input prompts are somehow
> being included  into the variables themselves somehow due to the way Komodo
> works.
>
> Thanks for the help. I've just taken to running the code in the Mac terminal
> which is working great.
>
> Asif

Are you sure that you are running python 3.x in each environment?  I'm
not familiar with Komodo, so I can't help you there, but in python
v2.x input attempts to evaluate the values you enter.  raw_input, on
the other hand returns your data as a string.  In python 3, input was
removed and raw_input's name was changed to input.

See if you have two different versions of python on your system.
>
> On Sun, Mar 25, 2012 at 9:45 AM, Joel Goldstick 
> wrote:
>>
>> On Sun, Mar 25, 2012 at 1:31 AM, Asif Kazmi  wrote:
>> > Hello,
>> >
>> > I'm going through Python Programming for the Absolute Beginner, 3rd
>> > edition,
>> > on a Mac with Python 3.2.
>> >
>> > In the second chapter, the book gives sample code that shows how a
>> > logical
>> > error can occur:
>> >
>> > # Trust Fund Buddy - Bad
>> > # Demonstrates a logical error
>> >
>> > print(
>> > """
>> >             Trust Fund Buddy
>> >
>> > Totals your monthly spending so that your trust fund doesn't run out
>> > (and you're forced to get a real job).
>> >
>> > Please enter the requested, monthly costs.  Since you're rich, ignore
>> > pennies
>> > and use only dollar amounts.
>> >
>> > """
>> > )
>> >
>> > car = input("Lamborghini Tune-Ups: ")
>> > rent = input("Manhattan Apartment: ")
>> > jet = input("Private Jet Rental: ")
>> > gifts = input("Gifts: ")
>> > food = input("Dining Out: ")
>> > staff = input("Staff (butlers, chef, driver, assistant): ")
>> > guru = input("Personal Guru and Coach: ")
>> > games = input("Computer Games: ")
>> >
>> > total = car + rent + jet + gifts + food + staff + guru + games
>> >
>> > print("\nGrand Total:", total)
>> >
>> > input("\n\nPress the enter key to exit.")
>> >
>> >
>> > This program should show the inputted numbers as a concatenation rather
>> > than
>> > a sum, I understand that is the mistake in the code. However, when I run
>> > it,
>> > it shows:
>> >
>> > Grand Total: 111Manhattan Apartment: 111Private Jet Rental: 111Gifts:
>> > 111Dining Out: 111Staff (butlers, chef, driver, assistant): 111Personal
>> > Guru
>> > and Coach: 111Computer Games: 111
>> >
>> > It appears to be adding the input prompt as part of the variables?
>> > except
>> > for car? What am I missing?
>> >
>> > Thanks,
>> > Asif
>> >
>> > ___
>> > Tutor maillist  -  Tutor@python.org
>> > To unsubscribe or change subscription options:
>> > http://mail.python.org/mailman/listinfo/tutor
>> >
>> Input returns a string in python 3.  So you are doing something like
>> '1' + '1' ... etc which will concatinate the strings.  Test it out by
>> typing in something other than a number for your inputs.
>>
>> Once you get that worked out, see what your code produces.
>>
>>
>> --
>> Joel Goldstick
>
>



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


Re: [Tutor] Question about input

2012-03-25 Thread Asif Kazmi
The odd thing is that the same code runs perfectly in the Mac terminal, but
incorrectly in Komodo Edit. In the latter, the input prompts are somehow
being included  into the variables themselves somehow due to the way Komodo
works.

Thanks for the help. I've just taken to running the code in the Mac
terminal which is working great.

Asif

On Sun, Mar 25, 2012 at 9:45 AM, Joel Goldstick wrote:

> On Sun, Mar 25, 2012 at 1:31 AM, Asif Kazmi  wrote:
> > Hello,
> >
> > I'm going through Python Programming for the Absolute Beginner, 3rd
> edition,
> > on a Mac with Python 3.2.
> >
> > In the second chapter, the book gives sample code that shows how a
> logical
> > error can occur:
> >
> > # Trust Fund Buddy - Bad
> > # Demonstrates a logical error
> >
> > print(
> > """
> > Trust Fund Buddy
> >
> > Totals your monthly spending so that your trust fund doesn't run out
> > (and you're forced to get a real job).
> >
> > Please enter the requested, monthly costs.  Since you're rich, ignore
> > pennies
> > and use only dollar amounts.
> >
> > """
> > )
> >
> > car = input("Lamborghini Tune-Ups: ")
> > rent = input("Manhattan Apartment: ")
> > jet = input("Private Jet Rental: ")
> > gifts = input("Gifts: ")
> > food = input("Dining Out: ")
> > staff = input("Staff (butlers, chef, driver, assistant): ")
> > guru = input("Personal Guru and Coach: ")
> > games = input("Computer Games: ")
> >
> > total = car + rent + jet + gifts + food + staff + guru + games
> >
> > print("\nGrand Total:", total)
> >
> > input("\n\nPress the enter key to exit.")
> >
> >
> > This program should show the inputted numbers as a concatenation rather
> than
> > a sum, I understand that is the mistake in the code. However, when I run
> it,
> > it shows:
> >
> > Grand Total: 111Manhattan Apartment: 111Private Jet Rental: 111Gifts:
> > 111Dining Out: 111Staff (butlers, chef, driver, assistant): 111Personal
> Guru
> > and Coach: 111Computer Games: 111
> >
> > It appears to be adding the input prompt as part of the variables? except
> > for car? What am I missing?
> >
> > Thanks,
> > Asif
> >
> > ___
> > Tutor maillist  -  Tutor@python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
> >
> Input returns a string in python 3.  So you are doing something like
> '1' + '1' ... etc which will concatinate the strings.  Test it out by
> typing in something other than a number for your inputs.
>
> Once you get that worked out, see what your code produces.
>
>
> --
> Joel Goldstick
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about input

2012-03-25 Thread Joel Goldstick
On Sun, Mar 25, 2012 at 1:31 AM, Asif Kazmi  wrote:
> Hello,
>
> I'm going through Python Programming for the Absolute Beginner, 3rd edition,
> on a Mac with Python 3.2.
>
> In the second chapter, the book gives sample code that shows how a logical
> error can occur:
>
> # Trust Fund Buddy - Bad
> # Demonstrates a logical error
>
> print(
> """
>             Trust Fund Buddy
>
> Totals your monthly spending so that your trust fund doesn't run out
> (and you're forced to get a real job).
>
> Please enter the requested, monthly costs.  Since you're rich, ignore
> pennies
> and use only dollar amounts.
>
> """
> )
>
> car = input("Lamborghini Tune-Ups: ")
> rent = input("Manhattan Apartment: ")
> jet = input("Private Jet Rental: ")
> gifts = input("Gifts: ")
> food = input("Dining Out: ")
> staff = input("Staff (butlers, chef, driver, assistant): ")
> guru = input("Personal Guru and Coach: ")
> games = input("Computer Games: ")
>
> total = car + rent + jet + gifts + food + staff + guru + games
>
> print("\nGrand Total:", total)
>
> input("\n\nPress the enter key to exit.")
>
>
> This program should show the inputted numbers as a concatenation rather than
> a sum, I understand that is the mistake in the code. However, when I run it,
> it shows:
>
> Grand Total: 111Manhattan Apartment: 111Private Jet Rental: 111Gifts:
> 111Dining Out: 111Staff (butlers, chef, driver, assistant): 111Personal Guru
> and Coach: 111Computer Games: 111
>
> It appears to be adding the input prompt as part of the variables? except
> for car? What am I missing?
>
> Thanks,
> Asif
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
Input returns a string in python 3.  So you are doing something like
'1' + '1' ... etc which will concatinate the strings.  Test it out by
typing in something other than a number for your inputs.

Once you get that worked out, see what your code produces.


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


[Tutor] Question about input

2012-03-24 Thread Asif Kazmi
Hello,

I'm going through Python Programming for the Absolute Beginner, 3rd
edition, on a Mac with Python 3.2.

In the second chapter, the book gives sample code that shows how a logical
error can occur:

# Trust Fund Buddy - Bad
# Demonstrates a logical error

print(
"""
Trust Fund Buddy

Totals your monthly spending so that your trust fund doesn't run out
(and you're forced to get a real job).

Please enter the requested, monthly costs.  Since you're rich, ignore
pennies
and use only dollar amounts.

"""
)

car = input("Lamborghini Tune-Ups: ")
rent = input("Manhattan Apartment: ")
jet = input("Private Jet Rental: ")
gifts = input("Gifts: ")
food = input("Dining Out: ")
staff = input("Staff (butlers, chef, driver, assistant): ")
guru = input("Personal Guru and Coach: ")
games = input("Computer Games: ")

total = car + rent + jet + gifts + food + staff + guru + games

print("\nGrand Total:", total)

input("\n\nPress the enter key to exit.")


This program should show the inputted numbers as a concatenation rather
than a sum, I understand that is the mistake in the code. However, when I
run it, it shows:

Grand Total: 111Manhattan Apartment: 111Private Jet Rental: 111Gifts:
111Dining Out: 111Staff (butlers, chef, driver, assistant): 111Personal
Guru and Coach: 111Computer Games: 111

It appears to be adding the input prompt as part of the variables? except
for car? What am I missing?

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


Re: [Tutor] question on self

2012-03-13 Thread wesley chun
i want to expand specifically on steve's response and note the big
distinction that needs to be made for everyone is that this is primary the
difference between calling a *function* and calling a *method* (which is a
function that belongs to/defined for a class).

with that instance (self), that method is considered "bound," and Python
automagically passes it in as the first argument to that method (self). if
you wish to call an *unbound* method, you need to pass an instance on your
own *and* reference it via its class, i.e., YourClass.TakeTurns(self) --
readability takes a blow there.

btw, if you want to make just a function call *and* that function doesn't
have much to do with the class, then just define it as a function. a
seldomly-used alternative is to make it a static method (using the
@staticmethod decorator) -- this lets you define a method within a class
but pretend it's like a function (where you don't need to use the instance
[self]).

cheers,
--wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
http://corepython.com

wesley.chun : wescpy-gmail.com : @wescpy/+wescpy
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question on self

2012-03-13 Thread Bill Allen
This little thread on the usage of self references when calling class instance 
methods and attributes was excellent, one of the best I have seen.

Thanks,
Bill Allen
Sent from my iPhone

On Mar 12, 2012, at 3:56, Alan Gauld  wrote:

> On 12/03/12 02:02, Michael Lewis wrote:
> 
>> I have another method called take turns (not shown for brevity
>> purposes). When I want to call it, why can't I just call it like a
>> function and use TakeTurns() instead of self.TakeTurns()?
> 
> The Steve's have given technical answers, its also stylistically
> better because it removed ambiguity for the reader as well as
> for Python.
> 
> Many corporate style guides advocate using this same style
> when using C++ or Java to make it explicit when you are using
> a class attribute rather than a local or global value/function.
> 
> It improves code clarity and therefore reduces potential bugs
> and speeds up maintenance for a tiny loss in initial coding
> productivity.
> 
> -- 
> Alan G
> 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
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question on self

2012-03-12 Thread Alan Gauld

On 12/03/12 02:02, Michael Lewis wrote:


I have another method called take turns (not shown for brevity
purposes). When I want to call it, why can't I just call it like a
function and use TakeTurns() instead of self.TakeTurns()?


The Steve's have given technical answers, its also stylistically
better because it removed ambiguity for the reader as well as
for Python.

Many corporate style guides advocate using this same style
when using C++ or Java to make it explicit when you are using
a class attribute rather than a local or global value/function.

It improves code clarity and therefore reduces potential bugs
and speeds up maintenance for a tiny loss in initial coding
productivity.

--
Alan G
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] question on self

2012-03-11 Thread Steve Willoughby

On 11-Mar-12 20:03, Steven D'Aprano wrote:

On Sun, Mar 11, 2012 at 07:02:11PM -0700, Michael Lewis wrote:

Why do I have to use "self.example" when calling a method inside a class?

For example:

 def Play(self):
 '''find scores, reports winners'''
 self.scores = []
 for player in range(self.players):
 print
 print 'Player', player + 1
 self.scores.append(self.TakeTurns())

I have another method called take turns (not shown for brevity purposes).
When I want to call it, why can't I just call it like a function and use
TakeTurns() instead of self.TakeTurns()?


Steven's notes about scoping rules are one reason.  Another is the 
matter of object instance binding.  When you call a method, you're not 
just calling a regular function.  You're calling a function bound to a 
particular object, so by saying self.TakeTurns(), Python knows that the 
object "self" is invoking that method, not some other instance of the 
Play class.  That method then can access all of that specific object's 
attributes as necessary.


--
Steve Willoughby / st...@alchemy.com
"A ship in harbor is safe, but that is not what ships are built for."
PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question on self

2012-03-11 Thread Steven D'Aprano
On Sun, Mar 11, 2012 at 07:02:11PM -0700, Michael Lewis wrote:
> Why do I have to use "self.example" when calling a method inside a class?
> 
> For example:
> 
> def Play(self):
> '''find scores, reports winners'''
> self.scores = []
> for player in range(self.players):
> print
> print 'Player', player + 1
> self.scores.append(self.TakeTurns())
> 
> I have another method called take turns (not shown for brevity purposes).
> When I want to call it, why can't I just call it like a function and use
> TakeTurns() instead of self.TakeTurns()?

When you call range() inside a method, as you do above, do you 
expect to get the global range() function, or the self.range() 
method (which likely doesn't exist)?

Same for len(), or any other built-in or global.

Similarly, how do you expect Python to distinguish between a persistent 
attribute, like self.scores, and a local variable, like player?

Since Python can't read your mind, one way or another you have to 
explicitly tell the compiler which of the two name resolution 
orders to use:

(1) The normal function scope rules:

- local variables have priority over:
- non-locals, which have priority over:
- globals, which have priority over:
- built-ins;

(2) or the attribute search rules, which is quite compilicated but a 
simplified version is:

- instance attributes or methods
- class attributes or methods
- superclass attributes or method
- computed attributes or methods using __getattr__

Python refuses to guess which one you want, since any guess is likely to 
be wrong 50% of the time. Instead, Python's design is to always use 
function scope rules, and if you want attributes or methods, you have to 
explicitly ask for them. This makes MUCH more sense than having to 
explicitly flag local variables!

Other languages made other choices. For instance, you might demand that 
the programmer declare all their variables up-front, and all their 
instance attributes. Then the compiler can tell at compile-time that 
range is a built-in, that player is a local variable, and that TakeTurns 
is an instance attribute. That's a legitimate choice, and some languages 
do it that way.

But having programmed in some of these other languages, give me Python's 
lack of declarations anytime!

Since all names (variables and attributes) in Python are generated at 
runtime, the compiler normally cannot tell what the scope of a name is 
until runtime (with a few exceptions).


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


[Tutor] question on self

2012-03-11 Thread Michael Lewis
Why do I have to use "self.example" when calling a method inside a class?

For example:

def Play(self):
'''find scores, reports winners'''
self.scores = []
for player in range(self.players):
print
print 'Player', player + 1
self.scores.append(self.TakeTurns())

I have another method called take turns (not shown for brevity purposes).
When I want to call it, why can't I just call it like a function and use
TakeTurns() instead of self.TakeTurns()?

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


Re: [Tutor] Question about writing to Excel with slavic characters

2012-03-09 Thread Marko Limbek
Hi Walter

It is as you say. Thanks for long explanation.
I am using the newer version.
Now I also understand difference between single underscore and double
underscore. I would still have problems if I would want to programme
them for instance.

Well I always try to be independent and I want to answer the questions
by myself. Learning the tutorial by heart is also not my way. Maybe I
need just to understand it better and understand better the whole
philosophy of private and public methods. And what is __init__ method
and __enter__ method and so on.
I was just asking of that getNumberofVariables() method, because I
wanted to run the methods my self and see if I get the labels I wanted
by myself. I wouldn't want to ask the author directly does this
programme does this or that because that might be silly questions
because the answer would be, 'well of course it does, run this and
this method' and you will see. I don't want to consume too much time
of the people. So I wanted to check first. As an amateur as I am.
Nobody really trained me how to programme except for in the first
years at the faculty some 10 years ago, but at that time I was not
that interested in programming.

Now we are resolving the issue directly with Albert.

Have a nice day,
Marko


On Fri, Mar 9, 2012 at 11:49 AM, Walter Prins  wrote:
> Hi Marko,
>
> On 9 March 2012 08:34, Marko Limbek  wrote:
>>  File "C:\Dropbox\Exc_MarkoL_Zenel\Python\crosstabs\src\src\rw.py",
>> line 715, in 
>>    mySavReaderObject.getNumberofVariables(savFileName,
>> mySavReaderObject.fh, mySavReaderObject.spssio)
>> AttributeError: 'SavReader' object has no attribute 'spssio'
>>
>> So the methods must really be somewhat internal.
>
> Python doesn't enforce access levels like some other languages do
> which means effectively, any member of any object can in principle be
> accessed.  By "gentlemans agreement", members with a name starting
> with a single underscore are supposed to be considered private
> (although you can still ignore this agreement and access them anyway)
> while members with double underscores get some behind the scenes
> assistance to ensure privateness and name uniqueness via "name
> mangling".  (There's a couple of other minor behavioural differences,
> but the point stands -- there's no preventing you as programmer from
> accessing "private" members of a class if you insist to do so.  But
> then it's doubly your problem if that gets you into trouble ;) )
>
> Anyway, the message then really means what it says -- The SavReader
> object instance you're using really does not have an spssio member
> (there should be no problem accessing it if it was there so I must
> interpret that message to mean what it says.)   I'm not sure why this
> would be the case -- perhaps we're not looking/using the same version
> of the reader class and the member name has changed?  (I previously
> guessed/assumed  that you were using the following version, or
> something close enough to it, given here:
> http://code.activestate.com/recipes/577650-python-reader-for-spss-sav-files/
>  Looking back I see you're actually using a slightly newer version
> from here: 
> http://code.activestate.com/recipes/577811-python-reader-writer-for-spss-sav-files-linux-mac-/
> But, everything I've said appears to still hold true about the updated
> version, so can you clarify which version you're currently using?)
>
> Regardless, the error simple enough to troubleshoot -- have a look at
> *your* version of the SavReader class, and find out what the member
> name should in fact be.  There are calls to e.g.
> getNumberofVariables() in the class itself, from which you can
> determine what the object data/field/variable member is that holds the
> value to pass to the spssio parameter of getNumberofVariables().
>
> But, I have to repeat: The value that you get from
> getNumberofVariables() is the exact same value that you get inside of
> the numVars variable after calling:
>
>  numVars, nCases, varNames, varTypes, printTypesFile,
> printTypeLabels, varWids = mySavReaderObj.getSavFileInfo()
>
> You can see this will be the case if you read the code:
> 1) The __init__ method assigns self.numVars_ from the result of
> calling self._readBasicSavFileInfo().
> 2) This in turn calls on self.getNumberofVariables() as follows:
>  numVars = self.getNumberofVariables(self.fh, self.spssio)[1]
> ... and that local variable numVars is what is returned and ends up in
> the object member self.numVars_.
> 3) Then, looking at getSavFileInfo() you can see that it in turn
> simply returns self.numVars_,
> 4) In other words it returns the same value that it previously
> retrieved using self.getNumberofVariables().
>
> So, the 2 ways are functionally identical w.r.t. the retrieval of the
> "NumberofVariables".  The only differences are that a) with the latter
> call you get a bunch of other stuff besides the number of variables,
> and b) With the latter call you don't have to worry about spssio or fh
> parameters 

Re: [Tutor] Question about writing to Excel with slavic characters

2012-03-09 Thread Walter Prins
Hi Marko,

On 9 March 2012 08:34, Marko Limbek  wrote:
>  File "C:\Dropbox\Exc_MarkoL_Zenel\Python\crosstabs\src\src\rw.py",
> line 715, in 
>    mySavReaderObject.getNumberofVariables(savFileName,
> mySavReaderObject.fh, mySavReaderObject.spssio)
> AttributeError: 'SavReader' object has no attribute 'spssio'
>
> So the methods must really be somewhat internal.

Python doesn't enforce access levels like some other languages do
which means effectively, any member of any object can in principle be
accessed.  By "gentlemans agreement", members with a name starting
with a single underscore are supposed to be considered private
(although you can still ignore this agreement and access them anyway)
while members with double underscores get some behind the scenes
assistance to ensure privateness and name uniqueness via "name
mangling".  (There's a couple of other minor behavioural differences,
but the point stands -- there's no preventing you as programmer from
accessing "private" members of a class if you insist to do so.  But
then it's doubly your problem if that gets you into trouble ;) )

Anyway, the message then really means what it says -- The SavReader
object instance you're using really does not have an spssio member
(there should be no problem accessing it if it was there so I must
interpret that message to mean what it says.)   I'm not sure why this
would be the case -- perhaps we're not looking/using the same version
of the reader class and the member name has changed?  (I previously
guessed/assumed  that you were using the following version, or
something close enough to it, given here:
http://code.activestate.com/recipes/577650-python-reader-for-spss-sav-files/
  Looking back I see you're actually using a slightly newer version
from here: 
http://code.activestate.com/recipes/577811-python-reader-writer-for-spss-sav-files-linux-mac-/
But, everything I've said appears to still hold true about the updated
version, so can you clarify which version you're currently using?)

Regardless, the error simple enough to troubleshoot -- have a look at
*your* version of the SavReader class, and find out what the member
name should in fact be.  There are calls to e.g.
getNumberofVariables() in the class itself, from which you can
determine what the object data/field/variable member is that holds the
value to pass to the spssio parameter of getNumberofVariables().

But, I have to repeat: The value that you get from
getNumberofVariables() is the exact same value that you get inside of
the numVars variable after calling:

  numVars, nCases, varNames, varTypes, printTypesFile,
printTypeLabels, varWids = mySavReaderObj.getSavFileInfo()

You can see this will be the case if you read the code:
1) The __init__ method assigns self.numVars_ from the result of
calling self._readBasicSavFileInfo().
2) This in turn calls on self.getNumberofVariables() as follows:
  numVars = self.getNumberofVariables(self.fh, self.spssio)[1]
... and that local variable numVars is what is returned and ends up in
the object member self.numVars_.
3) Then, looking at getSavFileInfo() you can see that it in turn
simply returns self.numVars_,
4) In other words it returns the same value that it previously
retrieved using self.getNumberofVariables().

So, the 2 ways are functionally identical w.r.t. the retrieval of the
"NumberofVariables".  The only differences are that a) with the latter
call you get a bunch of other stuff besides the number of variables,
and b) With the latter call you don't have to worry about spssio or fh
parameters (because they're absent/not required when calling
getSavFileInfo() and c) with the latter call the actual retrieval of
the number of variables happened slightly earlier on when the
SavReader object was created, while with the direct call to
getNumberofVariables() it is presumably read again directly from the
file.

So, I think you need to stop fixating on the getNumberofVariables()
method as it's not, I suspect, the solution to your real problem like
you seem to think, and it is also introducing a distraction (the
parameters issue) since it's not really the intended way for you to
use this class.  (Not that you absolutely cannot use it if you're
determined to do so, as I've already tried to explain, but it's just
probably just easier to go with the intended means of use for now
given that there's functionally no difference in the result up to this
point, at least that I can see.)

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


Re: [Tutor] Question about writing to Excel with slavic characters

2012-03-09 Thread Marko Limbek
Hi Walter

I understand, thank you. Maybe I am trying to do what is not meant to be done.
I tried as you suggested

mySavReaderObject = SavReader(savFileName)
mySavReaderObject.getNumberofVariables(savFileName,
mySavReaderObject.fh, mySavReaderObject.spssio)

but it won't work

  File "C:\Dropbox\Exc_MarkoL_Zenel\Python\crosstabs\src\src\rw.py",
line 715, in 
mySavReaderObject.getNumberofVariables(savFileName,
mySavReaderObject.fh, mySavReaderObject.spssio)
AttributeError: 'SavReader' object has no attribute 'spssio'

So the methods must really be somewhat internal.

The information that I get in
numVars, nCases, varNames, varTypes, printTypesFile, printTypeLabels, varWids
is not sufficient to me.

What I need from this programme are the labels that are in the column
'Values'  in SPSS 'Variable view'.
What is the most important is that unicode characters like 'č', 'š',
'ž', in the labels can be read. This is the only reason why I am
touching this programme.
I will forward the question to Albert.

Thank you,

Marko






On Thu, Mar 8, 2012 at 5:18 PM, Walter Prins  wrote:
> Hi Marko,
>
> I'm going out on a limb here as I know next to nothing about either
> SPSS or Albert-Jan's wrapper module, and so with that caveat, some
> comments/observations:
>
> On 8 March 2012 14:59, Marko Limbek  wrote:
>> I overcame commenting. I managed to read my own file and print it. Now
>> I am trying to use method getNumberofVariables()  but unsuccesfully.
>> First way
>>
>> SavReader(savFileName).getNumberofVariables()
>>
>> gives me this error
>>
>> Traceback (most recent call last):
>>  File "C:\Dropbox\Exc_MarkoL_Zenel\Python\crosstabs\src\src\rw.py",
>> line 660, in 
>>    SavReader(savFileName).getNumberofVariables()
>> TypeError: getNumberofVariables() takes exactly 3 arguments (1 given)
>>
>>
>>
>> Second way
>>
>> getNumberofVariables(savFileName, fh, spssio)
>>
>> gives me this error
>>
>> Traceback (most recent call last):
>>  File "C:\Dropbox\Exc_MarkoL_Zenel\Python\crosstabs\src\src\rw.py",
>> line 660, in 
>>    getNumberofVariables(savFileName, fh, spssio)
>> NameError: name 'getNumberofVariables' is not defined
>
> The short answer:
> ==
> Don't use getNumberofVariables, use the script as demonstrated at the
> bottom of the script in the "if __name__ == "__main__" section.  I
> suppose something like this should do (I've modified it slightly to
> make it a bit more obvious what's happening):
>
> ## - Get some basic file info
> savFileName = r"C:\Program
> Files\IBM\SPSS\Statistics\19\Samples\English\Employee data.sav"
> mySavReaderObj = SavReader(savFileName)
> numVars, nCases, varNames, varTypes, printTypesFile, printTypeLabels,
> varWids = \
>    mySavReaderObj.getSavFileInfo()
> #Now the number of variables is presumably in numVars...
>
>
> The longer answer:
> ==
> Firstly, getNumberofVariables() is defined as a class instance method.
>  This means you can only ever call it on an object instance of that
> class. It is not a standalone function that can be called freestanding
> as you tried to do in your latter attempt.  That is why you got the
> "not defined" error -- There is no freestanding function by that name
> (even if there happens to be a /method/ by that name inside the
> SavReader class.) so Python complained as such.
>
> Your prior attempt, which as you noticed requires to have parameters
> fh and spssio supplied appears to me to be effectively somewhat of an
> internal/private/helper method that is written in the style of a
> function, so consequently the method has no external dependencies on
> any state in the object/class and hence has to have the spssio and fh
> supplied when it's called.  You can see elsewhere in the class when
> this method is called, the object itself keeps track of the fh and the
> sspsio and so passes these into the method as required.
>
> >From this you can infer that you'd be able to do the same and thus
> successfully call getNumberofVariables() by retrieving the fh and
> sspsio from your SavReader object (e.g. what I called mySavReaderObj
> above), by passing in mySavReaderObj.fh and mySavREaderObj.spssio when
> calling mySavReaderObj.getNumberofVariables().  But, as per the short
> answer, you probably don't want to do that.
>
> As an aside it also then follows it would be possible to
> rewrite/refactor the getNumberofVariables() method (and indeed several
> others) to remove the fh and sspsio parameters, by having them picked
> up directly from the object instance when required.   Debateably, it
> might be an improvement that makes the code a bit more object oriented
> and less surprising to use.
>
> HTH,
>
> Walter
> ___
> 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:

Re: [Tutor] Question about writing to Excel with slavic characters

2012-03-08 Thread Walter Prins
Hi Marko,

I'm going out on a limb here as I know next to nothing about either
SPSS or Albert-Jan's wrapper module, and so with that caveat, some
comments/observations:

On 8 March 2012 14:59, Marko Limbek  wrote:
> I overcame commenting. I managed to read my own file and print it. Now
> I am trying to use method getNumberofVariables()  but unsuccesfully.
> First way
>
> SavReader(savFileName).getNumberofVariables()
>
> gives me this error
>
> Traceback (most recent call last):
>  File "C:\Dropbox\Exc_MarkoL_Zenel\Python\crosstabs\src\src\rw.py",
> line 660, in 
>    SavReader(savFileName).getNumberofVariables()
> TypeError: getNumberofVariables() takes exactly 3 arguments (1 given)
>
>
>
> Second way
>
> getNumberofVariables(savFileName, fh, spssio)
>
> gives me this error
>
> Traceback (most recent call last):
>  File "C:\Dropbox\Exc_MarkoL_Zenel\Python\crosstabs\src\src\rw.py",
> line 660, in 
>    getNumberofVariables(savFileName, fh, spssio)
> NameError: name 'getNumberofVariables' is not defined

The short answer:
==
Don't use getNumberofVariables, use the script as demonstrated at the
bottom of the script in the "if __name__ == "__main__" section.  I
suppose something like this should do (I've modified it slightly to
make it a bit more obvious what's happening):

## - Get some basic file info
savFileName = r"C:\Program
Files\IBM\SPSS\Statistics\19\Samples\English\Employee data.sav"
mySavReaderObj = SavReader(savFileName)
numVars, nCases, varNames, varTypes, printTypesFile, printTypeLabels,
varWids = \
mySavReaderObj.getSavFileInfo()
#Now the number of variables is presumably in numVars...


The longer answer:
==
Firstly, getNumberofVariables() is defined as a class instance method.
 This means you can only ever call it on an object instance of that
class. It is not a standalone function that can be called freestanding
as you tried to do in your latter attempt.  That is why you got the
"not defined" error -- There is no freestanding function by that name
(even if there happens to be a /method/ by that name inside the
SavReader class.) so Python complained as such.

Your prior attempt, which as you noticed requires to have parameters
fh and spssio supplied appears to me to be effectively somewhat of an
internal/private/helper method that is written in the style of a
function, so consequently the method has no external dependencies on
any state in the object/class and hence has to have the spssio and fh
supplied when it's called.  You can see elsewhere in the class when
this method is called, the object itself keeps track of the fh and the
sspsio and so passes these into the method as required.

>From this you can infer that you'd be able to do the same and thus
successfully call getNumberofVariables() by retrieving the fh and
sspsio from your SavReader object (e.g. what I called mySavReaderObj
above), by passing in mySavReaderObj.fh and mySavREaderObj.spssio when
calling mySavReaderObj.getNumberofVariables().  But, as per the short
answer, you probably don't want to do that.

As an aside it also then follows it would be possible to
rewrite/refactor the getNumberofVariables() method (and indeed several
others) to remove the fh and sspsio parameters, by having them picked
up directly from the object instance when required.   Debateably, it
might be an improvement that makes the code a bit more object oriented
and less surprising to use.

HTH,

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


Re: [Tutor] Question about writing to Excel with slavic characters

2012-03-08 Thread Marko Limbek
On Wed, Mar 7, 2012 at 11:36 PM, Steven D'Aprano  wrote:
> Marko Limbek wrote:
>
>> I put the recommended code
>>
>> savFileName =
>> "C:/dropbox/Exc_MarkoL_Zenel/Valicon/crosstabs/Tabela/ipk108_kosovo_data_finale_c1-1.sav"
>> with SavReader(savFileName) as sav:
>>    header = sav.next()
>>    for line in sav:
>>        process(line)
>>
>>
>> but I am get errors
>
>
>
> Will you tell us what errors, or should we just guess?
>
> Since I love guessing games, let me try... my guess is that you get
>
> AttributeError: 'SavReader' object has no attribute 'next'
>
> Am I close? If so, try using next(sav) instead of sav.next().


I overcame commenting. I managed to read my own file and print it. Now
I am trying to use method getNumberofVariables()  but unsuccesfully.
First way

SavReader(savFileName).getNumberofVariables()

gives me this error

Traceback (most recent call last):
  File "C:\Dropbox\Exc_MarkoL_Zenel\Python\crosstabs\src\src\rw.py",
line 660, in 
SavReader(savFileName).getNumberofVariables()
TypeError: getNumberofVariables() takes exactly 3 arguments (1 given)



Second way

getNumberofVariables(savFileName, fh, spssio)

gives me this error

Traceback (most recent call last):
  File "C:\Dropbox\Exc_MarkoL_Zenel\Python\crosstabs\src\src\rw.py",
line 660, in 
getNumberofVariables(savFileName, fh, spssio)
NameError: name 'getNumberofVariables' is not defined


Why there needs to be fh and spssio?
I would like to be able to know how to use all the methods to run and
test them and see, if any of them can give me labels from the file
instead of just pure numbers, before I start asking questions if there
is any method that can read labels. I am really sorry but I tried to
find answers to that in the tutorial.
I would like to read labels with such characters like čšž and not just
read pure numbers.


>
>
>> I have however managed to compile the programme in the module, I just
>> had to comment more than 20 lines (because of that problem with
>> "employee data.sav" ).
>> I also don't know, if it was right to comment all those lines. Without
>> commenting them I can't even compile the module.
>
>
>
> Marko, it seems that you don't know how to program Python. Perhaps you
> should do a Python tutorial or two so you can fix the code instead of just
> commenting out lines.
>
> Perhaps start here: http://docs.python.org/tutorial/
>


I have been using Python for a few months now and I am a
mathematician, so I have done some programming. It is true however
that I am not trained programmer. So please excuse dumb questions. But
I have fixed the code so far that I can read and print.

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


Re: [Tutor] Question about writing to Excel with slavic characters

2012-03-07 Thread Steven D'Aprano

Marko Limbek wrote:


I put the recommended code

savFileName = 
"C:/dropbox/Exc_MarkoL_Zenel/Valicon/crosstabs/Tabela/ipk108_kosovo_data_finale_c1-1.sav"
with SavReader(savFileName) as sav:
header = sav.next()
for line in sav:
process(line)


but I am get errors



Will you tell us what errors, or should we just guess?

Since I love guessing games, let me try... my guess is that you get

AttributeError: 'SavReader' object has no attribute 'next'

Am I close? If so, try using next(sav) instead of sav.next().




I have however managed to compile the programme in the module, I just
had to comment more than 20 lines (because of that problem with
"employee data.sav" ).
I also don't know, if it was right to comment all those lines. Without
commenting them I can't even compile the module.



Marko, it seems that you don't know how to program Python. Perhaps you should 
do a Python tutorial or two so you can fix the code instead of just commenting 
out lines.


Perhaps start here: http://docs.python.org/tutorial/


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


Re: [Tutor] Question about writing to Excel with slavic characters

2012-03-07 Thread Marko Limbek
Hi,

I have been trying to use that programme but without success.
In Eclipse you usually create new project in two steps, first you
create new Pydev project, then inside you create new Pydev module.
I have created new project and new module 'crosstabs', where I want to
read spss file. My programme is the module.
Now I have put this ReaderWriter programme into the same Pydev project
as a another new module called 'rw' and then imported it into my
module 'crosstabs' with

import rw
from rw import SavReader

I don't even know, if I did that correctly. Actually I don't even know
how to implement that programme.
I put the recommended code

savFileName = 
"C:/dropbox/Exc_MarkoL_Zenel/Valicon/crosstabs/Tabela/ipk108_kosovo_data_finale_c1-1.sav"
with SavReader(savFileName) as sav:
header = sav.next()
for line in sav:
process(line)


but I am get errors



I have however managed to compile the programme in the module, I just
had to comment more than 20 lines (because of that problem with
"employee data.sav" ).
I also don't know, if it was right to comment all those lines. Without
commenting them I can't even compile the module.


Maybe someone can tell me, how to actually implement that programme?
Where to put it in my Eclipse?


Is this programm ethe best way to read spss with Python?


Thank you so much,

Marko





On Tue, Mar 6, 2012 at 4:53 PM, Marko Limbek  wrote:
> Hi Albert
>
> Two notes
> first I have used the promising looking package memics and the result
> is the same as foreign package. Reading in R is fine, but reading in
> rpy on Python27 unfortunatelly I get funny characters again like
> PRI�TINA
>
> second I have to run your programme and I get the following errors,
> that I send in attachment as printscreen. There is a file "employee
> data.sav" that I don't have and if I define my own file, I am asked in
> the next step about the variable "id" that I also don't have. So I
> would like to ask for your advise.
>
> Thanks,
> Marko
>
>
>
> On Mon, Mar 5, 2012 at 8:20 PM, Albert-Jan Roskam  wrote:
>> Hi,
>>
>> The R package foreign, in particular the read.spss function has some known
>> problems reading spss system files. The memisc package also has a function
>> to read .sav files. The big advantage of that function is that you can
>> select rows and columns prior to actually reading the data into memory.
>>
>> If you're just using R and Rpy to read .sav files, you could also consider
>> using a Python program that I wrote a while ago:
>> http://code.activestate.com/recipes/577811-python-reader-writer-for-spss-sav-files-linux-mac-/
>> It runs on Windows, Mac and Linux and requires no installation of spss. I'd
>> be interested to hear your experiences.
>>
>> Regards,
>> Albert-Jan
>>
>> ~~
>> All right, but apart from the sanitation, the medicine, education, wine,
>> public order, irrigation, roads, a
>> fresh water system, and public health, what have the Romans ever done for
>> us?
>> ~~
>>
>> 
>> From: Marko Limbek 
>> To: cwi...@compuscan.co.za
>> Cc: tutor@python.org
>> Sent: Monday, March 5, 2012 2:05 PM
>> Subject: Re: [Tutor] Question about writing to Excel with slavic characters
>>
>> Thank you!
>>
>> That was easy. Now I have another problem.
>> I use RPy and read the spss database with method read.spss inside a
>> nested R code in Python, that looks like that:
>>
>>
>> import rpy
>>
>> r("""
>>
>> library(foreign)
>>
>> baza <- read.spss(""" + analysis[0] + """)
>>
>> print(baza$demo_izob0)
>>
>> """)
>>
>> Now when my text data labels in spss have slavic characters, they are
>> not recognised and output is something like that:
>>
>> stiriletna srednja �ola
>> nedokon�ana osnovna �ola
>>
>>
>> What should I do here?
>>
>>
>> Thanks a lot,
>>
>>
>> Marko
>>
>>
>>
>>
>> On Mon, Mar 5, 2012 at 1:46 PM, Christian Witts 
>> wrote:
>>> On 2012/03/05 02:37 PM, Marko Limbek wrote:
>>>
>>> Hi everyone.
>>>
>>>
>>> I am new to list and few months old to Python. I am writing some text
>>> to Excel and I open the new book and try to write to the book and the
>>> save it using
>>>
>>> book.s

Re: [Tutor] question about operator overloading

2012-03-06 Thread Joel Goldstick
On Tue, Mar 6, 2012 at 7:05 AM, Albert-Jan Roskam  wrote:
> From: Steven D'Aprano 
> To: tutor@python.org
> Sent: Tuesday, March 6, 2012 1:58 AM
>
> Subject: Re: [Tutor] question about operator overloading
>
> Alan Gauld wrote:
>
>> On 05/03/12 21:25, Dave Angel wrote:
>>
>>> It's not clear what __add__() should mean for physical files.
>>
>> My guess would be similar to the cat operator in Unix:
>>
>> $ cat file1, file2 > file3
>>
>> is equivalent to
>>
>> file3 = file1 + file2
>>
>> But of course, thats just my interpretation of file addition...
>
> I think that's what Albert-Jan is probably thinking, but the two models are
> not quite the same. I think that what he wants is probably closer to
> something like the fileinput module. I think what he wants is to avoid this:
> -> First off, thank you all for your replies, including the replies
> after this mail. And sorry for top-posting in an earlier mail
> -> And yes indeed Steven and Alan, this is what I had in mind.
> for f in (file1, file2, file3, file4):
>     for record in f:
>         process(record)
>
> in favour of this:
>
> all_the_files = file1 + file2 + file3 + file4  # merge file contents
> for record in all_the_files:
>     process(record)
>
> Albert-Jan, am I close? If not, please explain what you are trying to
> accomplish.
> > What I had in mind was something like Peter Otten suggested:
> merged = file1 + file2
> merged.save_as(filename)
> Your solution looks intuitive, but won't "all_the_files" become very large
> if file1 through file4 contain, say, 100 billion values each?
>
>
> If the files are small, the easy way is to just read their contents, add
> them together as strings or lists, and then process the lot. But if the
> files are big, or you want to process them on-demand instead of up-front,
> you need an approach similar to fileinput.
> > see above. Btw, contrary to what somebody in this thread said, Spss
> files are binary files, not text files.

I chimed in with an assumption that these are were text files.  Since
i wasn't right assuming that, and if I read the discussion correctly
there are two methods being contemplated.  One way is to read a file,
process it, write the result to an output file, read the next file,
process it and append to the output file.  The second method is to
concatinate all of the input files, then open it up and process it.

But, if the spss files aren't text, then I assume they have some
structure that might not be concatinatable.  Not sure if that is a
word.
>
>
> Personally, all these Reader and Append objects make my brain hurt, and I
> hardly ever use operator overloading, except perhaps for numeric types.
> Reader objects, I can just get. But "Append" objects?
>
> This may be useful:
>
> http://steve-yegge.blogspot.com.au/2006/03/execution-in-kingdom-of-nouns.html
> > Nice one ;-))
>
> and also itertools:
>
>
> from itertools import chain
> merged = chain(file1, file2, file3, file4)
> for record in merged:
>     process(record)
> > Very, *very* useful function, thank you!
> > this is (incomplete) code that I created without bothering about
> __add__:
> with SavWriter(mergedSavFileName, varNames, varTypes) as sav_merged:
>   for savFileName in glob.glob("d:/temp/*.sav"):
>     with SavReader(savFileName) as sav_r:
>   header = sav_r.next()
>   for row in sav_r:
>     sav_merged.writerow(row)
> http://code.activestate.com/recipes/577811-python-reader-writer-for-spss-sav-files-linux-mac-/
> ---> Maybe I am making my life too difficult by trying to use __add__?
>
> -- Steven
> ___
> 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
>



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


Re: [Tutor] question about operator overloading

2012-03-06 Thread Albert-Jan Roskam
From: Steven D'Aprano 
To: tutor@python.org 
Sent: Tuesday, March 6, 2012 1:58 AM
Subject: Re: [Tutor] question about operator overloading

Alan Gauld wrote:
>> On 05/03/12 21:25, Dave Angel wrote:
>> 
>>> It's not clear what __add__() should mean for physical files.
>> 
>> My guess would be similar to the cat operator in Unix:
>> 
>> $ cat file1, file2 > file3
>> 
>> is equivalent to
>> 
>> file3 = file1 + file2
>> 
>> But of course, thats just my interpretation of file addition...
>
>I think that's what Albert-Jan is probably thinking, but the two models are 
>not quite the same. I think that what he wants is probably closer to something 
>like the fileinput module. I think what he wants is to avoid this:
>-> First off, thank you all for your replies, including the replies after 
>this mail. And sorry for top-posting in an earlier mail
>-> And yes indeed Steven and Alan, this is what I had in mind.
>for f in (file1, file2, file3, file4):
>    for record in f:
>        process(record)
>
>in favour of this:
>
>all_the_files = file1 + file2 + file3 + file4  # merge file contents
>for record in all_the_files:
>    process(record)
>
>Albert-Jan, am I close? If not, please explain what you are trying to 
>accomplish.
>> What I had in mind was something like Peter Otten suggested:
>merged = file1 + file2
>merged.save_as(filename)
>Your solution looks intuitive, but won't "all_the_files" become very large if 
>file1 through file4 contain, say, 100 billion values each?
>
>If the files are small, the easy way is to just read their contents, add them 
>together as strings or lists, and then process the lot. But if the files are 
>big, or you want to process them on-demand instead of up-front, you need an 
>approach similar to fileinput.
>> see above. Btw, contrary to what somebody in this thread said, Spss 
>files are binary files, not text files.
>
>Personally, all these Reader and Append objects make my brain hurt, and I 
>hardly ever use operator overloading, except perhaps for numeric types. Reader 
>objects, I can just get. But "Append" objects?
>
>This may be useful:
>
>http://steve-yegge.blogspot.com.au/2006/03/execution-in-kingdom-of-nouns.html
>> Nice one ;-))
>
>and also itertools:
>
>
>from itertools import chain
>merged = chain(file1, file2, file3, file4)
>for record in merged:
>    process(record)
>> Very, *very* useful function, thank you!
>> this is (incomplete) code that I created without bothering about __add__:
>with SavWriter(mergedSavFileName, varNames, varTypes) as sav_merged:
>  for savFileName in glob.glob("d:/temp/*.sav"):
>    with SavReader(savFileName) as sav_r:
>  header = sav_r.next()
>  for row in sav_r:
>    sav_merged.writerow(row)
>http://code.activestate.com/recipes/577811-python-reader-writer-for-spss-sav-files-linux-mac-/
>---> Maybe I am making my life too difficult by trying to use __add__?
>
>-- Steven
>___
>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] question about operator overloading

2012-03-06 Thread Alan Gauld

On 06/03/12 02:42, Dave Angel wrote:


My guess would be similar to the cat operator in Unix:

file3 = file1 + file2



So somehow assigning the object to file3 will write the data to a file
by the name "file3" ? I know about __add__(), but didn't know we had
__assign__()


We don't need any special assign behavior, its just standard Python 
assignment of the returned object to a name.


class MyFile(file):

   def __add__(self, file2):
  newFile = MyFile('foo.dat','wb')
  newFile.write(self.read())
  newFile.write(file2.read())
  return newFile

file3 = MyFile('spam.dat') + MyFile('baz.dat')

--
Alan G
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] question about operator overloading

2012-03-06 Thread Peter Otten
Dave Angel wrote:

> On 03/05/2012 06:20 PM, Alan Gauld wrote:
>> On 05/03/12 21:25, Dave Angel wrote:
>>
>>> It's not clear what __add__() should mean for physical files.
>>
>> My guess would be similar to the cat operator in Unix:
>>
>> $ cat file1, file2 > file3
>>
>> is equivalent to
>>
>> file3 = file1 + file2
>>
>> But of course, thats just my interpretation of file addition...
>>
> 
> So somehow assigning the object to file3 will write the data to a file
> by the name "file3" ?  I know about __add__(), but didn't know we had
> __assign__()

That is indeed one problem that makes an approach based on operator 
overloading clumsy here. You can either invent a name for file3
or defer writing the file:

file3 = file1 + file2
file3.save_as(filename)

Below is an implementation with a made-up destination file name:

$ cat roskam.py
import os

def remove(filename):
try:
os.remove(filename)
except OSError:
pass

class File(object):
def __init__(self, filename):
self.filename = filename
def __iadd__(self, other):
with  self.open("a") as dest, other.open() as source:
dest.writelines(source)
return self
def __add__(self, other):
result = File("+".join([self.filename, other.filename]))
remove(result.filename)
result += self
result += other
return result
def open(self, *mode):
return open(self.filename, *mode)
def __str__(self):
return self.filename + ":\n" + "".join("" + line for line in 
self.open())

if __name__ == "__main__":
remove("file3")
remove("file4")

with open("file1", "w") as f:
f.write("""\
alpha
beta
gamma
""")
with open("file2", "w") as f:
f.write("""\
DELTA
EPSILON
""")

file1, file2, file3 = map(File, ["file1", "file2", "file3"])
file3 += File("file1")
file3 += File("file2")

file4 = file2 + file1 + file2

for f in file1, file2, file3, file4:
print f

$ python roskam.py 
file1:
alpha
beta
gamma

file2:
DELTA
EPSILON

file3:
alpha
beta
gamma
DELTA
EPSILON

file2+file1+file2:
DELTA
EPSILON
alpha
beta
gamma
DELTA
EPSILON

The code is meant to illustrate the implementation of __add__() and 
__iadd__(), I don't recommend that you actually use it. You can easily 
achieve the same with a for loop that is concise and easy to understand:

with open(destname, "wb") as dest:
for sourcename in sourcenames:
with open(sourcename, "rb") as source:
shutil.copyfileobj(source, dest)


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


Re: [Tutor] question about operator overloading

2012-03-05 Thread Dave Angel

On 03/05/2012 06:20 PM, Alan Gauld wrote:

On 05/03/12 21:25, Dave Angel wrote:


It's not clear what __add__() should mean for physical files.


My guess would be similar to the cat operator in Unix:

$ cat file1, file2 > file3

is equivalent to

file3 = file1 + file2

But of course, thats just my interpretation of file addition...



So somehow assigning the object to file3 will write the data to a file 
by the name "file3" ?  I know about __add__(), but didn't know we had 
__assign__()



--

DaveA

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


Re: [Tutor] question about operator overloading

2012-03-05 Thread Steven D'Aprano

Alan Gauld wrote:

On 05/03/12 21:25, Dave Angel wrote:


It's not clear what __add__() should mean for physical files.


My guess would be similar to the cat operator in Unix:

$ cat file1, file2 > file3

is equivalent to

file3 = file1 + file2

But of course, thats just my interpretation of file addition...


I think that's what Albert-Jan is probably thinking, but the two models are 
not quite the same. I think that what he wants is probably closer to something 
like the fileinput module. I think what he wants is to avoid this:


for f in (file1, file2, file3, file4):
for record in f:
process(record)

in favour of this:

all_the_files = file1 + file2 + file3 + file4  # merge file contents
for record in all_the_files:
process(record)

Albert-Jan, am I close? If not, please explain what you are trying to 
accomplish.

If the files are small, the easy way is to just read their contents, add them 
together as strings or lists, and then process the lot. But if the files are 
big, or you want to process them on-demand instead of up-front, you need an 
approach similar to fileinput.


Personally, all these Reader and Append objects make my brain hurt, and I 
hardly ever use operator overloading, except perhaps for numeric types. Reader 
objects, I can just get. But "Append" objects?


This may be useful:

http://steve-yegge.blogspot.com.au/2006/03/execution-in-kingdom-of-nouns.html

and also itertools:


from itertools import chain
merged = chain(file1, file2, file3, file4)
for record in merged:
process(record)



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


Re: [Tutor] question about operator overloading

2012-03-05 Thread Joel Goldstick
On Mon, Mar 5, 2012 at 6:35 PM, Joel Goldstick  wrote:
> On Mon, Mar 5, 2012 at 6:20 PM, Alan Gauld  wrote:
>> On 05/03/12 21:25, Dave Angel wrote:
>>
>>> It's not clear what __add__() should mean for physical files.
>>
>>
>> My guess would be similar to the cat operator in Unix:
>>
>> $ cat file1, file2 > file3
>>
>> is equivalent to
>>
>> file3 = file1 + file2
>>
>> But of course, thats just my interpretation of file addition...
>>
>> --
>> Alan G
>> 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
>
> if spss files are text (not binary) why not:
>
oops forgot the dots.

> f1 = open("f1").read()
> f2 = open("f2").read()
>
> outfile = open("outfile", "w")
> outfile.write(f1 + f2)
> outfile.close()
>
> You could put this in a function and pass all infiles as *filenames,
> then loop to read each file and output result
>
>
>
> --
> Joel Goldstick



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


Re: [Tutor] question about operator overloading

2012-03-05 Thread Joel Goldstick
On Mon, Mar 5, 2012 at 6:20 PM, Alan Gauld  wrote:
> On 05/03/12 21:25, Dave Angel wrote:
>
>> It's not clear what __add__() should mean for physical files.
>
>
> My guess would be similar to the cat operator in Unix:
>
> $ cat file1, file2 > file3
>
> is equivalent to
>
> file3 = file1 + file2
>
> But of course, thats just my interpretation of file addition...
>
> --
> Alan G
> 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

if spss files are text (not binary) why not:

f1 = open("f1")read()
f2 = open("f2")read()

outfile = open("outfile", "w")
outfile.write(f1 + f2)
outfile.close()

You could put this in a function and pass all infiles as *filenames,
then loop to read each file and output result



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


Re: [Tutor] question about operator overloading

2012-03-05 Thread Alan Gauld

On 05/03/12 21:25, Dave Angel wrote:


It's not clear what __add__() should mean for physical files.


My guess would be similar to the cat operator in Unix:

$ cat file1, file2 > file3

is equivalent to

file3 = file1 + file2

But of course, thats just my interpretation of file addition...

--
Alan G
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] question about operator overloading

2012-03-05 Thread Dave Angel

On 03/05/2012 04:10 PM, Albert-Jan Roskam wrote:

Hi Dave,

aha! Good thing I asked. ;-) I've indeed been thinking where this __add__ 
method should live. The program as it is now has a Generic class, a Reader 
class and a Writer class. I thought an Append class was appropriate because it 
uses Reader and Writer (and probably also Generic) methods and the data is from 
multiple files. It reads a bunch of files (even though the term 'reading' is 
more a conceptual term here, as none of the data will be held in memory), 
appends them (__add__), and writes them to one merged file. Doesn't adding 
__add__ change the responsibility from 'thou shallt read one and only one file' 
into something less precise?


So if I understand you correctly, the following pseudocode is better?

merged = Reader.readFile(somefile1) + Reader.readFile(somefile2)
# ..which is the same as: 
Reader.readFile(somefile1).__add__(Reader.readFile(somefile2))
for line in merged:
   Writer.writerow(line)


Maybe this is why my 'top-down code' (what I posted earlier) and my 'bottom-up 
code' (some code that I wrote earlier) don't add up (pun intended!). In the 
bottom-up code there was no need for an Append class!



Please don't top-post.  We've now lost all the context of what happened 
before.


You still don't get it.  If you're going to add objects, they should be 
objects that represent what's being added.  So the objects are of type 
MyFile, not type Reader, whatever that is.  Reader and Writer sounds 
like a java approach.


So you combine two files something like this:

file1 = MyFile(whatever, moreargs)
file2 = MyFile(whateverelse, lessargs)
file1 += file2

that last line will call the method  __iadd__() of class  MyFile.  Self 
will be file1, and the other parameter will be file2.  By convention, 
it'd add file2 to the end of already-existing file1.


It's not clear what __add__() should mean for physical files.  It builds 
something (MyFile instance) that represents two of them, but there's no 
way to assign a filename to it, except after the fact.  So it might be 
an in-memory equivalent (eg. a list).  It should NOT just extend the 
first file.  Generally, it shouldn't modify either of its arguments.


By the way, you could have learned a lot in your original example by 
just adding print statements in the two methods.


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


Re: [Tutor] question about operator overloading

2012-03-05 Thread Albert-Jan Roskam
Hi Dave,

aha! Good thing I asked. ;-) I've indeed been thinking where this __add__ 
method should live. The program as it is now has a Generic class, a Reader 
class and a Writer class. I thought an Append class was appropriate because it 
uses Reader and Writer (and probably also Generic) methods and the data is from 
multiple files. It reads a bunch of files (even though the term 'reading' is 
more a conceptual term here, as none of the data will be held in memory), 
appends them (__add__), and writes them to one merged file. Doesn't adding 
__add__ change the responsibility from 'thou shallt read one and only one file' 
into something less precise?


So if I understand you correctly, the following pseudocode is better?

merged = Reader.readFile(somefile1) + Reader.readFile(somefile2)
# ..which is the same as: 
Reader.readFile(somefile1).__add__(Reader.readFile(somefile2))
for line in merged:
  Writer.writerow(line)


Maybe this is why my 'top-down code' (what I posted earlier) and my 'bottom-up 
code' (some code that I wrote earlier) don't add up (pun intended!). In the 
bottom-up code there was no need for an Append class!
 
Regards,
Albert-Jan


~~
All right, but apart from the sanitation, the medicine, education, wine, public 
order, irrigation, roads, a 
fresh water system, and public health, what have the Romans ever done for us?
~~ 


>
> From: Dave Angel 
>To: Albert-Jan Roskam  
>Cc: Python Mailing List  
>Sent: Monday, March 5, 2012 9:36 PM
>Subject: Re: [Tutor] question about operator overloading
> 
>On 03/05/2012 03:16 PM, Albert-Jan Roskam wrote:
>> Hi,
>> 
>> I am extending a program for a hobby project where potentially huge spss 
>> files are read. I would like to add functionality to append files. I thought 
>> it would be nice and intuitive to overload + and += for this. The code below 
>> is a gross simplification, but I want to get the basics right. Is this the 
>> way how operator overloading is usually done?
>> 
>> 
>> class Append(object):
>> 
>>      def __init__(self, file1, file2=None):
>>          """ file1 and file2 will actually be of a class of my own,
>>          which has a readFile method that is a generator that returns
>>          one record at a time """
>>          self.file1 = file1
>>          self.file2 = file2
>>          self.merged = []
>> 
>>      def __add__(self):
>>          self.file1.extend(self.file2)
>>          return self.file1
>> 
>>      def __iadd__(self):
>>          self.merged.extend(self.file1)
>>          return self.merged
>>              def writerows(self):
>>          rows = self.file1
>>          for row in rows:
>>              yield row
>> 
>> # overloading '+'
>> file1 = [[1, 2, 3], [4, 5, 6], [6, 6, 6]]       file2 = [[1, 2, 3]]
>> app = Append(file1, file2)
>> merged = app.file1 + app.file2 # 'merged'  will not actually hold data
>> for line in app.writerows():
>>      print line
>> 
>> # overloading '+='
>> files = [file1, file2]
>> for i, f in enumerate(files):
>>      if i == 0:
>>          app = Append(f)
>>          app.merged = f
>>      else:
>>          app.merged += f
>> print app.merged
>> 
>
>I hate to say it, but it's not even close.
>
>When you say  app.file1 + app.file2,   you're not calling either of your 
>special methods you defined in Append.  You're just adding the file1 and file2 
>attributes.  Since in your example these are lists, they do the usual thing.
>
>Similarly, your app.merged += f  does NOT call your __iadd__() method.
>
>Just what kind of an object is an Append object supposed to be?  Classes are 
>usually for encapsulating data and behavior, not just to bundle up some 
>functions.
>
>Normally, you should be defining the __add__() and __iadd__() methods in the 
>class that file1 and file2 are instances of.  So if you want to make a dummy 
>example, start by defining a (single) class that holds just one of these.  
>Then create two instances, and try adding and +='ing the two instances.
>
>
>
>DaveA
>
>
>-- 
>DaveA
>
>
>
>___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about operator overloading

2012-03-05 Thread Dave Angel

On 03/05/2012 03:16 PM, Albert-Jan Roskam wrote:

Hi,

I am extending a program for a hobby project where potentially huge spss files 
are read. I would like to add functionality to append files. I thought it would 
be nice and intuitive to overload + and += for this. The code below is a gross 
simplification, but I want to get the basics right. Is this the way how 
operator overloading is usually done?


class Append(object):

 def __init__(self, file1, file2=None):
 """ file1 and file2 will actually be of a class of my own,
 which has a readFile method that is a generator that returns
 one record at a time """
 self.file1 = file1
 self.file2 = file2
 self.merged = []

 def __add__(self):
 self.file1.extend(self.file2)
 return self.file1

 def __iadd__(self):
 self.merged.extend(self.file1)
 return self.merged

 def writerows(self):

 rows = self.file1
 for row in rows:
 yield row

# overloading '+'
file1 = [[1, 2, 3], [4, 5, 6], [6, 6, 6]]   
file2 = [[1, 2, 3]]

app = Append(file1, file2)
merged = app.file1 + app.file2 # 'merged'  will not actually hold data
for line in app.writerows():
 print line

# overloading '+='
files = [file1, file2]
for i, f in enumerate(files):
 if i == 0:
 app = Append(f)
 app.merged = f
 else:
 app.merged += f
print app.merged



I hate to say it, but it's not even close.

When you say  app.file1 + app.file2,   you're not calling either of your 
special methods you defined in Append.  You're just adding the file1 and 
file2 attributes.  Since in your example these are lists, they do the 
usual thing.


Similarly, your app.merged += f  does NOT call your __iadd__() method.

Just what kind of an object is an Append object supposed to be?  Classes 
are usually for encapsulating data and behavior, not just to bundle up 
some functions.


Normally, you should be defining the __add__() and __iadd__() methods in the 
class that file1 and file2 are instances of.  So if you want to make a dummy 
example, start by defining a (single) class that holds just one of these.  Then 
create two instances, and try adding and +='ing the two instances.



DaveA


--

DaveA

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


[Tutor] question about operator overloading

2012-03-05 Thread Albert-Jan Roskam
Hi,

I am extending a program for a hobby project where potentially huge spss files 
are read. I would like to add functionality to append files. I thought it would 
be nice and intuitive to overload + and += for this. The code below is a gross 
simplification, but I want to get the basics right. Is this the way how 
operator overloading is usually done?


class Append(object):

    def __init__(self, file1, file2=None):
    """ file1 and file2 will actually be of a class of my own,
    which has a readFile method that is a generator that returns
    one record at a time """
    self.file1 = file1
    self.file2 = file2
    self.merged = []

    def __add__(self):
    self.file1.extend(self.file2)
    return self.file1

    def __iadd__(self):
    self.merged.extend(self.file1)
    return self.merged
    
    def writerows(self):
    rows = self.file1
    for row in rows:
    yield row

# overloading '+' 
file1 = [[1, 2, 3], [4, 5, 6], [6, 6, 6]]    
file2 = [[1, 2, 3]]
app = Append(file1, file2)
merged = app.file1 + app.file2 # 'merged'  will not actually hold data
for line in app.writerows():
    print line

# overloading '+=' 
files = [file1, file2]
for i, f in enumerate(files):
    if i == 0:
    app = Append(f)
    app.merged = f
    else:
    app.merged += f
print app.merged

 
Thank you in advance!


Regards,
Albert-Jan


~~
All right, but apart from the sanitation, the medicine, education, wine, public 
order, irrigation, roads, a 
fresh water system, and public health, what have the Romans ever done for us?
~~ ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about writing to Excel with slavic characters

2012-03-05 Thread Albert-Jan Roskam
Hi,

The R package foreign, in particular the read.spss function has some known 
problems reading spss system files. The memisc package also has a function to 
read .sav files. The big advantage of that function is that you can select rows 
and columns prior to actually reading the data into memory.

If you're just using R and Rpy to read .sav files, you could also consider 
using a Python program that I wrote a while ago:
http://code.activestate.com/recipes/577811-python-reader-writer-for-spss-sav-files-linux-mac-/
It runs on Windows, Mac and Linux and requires no installation of spss. I'd be 
interested to hear your experiences.

 
Regards,
Albert-Jan


~~
All right, but apart from the sanitation, the medicine, education, wine, public 
order, irrigation, roads, a 
fresh water system, and public health, what have the Romans ever done for us?
~~ 


>
> From: Marko Limbek 
>To: cwi...@compuscan.co.za 
>Cc: tutor@python.org 
>Sent: Monday, March 5, 2012 2:05 PM
>Subject: Re: [Tutor] Question about writing to Excel with slavic characters
> 
>Thank you!
>
>That was easy. Now I have another problem.
>I use RPy and read the spss database with method read.spss inside a
>nested R code in Python, that looks like that:
>
>
>import rpy
>
>r("""
>
>library(foreign)
>
>baza <- read.spss(""" + analysis[0] + """)
>
>print(baza$demo_izob0)
>
>""")
>
>Now when my text data labels in spss have slavic characters, they are
>not recognised and output is something like that:
>
>stiriletna srednja �ola
>nedokon�ana osnovna �ola
>
>
>What should I do here?
>
>
>Thanks a lot,
>
>
>Marko
>
>
>
>
>On Mon, Mar 5, 2012 at 1:46 PM, Christian Witts  wrote:
>> On 2012/03/05 02:37 PM, Marko Limbek wrote:
>>
>> Hi everyone.
>>
>>
>> I am new to list and few months old to Python. I am writing some text
>> to Excel and I open the new book and try to write to the book and the
>> save it using
>>
>> book.save
>>
>> Now when I write slavic characters in the text to Excel (č, š, ž, for
>> instance 0xc5), I get an error, I can't save it.
>> I have declared appropriate encoding
>>
>> # -*- coding: utf-8 -*-
>> # coding=
>> #!/E:/Python
>>
>> and those characters appear normally in the code, but there seems to
>> be the problem with the function book.save.
>> Does anyone have any ideas, what would be the problem and how to solve
>> it? Some additional encoding or some changes or parameters to the
>> book.save method?
>>
>> Is that the right forum for my question?
>>
>>
>> Thank you,
>>
>> Marko
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>> What package are you using to create your Excel workbook ?
>> If it's xlwt you can set your encoding type when you create your workbook
>> book = xlwt.Workbook(encoding="utf-8")
>> --
>>
>> Christian Witts
>> Python Developer
>___
>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] Question about writing to Excel with slavic characters

2012-03-05 Thread Steven D'Aprano

Marko Limbek wrote:

Thank you!

That was easy. Now I have another problem.
I use RPy and read the spss database with method read.spss inside a
nested R code in Python, that looks like that:


import rpy

r("""
library(foreign)
baza <- read.spss(""" + analysis[0] + """)
print(baza$demo_izob0)
""")

Now when my text data labels in spss have slavic characters, they are
not recognised and output is something like that:

stiriletna srednja �ola
nedokon�ana osnovna �ola


What should I do here?


Since the SPSS labels are being read by R, not Python, my guess is that this 
is likely a problem with R, not Python.


You might find the rpy mailing list more helpful for solving rpy problems.

https://lists.sourceforge.net/lists/listinfo/rpy-list

Good luck!



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


Re: [Tutor] Question about writing to Excel with slavic characters

2012-03-05 Thread Christian Witts

On 2012/03/05 03:05 PM, Marko Limbek wrote:

Thank you!

That was easy. Now I have another problem.
I use RPy and read the spss database with method read.spss inside a
nested R code in Python, that looks like that:


import rpy

r("""

library(foreign)

baza<- read.spss(""" + analysis[0] + """)

print(baza$demo_izob0)

""")

Now when my text data labels in spss have slavic characters, they are
not recognised and output is something like that:

stiriletna srednja �ola
nedokon�ana osnovna �ola


What should I do here?


Thanks a lot,


Marko




On Mon, Mar 5, 2012 at 1:46 PM, Christian Witts  wrote:

On 2012/03/05 02:37 PM, Marko Limbek wrote:

Hi everyone.


I am new to list and few months old to Python. I am writing some text
to Excel and I open the new book and try to write to the book and the
save it using

book.save

Now when I write slavic characters in the text to Excel (č, š, ž, for
instance 0xc5), I get an error, I can't save it.
I have declared appropriate encoding

# -*- coding: utf-8 -*-
# coding=
#!/E:/Python

and those characters appear normally in the code, but there seems to
be the problem with the function book.save.
Does anyone have any ideas, what would be the problem and how to solve
it? Some additional encoding or some changes or parameters to the
book.save method?

Is that the right forum for my question?


Thank you,

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

What package are you using to create your Excel workbook ?
If it's xlwt you can set your encoding type when you create your workbook
book = xlwt.Workbook(encoding="utf-8")
--

Christian Witts
Python Developer



Hi, you should avoid top-posting as it makes it hard to follow the 
thread if people have to bounce between the top and bottom of the post.


As for the answer to your question, I would suggest the R Mailing List 
if they have any issues with Unicode or need any encodings set when 
loading data etc.
There was a bug with Unicode support & RPy <2.2 but that was fixed last 
year so if you have a recent version of RPy that shouldn't be the issue.


--

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


Re: [Tutor] Question about writing to Excel with slavic characters

2012-03-05 Thread Marko Limbek
Thank you!

That was easy. Now I have another problem.
I use RPy and read the spss database with method read.spss inside a
nested R code in Python, that looks like that:


import rpy

r("""

library(foreign)

baza <- read.spss(""" + analysis[0] + """)

print(baza$demo_izob0)

""")

Now when my text data labels in spss have slavic characters, they are
not recognised and output is something like that:

stiriletna srednja �ola
nedokon�ana osnovna �ola


What should I do here?


Thanks a lot,


Marko




On Mon, Mar 5, 2012 at 1:46 PM, Christian Witts  wrote:
> On 2012/03/05 02:37 PM, Marko Limbek wrote:
>
> Hi everyone.
>
>
> I am new to list and few months old to Python. I am writing some text
> to Excel and I open the new book and try to write to the book and the
> save it using
>
> book.save
>
> Now when I write slavic characters in the text to Excel (č, š, ž, for
> instance 0xc5), I get an error, I can't save it.
> I have declared appropriate encoding
>
> # -*- coding: utf-8 -*-
> # coding=
> #!/E:/Python
>
> and those characters appear normally in the code, but there seems to
> be the problem with the function book.save.
> Does anyone have any ideas, what would be the problem and how to solve
> it? Some additional encoding or some changes or parameters to the
> book.save method?
>
> Is that the right forum for my question?
>
>
> Thank you,
>
> Marko
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
> What package are you using to create your Excel workbook ?
> If it's xlwt you can set your encoding type when you create your workbook
> book = xlwt.Workbook(encoding="utf-8")
> --
>
> Christian Witts
> Python Developer
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about writing to Excel with slavic characters

2012-03-05 Thread Christian Witts

On 2012/03/05 02:37 PM, Marko Limbek wrote:

Hi everyone.


I am new to list and few months old to Python. I am writing some text
to Excel and I open the new book and try to write to the book and the
save it using

book.save

Now when I write slavic characters in the text to Excel (č, š, ž, for
instance 0xc5), I get an error, I can't save it.
I have declared appropriate encoding

# -*- coding: utf-8 -*-
# coding=
#!/E:/Python

and those characters appear normally in the code, but there seems to
be the problem with the function book.save.
Does anyone have any ideas, what would be the problem and how to solve
it? Some additional encoding or some changes or parameters to the
book.save method?

Is that the right forum for my question?


Thank you,

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

What package are you using to create your Excel workbook ?
If it's xlwt you can set your encoding type when you create your workbook
book = xlwt.Workbook(encoding="utf-8")
--

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


[Tutor] Question about writing to Excel with slavic characters

2012-03-05 Thread Marko Limbek
Hi everyone.


I am new to list and few months old to Python. I am writing some text
to Excel and I open the new book and try to write to the book and the
save it using

book.save

Now when I write slavic characters in the text to Excel (č, š, ž, for
instance 0xc5), I get an error, I can't save it.
I have declared appropriate encoding

# -*- coding: utf-8 -*-
# coding=
#!/E:/Python

and those characters appear normally in the code, but there seems to
be the problem with the function book.save.
Does anyone have any ideas, what would be the problem and how to solve
it? Some additional encoding or some changes or parameters to the
book.save method?

Is that the right forum for my question?


Thank you,

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


Re: [Tutor] Question about an example in Python doc

2012-02-10 Thread Hugo Arts
On Fri, Feb 10, 2012 at 3:12 PM, daedae11  wrote:
> The example is the third example in (Python2.7's doc)->(Python Library
> Reference)->17.2.2.
> The code of the example is:
>
> import socket
>
> # the public network interface
> HOST = socket.gethostbyname(socket.gethostname())
>
> # create a raw socket and bind it to the public interface
> s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
> s.bind((HOST, 0))
>
> # Include IP headers
> s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
>
> # receive all packages
> s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
>
> # receive a package
> print s.recvfrom(65565)
>
> # disabled promiscuous mode
> s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
>
>
> However, when I run it, the interpreter show the following error:
>
> Traceback (most recent call last):
>   File "E:\c language\Eclipse\example\src\sniffer.py", line 12, in 
> s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
>   File "D:\Python27\lib\socket.py", line 187, in __init__
> _sock = _realsocket(family, type, proto)
> socket.error: [Errno 10013]
>

That's very strange, because when I run it, the interpreter shows the
following error:

Traceback (most recent call last):
  File "C:/Users/hugo/Downloads/test.py", line 7, in 
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
  File "C:\Python27\lib\socket.py", line 187, in __init__
_sock = _realsocket(family, type, proto)
error: [Errno 10013] An attempt was made to access a socket in a way
forbidden by its access permissions
>>>

Which is identical to yours, but includes a helpful message telling
you what is wrong. Did you not get that message, or did you just paste
it wrong?

In any case, Walter got you the solution.

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


Re: [Tutor] Question about an example in Python doc

2012-02-10 Thread Walter Prins
Hi,

On 10 February 2012 14:12, daedae11  wrote:
> Traceback (most recent call last):
>   File "E:\c language\Eclipse\example\src\sniffer.py", line 12, in 
> s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
>   File "D:\Python27\lib\socket.py", line 187, in __init__
> _sock = _realsocket(family, type, proto)
> socket.error: [Errno 10013]

A bit of googling suggests that "ErrNo 10013" means "Access denied".
The error therefore presumably results because raw sockets require
elevated (Administrator) privileges.  The documentation you're
referring to actually states as much: "The last example shows how to
write a very simple network sniffer with raw sockets on Windows. The
example requires administrator privileges to modify the interface:"
So I conclude you need to run your script as administrator (and
apparently have not done so above.)

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


[Tutor] Question about an example in Python doc

2012-02-10 Thread daedae11
The example is the third example in (Python2.7's doc)->(Python Library 
Reference)->17.2.2.
The code of the example is:

import socket

# the public network interface
HOST = socket.gethostbyname(socket.gethostname())

# create a raw socket and bind it to the public interface
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
s.bind((HOST, 0))

# Include IP headers
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)

# receive all packages
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)

# receive a package
print s.recvfrom(65565)

# disabled promiscuous mode
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)


However, when I run it, the interpreter show the following error:

Traceback (most recent call last):
  File "E:\c language\Eclipse\example\src\sniffer.py", line 12, in 
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
  File "D:\Python27\lib\socket.py", line 187, in __init__
_sock = _realsocket(family, type, proto)
socket.error: [Errno 10013] 

What's the matter?




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


Re: [Tutor] Question on how to do exponents

2012-02-07 Thread bob gailer

On 2/7/2012 1:57 PM, Sarma Tangirala wrote:


Anyway, I was wondering about this, if internally pow() actually uses 
**. :P



>>> from dis  import dis
>>> dis(lambda a,b:a**b)
  1   0 LOAD_FAST0 (a)
  3 LOAD_FAST1 (b)
  6 BINARY_POWER
  7 RETURN_VALUE
>>> dis(lambda a,b:pow(a,b))
  1   0 LOAD_GLOBAL  0 (pow)
  3 LOAD_FAST0 (a)
  6 LOAD_FAST1 (b)
  9 CALL_FUNCTION2
 12 RETURN_VALUE

Now you know, and you know how to find out!

To delve any deeper you'd have to inspect the c source for pow.
I'd assume it uses the c exponent operator

--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] Question on how to do exponents

2012-02-07 Thread Dave Angel

On 02/07/2012 01:57 PM, Sarma Tangirala wrote:

On 8 February 2012 00:01, Steven D'Aprano  wrote:


Sarma Tangirala wrote:

  Is is better to use pow() against **?

Advantages of **

- it is shorter to type x**y vs pow(x, y)
- being an operator, it is slightly faster than calling a function
- you can't monkey-patch it

Disadvantages of **

- being an operator, you can't directly use it as a function-object
- it can't take three arguments
- hard to google for "**"
- you can't monkey-patch it

Advantages of pow()

- it is a function, so you can pass it around as an object
- three argument form
- easy to call help(pow) to see documentation
- easy to google for "pow"
- can be monkey-patched

Disadvantages of pow()

- a tiny bit slower due to the function call
- slightly longer to type
- can be monkey-patched


Weigh up the advantages and disadvantages of each, and make the call which
is better for you.

(My preference is to use the ** operator.)



A simple "function call" argument would have done! :D Thanks for the survey!

Anyway, I was wondering about this, if internally pow() actually uses **. :P


I have no idea, but I'd assume so, unless there's a 3rd argument.   At 
that point, the algorithm must change drastically.


--

DaveA

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


Re: [Tutor] Question on how to do exponents

2012-02-07 Thread Sarma Tangirala
On 8 February 2012 00:01, Steven D'Aprano  wrote:

> Sarma Tangirala wrote:
>
>  Is is better to use pow() against **?
>>
>
>
> Advantages of **
>
> - it is shorter to type x**y vs pow(x, y)
> - being an operator, it is slightly faster than calling a function
> - you can't monkey-patch it
>
> Disadvantages of **
>
> - being an operator, you can't directly use it as a function-object
> - it can't take three arguments
> - hard to google for "**"
> - you can't monkey-patch it
>
> Advantages of pow()
>
> - it is a function, so you can pass it around as an object
> - three argument form
> - easy to call help(pow) to see documentation
> - easy to google for "pow"
> - can be monkey-patched
>
> Disadvantages of pow()
>
> - a tiny bit slower due to the function call
> - slightly longer to type
> - can be monkey-patched
>
>
> Weigh up the advantages and disadvantages of each, and make the call which
> is better for you.
>
> (My preference is to use the ** operator.)
>
>
A simple "function call" argument would have done! :D Thanks for the survey!

Anyway, I was wondering about this, if internally pow() actually uses **. :P


>
>
> --
> Steven
>
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor
>



-- 
Sarma Tangirala,
Class of 2012,
Department of Information Science and Technology,
College of Engineering Guindy - Anna University
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question on how to do exponents

2012-02-07 Thread Steven D'Aprano

Sarma Tangirala wrote:


Is is better to use pow() against **?



Advantages of **

- it is shorter to type x**y vs pow(x, y)
- being an operator, it is slightly faster than calling a function
- you can't monkey-patch it

Disadvantages of **

- being an operator, you can't directly use it as a function-object
- it can't take three arguments
- hard to google for "**"
- you can't monkey-patch it

Advantages of pow()

- it is a function, so you can pass it around as an object
- three argument form
- easy to call help(pow) to see documentation
- easy to google for "pow"
- can be monkey-patched

Disadvantages of pow()

- a tiny bit slower due to the function call
- slightly longer to type
- can be monkey-patched


Weigh up the advantages and disadvantages of each, and make the call which is 
better for you.


(My preference is to use the ** operator.)



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


Re: [Tutor] Question on how to do exponents

2012-02-07 Thread Alan Gauld

On 07/02/12 16:54, Sarma Tangirala wrote:


Is is better to use pow() against **?


I suspect ** will be faster since it doesn't have the function
call overhead.

But I haven't tried timing it. Feel free to do some tests and find out.
Let us know how you get on!


--
Alan G
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] Question on how to do exponents

2012-02-07 Thread Sarma Tangirala
On 7 February 2012 13:49, Alan Gauld  wrote:

> On 07/02/12 01:01, Nate Lastname wrote:
>
>> Exponents ... are **(or ^)
>>
>
> Not quite the ^ operator is a bitwise XOR...
>
> >>> 2^2
> 0
> >>> 2^1
> 3
>
> pow() is the other way to do exponents.
>
>
Is is better to use pow() against **?


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



-- 
Sarma Tangirala,
Class of 2012,
Department of Information Science and Technology,
College of Engineering Guindy - Anna University
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question on how to do exponents

2012-02-07 Thread Alan Gauld

On 07/02/12 01:01, Nate Lastname wrote:

Exponents ... are **(or ^)


Not quite the ^ operator is a bitwise XOR...

>>> 2^2
0
>>> 2^1
3

pow() is the other way to do exponents.

--
Alan G
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] Question on how to do exponents

2012-02-06 Thread Steven D'Aprano
On Mon, Feb 06, 2012 at 04:54:57PM -0800, William Stewart wrote:
> Hello everyone, I am making a calculator and I need to know how to make it do 
> exponents and remainders
> How can I input this info in python?
> Any help would be appreciated

You can do exponents either with the ** operator or the pow() 
function:

py> 2**4
16
py> pow(3, 5)
243


The pow() function is especially useful for advanced mathematics where 
you want to perform exponents modulo some base:

py> pow(3, 5, 2)
1

That is, it calculates the remainder when divided by 2 of 3**5 *without* 
needing to calculate 3**5 first. This is especially useful when 
the intermediate number could be huge:

py> pow(1357924680, 2468013579, 1256711)
418453L


To get the remainder, use the % operator or the divmod() function:

py> 17 % 2
1
py> divmod(17, 2)
(8, 1)


Hope this helps.

P.S. please don't hijack threads by replying to an existing message, as 
it could lead to some people not seeing your email. It is better to 
start a new thread by using "New Message", not with "Reply".


-- 
Steven

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


Re: [Tutor] Question on how to do exponents

2012-02-06 Thread Nate Lastname
Exponents and remainder (modulus) are **(or ^) and % respectively.  I.E.;
d = a ** b (exponent)
c = a % b (modulus)

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


[Tutor] Question on how to do exponents

2012-02-06 Thread William Stewart
Hello everyone, I am making a calculator and I need to know how to make it do 
exponents and remainders
How can I input this info in python?
Any help would be appreciated
Thanks

--- On Mon, 2/6/12, Steven D'Aprano  wrote:


From: Steven D'Aprano 
Subject: Re: [Tutor] Sandbox Game
To: "tutor" 
Date: Monday, February 6, 2012, 7:50 PM


On Mon, Feb 06, 2012 at 09:13:48AM -0500, Nate Lastname wrote:
> Hello List,
> 
> I am quite sorry for my attitude.  I will look more thoroughly into the
> search results.  Thanks for the link to Epik.  I had found this, but I
> didn't realize that it was Python.  I apologize once again, and thank you
> for your help.  I did give you a link to a sandbox game (powdertoy.co.uk)
> as an example of what I wanted, but that must not have been delivered
> properly.

Thank you for the gracious apology, and welcome to the group!

Don't worry about asking stupid questions, we don't mind them so long as 
you make an effort to solve them yourself first, and that you learn from 
them as you go.


-- 
Steven

___
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] Question regarding setup.py

2012-01-27 Thread Evert Rol
> I had a question regarding installing packages that I posted a couple of days 
> ago. But I'm re-sending the question again.. this time with output so that it 
> is clearer.
> 
> I am unable to install libraries using 'python setup.py install'
> 
> Say that I'm installing a package "kando". I extract it and I'm currently in 
> its directory:
> 
> Output to dir:
> dir
>  11357Aug 12 20:43:46 2011  COPYING.txt
>   2769Aug 12 20:46:34 2011  PKG-INFO
>   1490Aug 12 20:39:31 2011  README.txt
> 56Aug 05 20:06:46 2011  kando
>   6362Aug 12 20:35:23 2011  kando.py
>868Oct 20 17:48:00 2011  setup.py
> 
> Next, I try and install kando and this is what I get:
> 
> python setup.py install
> file kando.py (for module kando) not found
> file kando.py (for module kando) not found
> error: file '/var/sysmgr/vsh/kando' does not exist
> Thu Oct 20 18:35:01 UTC 2011
> running install
> running build
> running build_py
> running build_scripts

I assume you're running this in the unpacked directory (it's what you suggest, 
but I can't tell with 100% certainty.).
Then I can only think that the setup.py is misbehaving; the 
'/var/sysmgr/vsh/kando' mention suggests that. 
Usually, certainly for small libraries (this seems to be one), these are 
relatively small, so perhaps you can post it?
Also, check the README file for any installation suggestions.

Alternatively, if the contents of the kando/ directory just contains Python 
files, you could copy-paste that whole directory into your Python library 
installation directory. The latter is system dependent, but should be 
relatively easy to find out. 

Another thing I can think of that may cause problems, is that in the unpacked 
directory, there is both a kando directory (which presumably contains an 
__init__.py file) and a kando.py file.


> I guess the installer is not looking in the right path for the files to be 
> installed as it cannot find kando.py although I can see it in the output of 
> dir. This is not specific to just kando. I have tried installing 
> arithmetic-0.5 and other packages.
> Can you please tell me how I can change the search path of the installer?

No, that's not how it works.
You just run python setup.py install in the directory, and Python will happily 
install the library correctly.
You can alter the *installation* path, using a flag like --prefix. Usually, I 
wouldn't recommend that.

  Evert

> Thanks in advance.
> 
> Thanks,
> San
> 
> ___
> 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] Question regarding setup.py

2012-01-26 Thread sp6

Hi All,

I had a question regarding installing packages that I posted a couple  
of days ago. But I'm re-sending the question again.. this time with  
output so that it is clearer.


I am unable to install libraries using 'python setup.py install'

Say that I'm installing a package "kando". I extract it and I'm  
currently in its directory:


Output to dir:
dir
  11357Aug 12 20:43:46 2011  COPYING.txt
   2769Aug 12 20:46:34 2011  PKG-INFO
   1490Aug 12 20:39:31 2011  README.txt
 56Aug 05 20:06:46 2011  kando
   6362Aug 12 20:35:23 2011  kando.py
868Oct 20 17:48:00 2011  setup.py

Next, I try and install kando and this is what I get:

python setup.py install
file kando.py (for module kando) not found
file kando.py (for module kando) not found
error: file '/var/sysmgr/vsh/kando' does not exist
Thu Oct 20 18:35:01 UTC 2011
running install
running build
running build_py
running build_scripts

I guess the installer is not looking in the right path for the files  
to be installed as it cannot find kando.py although I can see it in  
the output of dir. This is not specific to just kando. I have tried  
installing arithmetic-0.5 and other packages.

Can you please tell me how I can change the search path of the installer?
Thanks in advance.

Thanks,
San

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


Re: [Tutor] Question about install.py

2012-01-19 Thread Evert Rol
  Hi,

> I'm new to Python and was wondering if someone could answer a question I have.
> Say that I have a python library, arithmetic-0.5, located at /X/arithmetic-0.5
> I'd like to run setup and install it. But I guess since /X/arithmetic-0.5 is 
> not in install.py's default search path, it comes back with an error saying 
> that it cannot find the necessary files.
> Can you please tell me how I can change the search path of install.py? What 
> parameter do I need to modify?

I don't know about install.py. Perhaps you can give a pointer to that (eg, a 
webpage)?

As far as I my knowledge goes, you install libraries (modules) using setup.py.
In that case, a command like 
$> python setup.py install
should do it. That assumes you're working from the command line. 
Python will automatically install the library in a place where it can find it.
See also http://docs.python.org/install/index.html
It can be easier to use a binary installer though, especially if you're not 
used to working on command lines.

If you're just trying to install a Python library, it can help if you mention 
which library you want to install, what you are using for the installation 
(source code, or installer), which python version and on which OS you are 
working.
Also, you mention an error, but don't specify it. Python usually comes with a 
whole backtrace, which you can copy-paste into your email.

Cheers,

  Evert


> 
> Thanks in advance.
> 
> 
> 
> ___
> 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] Question about install.py

2012-01-18 Thread sp6

Hello,

I'm new to Python and was wondering if someone could answer a question I have.
Say that I have a python library, arithmetic-0.5, located at /X/arithmetic-0.5
I'd like to run setup and install it. But I guess since  
/X/arithmetic-0.5 is not in install.py's default search path, it comes  
back with an error saying that it cannot find the necessary files.
Can you please tell me how I can change the search path of install.py?  
What parameter do I need to modify?


Thanks in advance.



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


Re: [Tutor] question about gzip module

2012-01-05 Thread Walter Prins
Hi,

On 5 January 2012 15:45, daedae11  wrote:
> Is there anyone who can give me an example of how to use the gzip module?
> I have read the document, but there is no example in the document.

Which document are you referring to?   The Official Python
documentation does in fact contain examples also (See 12.2.1):
http://docs.python.org/library/gzip.html


(But +1 for PyMOTW as mentioned by Izantal.)

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


Re: [Tutor] question about gzip module

2012-01-05 Thread lzantal
Good morning,

I learned it (and many other modules) from pymotw.
Here is a direct link to the gzip week.
http://www.doughellmann.com/PyMOTW/gzip/index.html#module-gzip

lzantal



On Jan 5, 2012, at 7:45 AM, daedae11 wrote:

> Is there anyone who can give me an example of how to use the gzip module?
> I have read the document, but there is no example in the document.
> Thank you!!
>  
> daedae11
> ___
> 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] question about gzip module

2012-01-05 Thread daedae11
Is there anyone who can give me an example of how to use the gzip module?
I have read the document, but there is no example in the document.
Thank you!!




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


Re: [Tutor] question about a exercise

2012-01-05 Thread Wayne Werner
On Thu, Jan 5, 2012 at 9:22 AM, daedae11  wrote:

> **
> The exercise is:
>
> Write a function which has 3 parameters. First parameter is a char, second
> parameter is a integer, third parameter is a integer.
> The function would create a file which have following requests:
> 1. the length of the file is in accordance with the third parameter.
> 2. the content of the file must be random generated.
> 3. the time first parameter occurred in the content must be in accordance
> with second parameter.
>
> please give me some hints. It would be better if you give me the code.
>

It would be better if /you/ gave us the code that shows what you've tried.
Also, if we give you the solution(s) then you won't learn.

To accomplish this exercise you need a few skills:

1. Write a function that takes parameters - can you do this?
2. Create a file - can you do this?
3. Generate random text - can you do this?
4. Modify text (or generate slightly less-random text) - can you do this?

If you can do those four things then you should be able to easily
accomplish this task (that looks an awful lot like homework)

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


Re: [Tutor] question about a exercise

2012-01-05 Thread Alexander
On Thu, Jan 5, 2012 at 10:22 AM, daedae11  wrote:

> **
> The exercise is:
>
> Write a function which has 3 parameters. First parameter is a char, second
> parameter is a integer, third parameter is a integer.
> The function would create a file which have following requests:
> 1. the length of the file is in accordance with the third parameter.
> 2. the content of the file must be random generated.
> 3. the time first parameter occurred in the content must be in accordance
> with second parameter.
>
> please give me some hints. It would be better if you give me the code.
>
> --
> daedae11
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
> You're likely going to get patronized for asking for the code as if you're
asking for someone to do your homework problem for you.
-- 
Alexander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] question about a exercise

2012-01-05 Thread daedae11
The exercise is:

Write a function which has 3 parameters. First parameter is a char, second 
parameter is a integer, third parameter is a integer.
The function would create a file which have following requests:
1. the length of the file is in accordance with the third parameter.
2. the content of the file must be random generated.
3. the time first parameter occurred in the content must be in accordance with 
second parameter.

please give me some hints. It would be better if you give me the code.




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


Re: [Tutor] question about the an exercise in (including the discription about the exercise)

2012-01-04 Thread Alan Gauld

On 04/01/12 14:54, Joel Goldstick wrote:


two files' content is equal, just print "equal". Else, print the
rows And column number of the first different position.



while True:
   line = f1.readline()
   if line != f2.readline():
print lineNum, " : ", line


# in here I believe you need a bit more.  You now know the lines are
not equal, but the exercise requires the line number and column number


Oops, I didn't notice the column bit...sorry.


# To do that, you need to do something similar to what Alan has shown
 for i, c in enumerate(line):  #enumerate iterates over the
   if line2[i] != c:  # line2[i] is the
   print "The file differs at line %d, column %d" % lineNum, i


Yep, that ought to work.

--
Alan G
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] question about the an exercise in (including the discription about the exercise)

2012-01-04 Thread Joel Goldstick
On Wed, Jan 4, 2012 at 9:36 AM, Alan Gauld  wrote:
> On 04/01/12 14:13, David Palao wrote:
>>
>> Hi,
>> some hints:
>> 1) strings are iterables
>
>
> And so are files ;-)
>
>> 2) help(zip)
>> 3) help(enumerate)
>
>
>>    Write a program that compare the two files given by users. If the
>>    two files' content is equal, just print "equal". Else, print the
>>    rows And column number of the first different position.
>
>
> In pseudocode you could do:
>
> f1 = open(file1)
> f2 = open(file2)
> lineNum = 1
> while True:
>   line = f1.readline()
# I would change next line to this:
 line2 = f2.readline()# this to have a name for each line for below
 if line != line2:
>   if line != f2.readline():
>        print lineNum, " : ", line

# in here I believe you need a bit more.  You now know the lines are
not equal, but the exercise requires the line number and column number
where the two lines differ
# To do that, you need to do something similar to what Alan has shown
for i, c in enumerate(line):  #enumerate iterates over the
characters in line, and returns the index and the character
  if line2[i] != c:  # line2[i] is the
character in the same position on the line as c from line
  print "The file differs at line %d, column %d" % lineNum, i
>        exit
>   else:
>       lineNum += 1
> print "equal"
>
>
> But there other approaches you could use.
>
> --
> Alan G
> 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



-- 


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


Re: [Tutor] question about the an exercise in (including the discription about the exercise)

2012-01-04 Thread Alan Gauld

On 04/01/12 14:13, David Palao wrote:

Hi,
some hints:
1) strings are iterables


And so are files ;-)


2) help(zip)
3) help(enumerate)



Write a program that compare the two files given by users. If the
two files' content is equal, just print "equal". Else, print the
rows And column number of the first different position.


In pseudocode you could do:

f1 = open(file1)
f2 = open(file2)
lineNum = 1
while True:
   line = f1.readline()
   if line != f2.readline():
print lineNum, " : ", line
exit
   else:
   lineNum += 1
print "equal"


But there other approaches you could use.

--
Alan G
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] question about the an exercise in (including the discription about the exercise)

2012-01-04 Thread David Palao
Hi,
some hints:
1) strings are iterables
2) help(zip)
3) help(enumerate)

Best regards.

2012/1/4 daedae11 

> **
> Who can give me an example program about the exercise 6 in chapter 9 in
>  ?
>
> The exercise is:
> Write a program that compare the two files given by users. If the two
> files' content is equal, just print "equal". Else, print the rows And
> column number of the first different position.
>
> Thank you!
>
>
>
>
>
> Thank you!
>
> --
> daedae11
>
> ___
> 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] question about the an exercise in (including the discription about the exercise)

2012-01-04 Thread daedae11
Who can give me an example program about the exercise 6 in chapter 9 in  ?

The exercise is:
Write a program that compare the two files given by users. If the two files' 
content is equal, just print "equal". Else, print the rows And column number of 
the first different position.

Thank you!





Thank you!




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


Re: [Tutor] question about the exercises in

2012-01-04 Thread Walter Prins
Hi daedae11,

2012/1/4 daedae11 :
> Who can give me an example program about the exercise 4 in chapter 9 in
>  ?
>
> Thank you!

You're limiting the number of people who might help you by not posting
the excercise/problem you're having directly and instead only giving a
reference to a book the readers of your message may not have.
(Probably not, judging by the lack of responses so far.)

Please post details of the excercise, what you've tried, what happened
as a result (including any errors messages and stack traces as
appropriate), and what you expected should've happened.  This will
ensure people have all the required information to help you directly
without having to spend time hunting down material and/or having to
guess at or extract from you what problem(s) you're having.

Thanks

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


[Tutor] question about the exercises in

2012-01-04 Thread daedae11
Who can give me an example program about the exercise 4 in chapter 9 in  ?

Thank you!




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


[Tutor] question about the exercises in

2012-01-04 Thread daedae11
Who can give me an example program about the exercise 4 in chapter 9 in  ?




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


Re: [Tutor] question about pywin32

2011-12-26 Thread Marc Tompkins
On Mon, Dec 26, 2011 at 5:18 AM, daedae11  wrote:

> **
> Does pywin32 provide a module for AES encryption algorithm ?
>
> The description of some module in pywin32 document is so simple that there
> is not introduction about the function of the function.
> For example, "CryptProtectData" function in module win32crypt.
>
Lie Ryan has already covered this pretty well, but I thought I'd re-state
for clarification:  pywin32 itself does not provide modules for ANYTHING.
pywin32 is just a convenience wrapper for functions that already exist in
the win32 library; without pywin it's a horrible task to call win32
functions from Python.

Since pywin doesn't provide the functions, it also doesn't provide
documentation.  For that, you go to the people who actually wrote the
functions: Microsoft.  In fact, it might make more sense to turn your
search around: look at MSDN _first_ to see what functions are available,
and then look at the pywin docs to see how to call them.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about pywin32

2011-12-26 Thread Lie Ryan

On 12/27/2011 02:58 AM, Lie Ryan wrote:

On 12/27/2011 12:18 AM, daedae11 wrote:

Does pywin32 provide a module for AES encryption algorithm ?
The description of some module in pywin32 document is so simple that
there is not introduction about the function of the function.
For example, "CryptProtectData" function in module win32crypt.



It is not the intent of pywin32 to document win32 functions. For each of
pywin32 function, there is a corresponding C function with the same name
in MSDN, for example, for CryptProtectData:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa380261%28v=vs.85%29.aspx


a small correction: "...there is a corresponding C function with the 
same name in win32 library, which is documented in MSDN..."


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


Re: [Tutor] question about pywin32

2011-12-26 Thread Lie Ryan

On 12/27/2011 12:18 AM, daedae11 wrote:

Does pywin32 provide a module for AES encryption algorithm ?
The description of some module in pywin32 document is so simple that
there is not introduction about the function of the function.
For example, "CryptProtectData" function in module win32crypt.



It is not the intent of pywin32 to document win32 functions. For each of 
pywin32 function, there is a corresponding C function with the same name 
in MSDN, for example, for CryptProtectData: 
http://msdn.microsoft.com/en-us/library/windows/desktop/aa380261%28v=vs.85%29.aspx



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


[Tutor] question about pywin32

2011-12-26 Thread daedae11
Does pywin32 provide a module for AES encryption algorithm ?

The description of some module in pywin32 document is so simple that there is 
not introduction about the function of the function.
For example, "CryptProtectData" function in module win32crypt.



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


Re: [Tutor] question about the build-in function reversed in Python2.5

2011-12-25 Thread Steven D'Aprano

daedae11 wrote:

The build-in function reversed() in Python2.5  returns a iterator. But I don't 
know how to use the iterator.
Please give me a simple example about how to use bulid-in function reversed() 
to reverse a list.


You use the iterator the same way you would any other iterator:

* in for loops:

for obj in reversed(my_list):
print(obj)

* pass it to functions which expect an iterator:

a = reduce(function, reversed(my_list))
b = map(func, reversed(my_string))

* create a new sequence:

my_list = list(reversed(my_list))


Note that the advantage of reversed is that it is lazy (it returns an 
iterator). If you just want a copy of a list in reverse order, you can use 
slicing:


my_list[::-1]

(also works on strings and tuples).

If you want to reverse the list in place, instead of making a copy:

my_list.reverse()  # must be a list, not strings or tuples


reversed() is more general: it can work on any finite iterable object, not 
just lists.





--
Steven

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


Re: [Tutor] question about the build-in function reversed in Python2.5

2011-12-24 Thread bob gailer

On 12/25/2011 12:02 AM, daedae11 wrote:
The build-in function reversed() in Python2.5  returns a iterator. But 
I don't know how to use the iterator.
Please give me a simple example about how to use bulid-in function 
reversed() to reverse a list.



>>> [x for x in reversed([1,2,3])]
[3, 2, 1]
>>> list(reversed([1,2,3]))
[3, 2, 1]

From the docs (it's all here though takes a bit of digging):

iterator

   An object representing a stream of data. Repeated calls to the
   iterator's next()  method return
   successive items in the stream. When no more data are available a
   StopIteration 
   exception is raised instead. At this point, the iterator object is
   exhausted and any further calls to its next()
method just raise StopIteration
again. Iterators
   are required to have an __iter__()
method that returns the
   iterator object itself so every iterator is also iterable and may be
   used in most places where other iterables are accepted. One notable
   exception is code which attempts multiple iteration passes. A
   container object (such as a list )
   produces a fresh new iterator each time you pass it to the iter()
function or use it in a for
loop. Attempting this with an
   iterator will just return the same exhausted iterator object used in
   the previous iteration pass, making it appear like an empty container.

   More information can be found in /Iterator Types/
   .

iterable
   A container object capable of returning its members one at a time.
   Examples of iterables include all sequence types (such as list
   , str , and
   tuple ) and some non-sequence types
   like dict  and file
and objects of any classes you define
   with an __iter__()  or
   __getitem__()  method.
   Iterables can be used in a for 
   loop and in many other places where a sequence is needed (zip()
   , map() ,
   ...). When an iterable object is passed as an argument to the
   built-in function iter() , it returns
   an iterator for the object. This iterator is good for one pass over
   the set of values. When using iterables, it is usually not necessary
   to call iter()  or deal with iterator
   objects yourself. The for statement does that automatically for you,
   creating a temporary unnamed variable to hold the iterator for the
   duration of the loop. See also /iterator/ <#term-iterator>,
   /sequence/ <#term-sequence>, and /generator/ <#term-generator>. 



   7.3. The for <#for> statement

The for <#for> statement is used to iterate over the elements of a 
sequence (such as a string, tuple or list) or other iterable object:


*for_stmt*  ::=  "for"target_list"in"expression_list 
   ":"suite  <#grammar-token-suite>
  ["else" ":"suite  <#grammar-token-suite>]

The expression list is evaluated once; it should yield an iterable 
object. An iterator is created for the result of the expression_list. 
The suite is then executed once for each item provided by the iterator, 
in the order of ascending indices. Each item in turn is assigned to the 
target list using the standard rules for assignments, and then the suite 
is executed. When the items are exhausted (which is immediately when the 
sequence is empty), the suite in the else <#else> clause, if present, is 
executed, and the loop terminates.


--
Bob Gailer
919-636-4239
Chapel Hill NC

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


[Tutor] question about the build-in function reversed in Python2.5

2011-12-24 Thread daedae11

The build-in function reversed() in Python2.5  returns a iterator. But I don't 
know how to use the iterator.
Please give me a simple example about how to use bulid-in function reversed() 
to reverse a list.

Thank you in advance.




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


Re: [Tutor] Question

2011-12-03 Thread Walter Prins
Hello Michael,

On 3 December 2011 08:31, Michael Hall  wrote:

> Andreas and others "Thank you for your help. I am still having an issues.
> I went to the links and they were very helpful.

Would you mind explaining exactly how they helped you? :)


> Here is my problem. If you enter the number 6 the program is just what the
> teacher wants.

Well, to be pedantic no, it's not just what the teacher wants.  The problem
states:
# a) write a function, getDivisors(), that returns a list of all
# of the positive divisors of a given number. for example -
# result = getDivisors(24)
# print(result)
# would yield: "[ 1, 2, 3, 4, 6, 8, 12]"

As your solution stands, the function getDivisors(num) that you have posted
does not return anything at all.   So you've not actually solved part a) of
this problem yet at all.

In the solution of part a) you should have the above snippet of code
somewhere in your program, and it should return the list as described when
run.

My problem is if you enter any other number it is wrong.

It is wrong because you have the answer for 6 hardcoded inside of your
getDivisors() function.  In other words, the *only* list your function can
return is [1,2,3] as that's what it returns explicitly.  To belabor the
point further: You never actually build the result list you want to return
later in the function.

Also, this problem is actually trying to work/solve the bigger problem of
deciding whether a given number input by the user is actually a perfect
number, rather than the first problem of writing a function to find the
divisors of a given number.   However, you simply cannot go and work on the
bigger problem before you have a demonstrably working solution to part a),
that is, a working getDivisors() function that actually returns a list of
divisors for a given number, correctly, for arbitrary input.

Do not pass go, do not collect $200 or £200 before you've completed this
task.  ;)

I would submit your real problem is not that the numer returned is wrong,
the real problem is that you don't seem to understand the basic building
blocks needed to solve this problem e.g:
a) how to use function calls to return results
b) working with Python lists (putting items into them, passing them around
etc.)

You absolutely must get a conceptual handle on calling functions and
returning results and working with lists in order to be able to solve this.

If I put the following requirement to you:
"Write a function that returns the square of the number given to it"
... would you be able how to solve it?  If not, what problems do you run
into/what do you not understand?

If I then put the following requirement to you:
"Write a function that will return the square of every number in the list
given to it (as a return list)"
... would you be able to solve it? If not, what problems do you run
into/what do you not understand?

I'd suggest trying the above questions and posting back your solution(s) to
them to help us establish that you do understanding functions and lists.

Finally, allow me to point out that you're top posting, that is, you're
posting your responses to previous emails at the top.  Please note that the
convention on this list is to bottom-post, or at least to follow responses
**below** relevant parts of emails inline, hence preserving the context in
easy reading order for both the participants and people who may not have
followed/read the question/answers provided up to that point.  If some
people bottom post and some top post it can become very difficult to follow
who said what when and makes helping on a list like this more work than it
would otherwise be.  Please help the people on this list trying to help you
by respecting this convention, thanks.

Cheers,

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


Re: [Tutor] Question

2011-12-03 Thread Alan Gauld

On 03/12/11 08:31, Michael Hall wrote:


# a) write a function, getDivisors(), that returns a list of all
# of the positive divisors of a given number.


This is a very clear statement of what you need to do.


def getDivisors(num):
 my_list = []
 sum = 0
 for number in range(1, num, 1):

 if num % number == 0:
 print([1, 2, 3])
 sum += num

 print('The sum is ', sum)
 if sum == num:
 print(num, 'is a perfect number')
 else:
 print(num, 'is not a perfect number')



problem. If you enter the number 6 the program is just what the teacher
wants. My problem is if you enter any other number it is wrong.


Even for 6 it is NOT what the teacher wants.
Your function PRINTS the answer the teacher asked for a function that 
RETURNS the answer. These are different things.

Do you understand the difference?

Also the reason it works for 6 is because you hard coded the answer for 6:

>  if num % number == 0:
>  print([1, 2, 3])

You only ever print [1,2,3]. You are not finding the divisors you are 
just printing [1,2,3].


Similarly the teacher did not ask you to test/report whether the number 
was perfect in the function, only to get the list of divisors. You need 
to strip the function back to the minimum to do what you were asked to do.


def getDivisors(num):
my_list = []
for x in range (1,num):
   # if is x a divisor of num
   # add x to my_list
return my_list

I've left the commented lines for you to complete.

But that is ALL you need for part (a) of the assignment.

You might need a main() function to test it, but it will simply print 
the result. Something like:


def main():
   print getDivisors(24)


As it is you are trying to do way too much and making your function more 
complicated than it needs to be. You can tweak it to make it more 
efficient later, but for now stick to the simplest thing that can 
possibly work and solve the problem you were asked to solve.


Once you have part (a) working part (b) of the assignment becomes easy.
But get (a) working before attempting (b). At the moment you are mixing 
the two together and making it more difficult. And that is one of the 
lessons from the homework. In programming, if you split a task down into 
smaller chunks it becomes easier. If you try to solve everything in one 
place it is much harder.


--
Alan G
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] Question on List Comprehensions

2011-11-22 Thread Steve Willoughby

On 21-Nov-11 23:49, Charles Becker wrote:

Alan, Steve, future readers,

After some re-reading and hacking I was able to discover the solution.  Since I 
raised the question here it is :

[['{0}'.format(x+1), x+1] for x in range(size)]


Just to fill out some other refinements for your information, if you're 
not planning to do anything special with the string formatting in each 
list, you don't really need to call format() when all it's doing is just 
making a string representation of the data value.  so

  '{0}'.format(x+1)
could just be
  str(x+1)

Resulting in:
  [[str(x+1), x+1] for x in range(size)]

Also, if you didn't like the repeated x+1 in there, you could just 
change the range call to go from 1..size directly:


  [[str(x), x] for x in range(1,size+1)]




--
Steve Willoughby / st...@alchemy.com
"A ship in harbor is safe, but that is not what ships are built for."
PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question on List Comprehensions

2011-11-21 Thread Charles Becker
Alan, Steve, future readers,

After some re-reading and hacking I was able to discover the solution.  Since I 
raised the question here it is :

[['{0}'.format(x+1), x+1] for x in range(size)]

This will create the list with nested lists for whatever number 'size' is set 
to.  This should be good enough to get anyone started on future problems in 
this area, and yes the redundancy present does make sense in the scope of what 
I'm working on. :)

Thanks!  I'll leave future questions on the backburner a little longer.
Charles

Sent from my iPhone

On Nov 21, 2011, at 7:04 PM, Alan Gauld  wrote:

> On 22/11/11 00:10, Steven D'Aprano wrote:
> 
>> Because you don't have a list comprehension. You can't put add arbitrary
>> code inside a square brackets [ ]. You have to follow the syntax for a
>> list comprehension:
>> 
>> listcomp = [expression for name in sequence]
>> 
>> not
>> 
>> listcomp = [expression for name in sequence another_command]
> 
> And being picky you can add a conditional after the loop:
> 
> > listcomp = [expression for name in sequence if some_condition]
> 
> But it must be an if test, nothing else will do.
> 
> -- 
> Alan G
> 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
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question on List Comprehensions

2011-11-21 Thread Charles Karl Becker
Steven and Alan,

Thank you for your comments!

Alan said:
>> Because you don't have a list comprehension. You can't put add arbitrary
>> code inside a square brackets [ ]. You have to follow the syntax for a
>> list comprehension:

This helps me understand a lot when looking back, I thought that any
operation done in place of defining the list literally was a list
comprehension.  I'm on wikipedia and a few tutorials now to refine and
will post back when I've come up with the solution I'm looking for
(and a comment as to if it's worth replacing a for loop with).

Thanks again!
Charles

On Mon, Nov 21, 2011 at 7:04 PM, Alan Gauld  wrote:
> On 22/11/11 00:10, Steven D'Aprano wrote:
>
>> Because you don't have a list comprehension. You can't put add arbitrary
>> code inside a square brackets [ ]. You have to follow the syntax for a
>> list comprehension:
>>
>> listcomp = [expression for name in sequence]
>>
>> not
>>
>> listcomp = [expression for name in sequence another_command]
>
> And being picky you can add a conditional after the loop:
>
>> listcomp = [expression for name in sequence if some_condition]
>
> But it must be an if test, nothing else will do.
>
> --
> Alan G
> 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
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question on List Comprehensions

2011-11-21 Thread Alan Gauld

On 22/11/11 00:10, Steven D'Aprano wrote:


Because you don't have a list comprehension. You can't put add arbitrary
code inside a square brackets [ ]. You have to follow the syntax for a
list comprehension:

listcomp = [expression for name in sequence]

not

listcomp = [expression for name in sequence another_command]


And being picky you can add a conditional after the loop:

> listcomp = [expression for name in sequence if some_condition]

But it must be an if test, nothing else will do.

--
Alan G
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] Question on List Comprehensions

2011-11-21 Thread Steven D'Aprano

Charles Karl Becker wrote:

I'm trying to use a list comprehension to build a list with a variable
number of lists nested within it (ideally eventually going several
levels of nesting).  However I seem to be observing some strange
behavior and was wondering if anyone could take a look at this and
tell me if what I'm trying to do with list comps is possible, or is a
map() or for loop the best thing here?



When in doubt, always use a for loop. List comps can't do anything that 
for loops can do, in fact they can do LESS.




I'm not worrying about incrementing the variables in the later
examples since I'm confused about their behavior (just simply adding
new elements to the list rather than nesting the lists; and then
setting the list to [none] in the last uncommented.  The last
commented one produces a syntax error, is it impossible to be
recursive with list comps like that or is my syntax just faulty?)


Your syntax is faulty. List comps are not full-blown replacements for 
for-loops, they are intentionally simple and straightforward.



board_size = 5
master_list = []

# this block produces the desired behavior
for c in range(board_size):
cell = ['', c+1]
master_list.append(cell)

print(master_list)

# I don't understand why this block behaves the way it does
master_list = []
master_list = [board_size * cell]
print(master_list)


You start of with master_list set to an empty list.

Then you immediately throw away that empty list, and set master_list to 
a list containing a single value, board_size * cell. Since by accident 
cell happens to equal a list left over from the previous part of code, 
you multiply a number 5 by a list ['', 5].


Multiplication of lists performs repetition:

py> ['a', 'b', 'c']*3
['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']

By the way, there is no list comprehension there. All you have is a list 
containing a single item.


[42] is not a list comp, it is a list containing a single item, 42.

[4*x] is not a list comp, it is a list containing a single item, 4*x 
(whatever x happens to be).


[4*x for x in (25, 36, 19, 5)] is a list comp.




# I also don't understand why this block behaves the way that it does
master_list = []
master_list = [master_list.append(cell)]
print(master_list)


You call master_list.append, which modifies master_list in place and 
returns None. So you append cell to master_list, then you create a new 
list [None], and set master_list to that new list, throwing away the 
work you did earlier.


Again, there is no list comprehension here either.



# this block produces a syntax error, and I'm not sure why
'''
master_list = []
master_list = [x for c in range(board_size) master_list.append(cell)]
print(master_list)
'''


Because you don't have a list comprehension. You can't put add arbitrary 
code inside a square brackets [ ]. You have to follow the syntax for a 
list comprehension:


listcomp = [expression for name in sequence]

not

listcomp = [expression for name in sequence another_command]



--
Steven

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


[Tutor] Question on List Comprehensions

2011-11-21 Thread Charles Karl Becker
I'm trying to use a list comprehension to build a list with a variable
number of lists nested within it (ideally eventually going several
levels of nesting).  However I seem to be observing some strange
behavior and was wondering if anyone could take a look at this and
tell me if what I'm trying to do with list comps is possible, or is a
map() or for loop the best thing here?

I'm not worrying about incrementing the variables in the later
examples since I'm confused about their behavior (just simply adding
new elements to the list rather than nesting the lists; and then
setting the list to [none] in the last uncommented.  The last
commented one produces a syntax error, is it impossible to be
recursive with list comps like that or is my syntax just faulty?)
Thanks!
Charles

Here's the raw code with my comments :

board_size = 5
master_list = []

# this block produces the desired behavior
for c in range(board_size):
cell = ['', c+1]
master_list.append(cell)

print(master_list)

# I don't understand why this block behaves the way it does
master_list = []
master_list = [board_size * cell]
print(master_list)

# I also don't understand why this block behaves the way that it does
master_list = []
master_list = [master_list.append(cell)]
print(master_list)

# this block produces a syntax error, and I'm not sure why
'''
master_list = []
master_list = [x for c in range(board_size) master_list.append(cell)]
print(master_list)
'''
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Question about graphics.

2011-11-09 Thread Nathaniel Trujillo
I installed livewires for python 2.x so should that work with python
version 2.7.2 ? I typed in the code you see below and got the following
error message.

Here is the code.

from livewires import games

and here is the error message

Traceback (most recent call last):
  File "C:/Python27/new_graphics_window.py", line 4, in 
from livewires import games
ImportError: No module named livewires

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


Re: [Tutor] Question about GUI applications.

2011-11-08 Thread Steve Willoughby

On 08-Nov-11 16:38, Alan Gauld wrote:

I note it says this sets the bitmap for the "iconified widget".
That to me means the icon on the desktop, or in the Taskbar.
Can you confirm that it also sets the icon at top left in
the title bar?


Yes, it changes the top left of the application window.

To test, I made a "G" image and installed it.  Here's a screenshot of 
the app window with and without that code.




--
Steve Willoughby / st...@alchemy.com
"A ship in harbor is safe, but that is not what ships are built for."
PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C
<><>___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about GUI applications.

2011-11-08 Thread Alan Gauld

On 08/11/11 15:56, Steve Willoughby wrote:


I have an app I'm developing and running successfully on Windows (as
well as OSX and Linux). At least in this case it is able to replace the
application icon in place of the default "TK" one. The code I use is:

root = Tkinter.Tk()
root.iconbitmap(default=ico_image_filename)



Steve,

I just checked the help:

-
>>> help (top.iconbitmap)
Help on method wm_iconbitmap in module tkinter:

wm_iconbitmap(self, bitmap=None, default=None) method of
tkinter.Tk instance
Set bitmap for the iconified widget to BITMAP. Return
the bitmap if None is given.
-

I note it says this sets the bitmap for the "iconified widget".
That to me means the icon on the desktop, or in the Taskbar.
Can you confirm that it also sets the icon at top left in
the title bar?

The basic icon was always set it is specifically the title
bar icon that was broken... Not having a Windows PC anymore
I can't test it...

--
Alan G
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] Question about GUI applications.

2011-11-08 Thread Alan Gauld

On 08/11/11 15:56, Steve Willoughby wrote:


I can't recall what it is, but its similar to the one used for setting
the title text on the Window, one of the wm_x calls.


I have an app I'm developing and running successfully on Windows ...

root = Tkinter.Tk()
root.iconbitmap(default=ico_image_filename)


Yep, that's the one I was thinking of. Looks like they must have fixed 
the problem. Last time I tried it ran without errors but didn't change 
the icon - that would have been with Python 2.2-3(ish) on Windows XP.

It was a known issue on the Tk forums...

Hmm, Googling, it looks like it was probably fixed in Tk 8.4.
Which is a wee while ago! :-)

Although I see it still being described as a bug up until April 2008 at 
least. The suggested "fix" being to edit the icon in wish.exe using a 
resource editor - yikes!




--
Alan G
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] Question about GUI applications.

2011-11-08 Thread Steve Willoughby

On 08-Nov-11 00:39, Alan Gauld wrote:

On 08/11/11 04:30, Nathaniel Trujillo wrote:

I just wrote the following GUI application. How do I get rid of the 7k
in the upper left hand corner and how to I put other stuff there like
say a picture of someone. Thanks for the help.


If you are using Windows I don't think you can, due to a bug in the
underlying Tk libraries. If you are using Linux/MacOS then there is a
function to replace the control icon.

I can't recall what it is, but its similar to the one used for setting
the title text on the Window, one of the wm_x calls.

But you might get a better response asking on the Tkinter mailing list...



I have an app I'm developing and running successfully on Windows (as 
well as OSX and Linux).  At least in this case it is able to replace the 
application icon in place of the default "TK" one.  The code I use is:


root = Tkinter.Tk()
root.iconbitmap(default=ico_image_filename)

(on Linux I use root.iconbitmap(bitmap='@'+xbm_filename))


--
Steve Willoughby / st...@alchemy.com
"A ship in harbor is safe, but that is not what ships are built for."
PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about GUI applications.

2011-11-08 Thread Alan Gauld

On 08/11/11 04:30, Nathaniel Trujillo wrote:

I just wrote the following GUI application. How do I get rid of the 7k
in the upper left hand corner and how to I put other stuff there like
say a picture of someone. Thanks for the help.


If you are using Windows I don't think you can, due to a bug in the 
underlying Tk libraries. If you are using Linux/MacOS then there is a 
function to replace the control icon.


I can't recall what it is, but its similar to the one used for setting 
the title text on the Window, one of the wm_x calls.


But you might get a better response asking on the Tkinter mailing list...

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


[Tutor] Question about GUI applications.

2011-11-07 Thread Nathaniel Trujillo
I just wrote the following GUI application. How do I get rid of the 7k in
the upper left hand corner and how to I put other stuff there like say a
picture of someone. Thanks for the help.

Here is the GUI application. It is called mad_lib.py.py

# Mad Lib
# Create a story based on user input
from tkinter import *
class Application(Frame):
""" GUI application that creates a story based on user input. """
def __init__(self, master):
""" Initialize Frame. """
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
""" Create widgets to get story infomation and to display story. """
# create instruction label
Label(self, text = "Enter information for a new story").grid(row =
0, column = 0, columnspan = 2, sticky = W)
# create a label and text entry for the name of a person
Label(self, text = "Person: ").grid(row = 1, column = 0, sticky = W)
self.person_ent = Entry(self)
self.person_ent.grid(row = 1, column = 1, sticky = W)
# create a label and text entry for a plural noun
Label(self, text = "Plural Noun:").grid(row = 2, column = 0, sticky
= W)
self.noun_ent = Entry(self)
self.noun_ent.grid(row = 2, column = 1, sticky = W)
# create a label and text entry for a verb
Label(self, text = "Verb:").grid(row = 3, column = 0, sticky = W)
self.verb_ent = Entry(self)
self.verb_ent.grid(row = 3, column = 1, sticky = W)
# create a label for adjectives check buttons
Label(self, text = "Adjective(s):").grid(row = 4, column = 0,
sticky = W)
# create itchy check button
self.is_itchy = BooleanVar()
Checkbutton(self, text = "itchy", variable =
self.is_itchy).grid(row = 4, column = 1, sticky = W)
# create joyous check button
self.is_joyous = BooleanVar()
Checkbutton(self, text = "joyous", variable =
self.is_joyous).grid(row = 4, column = 2, sticky = W)
# create electric check button
self.is_electric = BooleanVar()
Checkbutton(self, text = "electric", variable =
self.is_electric).grid(row = 4, column = 3, sticky = W)
# create a label for body parts radio buttons
Label(self, text = "Body Part:").grid(row = 5, column = 0, sticky =
W)
# create variable for single body part
self.body_part = StringVar()
self.body_part.set(None)
# create body part radio buttons
body_parts = ["bellybutton", "big toe", "medulla oblongata"]
column = 1
for part in body_parts:
Radiobutton(self, text = part, variable = self.body_part, value
= part).grid(row = 5, column = column, sticky = W)
column += 1
# create a submit button
Button(self, text = "Click for story", command =
self.tell_story).grid(row = 6, column = 0, sticky = W)
self.story_txt = Text(self, width = 75, height = 10, wrap = WORD)
self.story_txt.grid(row = 7, column = 0, columnspan = 4)
def tell_story(self):
""" Fill text box with new story based on user input. """
# gets values fom the GUI
person = self.person_ent.get()
noun = self.noun_ent.get()
verb = self.verb_ent.get()
adjectives = ""
if self.is_itchy.get():
adjectives += "itchy, "
if self.is_joyous.get():
adjectives += "joyous, "
if self.is_electric.get():
adjectives += "electric, "
body_part = self.body_part.get()
# create the story
story = "The famous explorer "
story += person
story += " had nearly given up a life-long quest to find The Lost
City of "
story += noun.title()
story += " when one day, the "
story += noun
story += " found "
story += person + "."
story += "A strong, "
story += adjectives
story += "peculiar feeling overwhelmed the explorer. "
story += "After all this time, the quest was finally over. A tear
came to "
story += person + "'s "
story += body_part + ". "
story += "And then, the "
story += noun
story += " promptly devoured "
story += person + "."
story += "The moral of the story? Be careful what you "
story += verb
story += " for."
# display the story
self.story_txt.delete(0.0, END)
self.story_txt.insert(0.0, story)
# main
root = Tk()
root.title("Mad Lib")
app = Application(root)
root.mainloop()
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about sorting a list within a dictionary within a list

2011-08-01 Thread Peter Otten
Peter Otten wrote:

> Untested:
> 
> from operator import attrgetter, itemgetter
> from itertools import imap
> 
> firsts = imap(itemgetter(0), conn.get_all_instances())
> reservations = sorted(firsts, key=attrgetter("launch_time"))
> 
> This gives you objects rather than the objects' __dict__s.

Oops, I think I missed one level of indirection:

firsts = (r.instances[0] for r in conn.get_all_instances())
reservations = sorted(firsts, key=attrgetter("launch_time"))
 


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


Re: [Tutor] Question about sorting a list within a dictionary within a list

2011-08-01 Thread Peter Otten
ian douglas wrote:

> On 08/01/2011 01:03 PM, Peter Otten wrote:
>> ian douglas wrote:
>>
>>> I'm using the Bono library for talking to EC2, and I'm getting a list of
>>>
>>> I cannot help you with the django or boto part.
> 
> Well, I suppose that using django/bono wasn't really relevant to the
> question.
> 
> I appreciate the feedback though, I'll definitely keep it in mind for
> future projects. The sort() and mykey() stuff you proposed looked neat.
> I'll dig into that stuff more to see how it works when I finish this
> project. I appreciate the LEGAL_SORTKEYS bit too, it was on my to-do
> list as well.
> 
> 
> In the end, I ended up flattening things a little, instead of having a
> list of objects, and those objects holding a list of instances, and each
> of those instances being objects themselves:
> 
>  reservations_bulk = conn.get_all_instances()
>  reservations_unsorted = [] ;
>  for reservation in reservations_bulk:
>  instance = reservation.instances[0].__dict__
>  reservations_unsorted.append(instance)
>  reservations = sorted(reservations_unsorted,
> key=itemgetter('launch_time'))
> 
> I'm sure there's an even cleaner way of doing the for loop too?

Untested:

from operator import attrgetter, itemgetter
from itertools import imap

firsts = imap(itemgetter(0), conn.get_all_instances())
reservations = sorted(firsts, key=attrgetter("launch_time"))

This gives you objects rather than the objects' __dict__s.

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


<    1   2   3   4   5   6   7   8   9   10   >