By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,611 Members | 870 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,611 IT Pros & Developers. It's quick & easy.

beginner, idiomatic python

P: n/a
Would someone like to suggest a replacement for this? It works ok,
but it doesn't look like any of the other code:

tempList = ['1','2','3','4','5','6','7','8']
sampleList=[]
for port in tempList:
pagefound = False
for i in range(self.parent.GetPageCount()):
page=self.parent.GetPage(i)
if hasattr(page, "port"):
if page.port == int(port):
pagefound=True
if not pagefound:
sampleList.append(port)

Thanks!
Aug 23 '07 #1
Share this Question
Share on Google+
21 Replies

P: n/a
bambam wrote:
Would someone like to suggest a replacement for this? It works ok,
but it doesn't look like any of the other code:

tempList = ['1','2','3','4','5','6','7','8']
sampleList=[]
for port in tempList:
pagefound = False
for i in range(self.parent.GetPageCount()):
page=self.parent.GetPage(i)
if hasattr(page, "port"):
if page.port == int(port):
pagefound=True
if not pagefound:
sampleList.append(port)

Thanks!

Look at good questions. This is a _very_ underspecified question.

One stab at mindreading:

def ported_pages(self):
for i in range(self.parent.GetPageCount()):
if hasattr(page, 'port'):
yield page

...
tempList = ['1','2','3','4','5','6','7','8']
missing = dict((int(v), v) for v in tempList)
for page in self.ported_pages():
if page.port in missing:
missing.pop(page.port)
if not missing:
break
sampleList = missing.values()
...

-Scott David Daniels
Aug 23 '07 #2

P: n/a
Does page count change? i.e. is it necessary to retrieve it in every
loop or
tempList = ['1','2','3','4','5','6','7','8']
sampleList=[]
page_count = self.parent.GetPageCount()
<snipped>
for i in range(page_count):

Also, once pagefound is set to True, all pages following will not be
appended to sampleList because it is not initialized to False under
the "for i in range(self.parent.GetPageCount())" loop.

Finally, if I understand the logic and question correctly, you want
something like
tempList = ['1','2','3','4','5','6','7','8']
sampleList=[]
page_count = self.parent.GetPageCount()
for port in tempList:
for i in range(page_count):
page=self.parent.GetPage(i)
if (hasattr(page, "port")) and (page.port != int(port)) :
sampleList.append(port)

or perhaps (I'm not sure)
tempList = [1, 2, 3, 4, 5, 6, 7, 8]
sampleList=[]
page_count = self.parent.GetPageCount()
for i in range(page_count):
page=self.parent.GetPage(i)
if (hasattr(page, "port")) and (page.port not in tempList) :
sampleList.append(port)
HTH

Aug 23 '07 #3

P: n/a
Wos! Several different thoughts:

An object using yield to return only the relevant pages, one at a time.
Pop to remove the items from the list.
A dictionary to map between the strings and the integers.

The dictionary was particularly unexpected. Eventually, I
plan to change the string ports to device names. On the other
hand, it looks like the only reason I have port numbers is
to use as an index in things like this.

After examining your suggestion, I realised that another thing
I am interested in could be generalised: I want the complement
of the set of ports in pages, given a universal set in tempList.
Ignoring the break condition for the moment, and my problem
with int(port)/str(port), would you have offered a different solution
if I had asked for the relative complement of a small set?

a= ['a','b','c']
b= ['b']
c= a-b #set theoretic difference, a\b, a.~b, ['a','c']

Steve.

"Zentrader" <ze********@gmail.comwrote in message
news:11********************@l22g2000prc.googlegrou ps.com...
Does page count change? i.e. is it necessary to retrieve it in every
loop or
tempList = ['1','2','3','4','5','6','7','8']
sampleList=[]
page_count = self.parent.GetPageCount()
<snipped>
for i in range(page_count):

Also, once pagefound is set to True, all pages following will not be
appended to sampleList because it is not initialized to False under
the "for i in range(self.parent.GetPageCount())" loop.

Finally, if I understand the logic and question correctly, you want
something like
tempList = ['1','2','3','4','5','6','7','8']
sampleList=[]
page_count = self.parent.GetPageCount()
for port in tempList:
for i in range(page_count):
page=self.parent.GetPage(i)
if (hasattr(page, "port")) and (page.port != int(port)) :
sampleList.append(port)

or perhaps (I'm not sure)
tempList = [1, 2, 3, 4, 5, 6, 7, 8]
sampleList=[]
page_count = self.parent.GetPageCount()
for i in range(page_count):
page=self.parent.GetPage(i)
if (hasattr(page, "port")) and (page.port not in tempList) :
sampleList.append(port)
HTH

Aug 24 '07 #4

P: n/a
En Thu, 23 Aug 2007 23:54:14 -0300, bambam <da***@asdf.asdfescribi�:
After examining your suggestion, I realised that another thing
I am interested in could be generalised: I want the complement
of the set of ports in pages, given a universal set in tempList.
Ignoring the break condition for the moment, and my problem
with int(port)/str(port), would you have offered a different solution
if I had asked for the relative complement of a small set?

a= ['a','b','c']
b= ['b']
c= a-b #set theoretic difference, a\b, a.~b, ['a','c']
If you want a set - just use a set:

pya = set(['a','b','c'])
pyb = set(['b'])
pyc = a-b
pyc
set(['a', 'c'])

--
Gabriel Genellina

Aug 24 '07 #5

P: n/a
Wos! Several different thoughts:

An object using yield to return only the relevant pages, one at a time.
Pop to remove the items from the list.
A dictionary to map between the strings and the integers.

The dictionary was particularly unexpected. Eventually, I
plan to change the string ports to device names. On the other
hand, it looks like the only reason I have port numbers is
to use as an index in things like this.

After examining your suggestion, I realised that another thing
I am interested in could be generalised: I want the complement
of the set of ports in pages, given a universal set in tempList.
Ignoring the break condition for the moment, and my problem
with int(port)/str(port), would you have offered a different solution
if I had asked for the relative complement of a small set?

a= ['a','b','c']
b= ['b']
c= a-b #set theoretic difference, a\b, a.~b, ['a','c']

Steve.

"Scott David Daniels" <da*****@dsl-only.netwrote in message
news:13*************@corp.supernews.com...
bambam wrote:
>Would someone like to suggest a replacement for this? It works ok,
but it doesn't look like any of the other code:

tempList = ['1','2','3','4','5','6','7','8']
sampleList=[]
for port in tempList:
pagefound = False
for i in range(self.parent.GetPageCount()):
page=self.parent.GetPage(i)
if hasattr(page, "port"):
if page.port == int(port):
pagefound=True
if not pagefound:
sampleList.append(port)

Thanks!

Look at good questions. This is a _very_ underspecified question.

One stab at mindreading:

def ported_pages(self):
for i in range(self.parent.GetPageCount()):
if hasattr(page, 'port'):
yield page

...
tempList = ['1','2','3','4','5','6','7','8']
missing = dict((int(v), v) for v in tempList)
for page in self.ported_pages():
if page.port in missing:
missing.pop(page.port)
if not missing:
break
sampleList = missing.values()
...

-Scott David Daniels

Aug 24 '07 #6

P: n/a
Excellent. By symmetry, I see that "list" casts the set back into a list.

I wonder why list has not been extended with the same (difference,
interesection) methods? Casting to set looks a little kludgy:

c = list(set(a)-set(b))

I wonder if that is clearer than the explicit loop?

Steve.

"Gabriel Genellina" <ga*******@yahoo.com.arwrote in message
news:ma**************************************@pyth on.org...
En Thu, 23 Aug 2007 23:54:14 -0300, bambam <da***@asdf.asdfescribi?:
>After examining your suggestion, I realised that another thing
I am interested in could be generalised: I want the complement
of the set of ports in pages, given a universal set in tempList.
Ignoring the break condition for the moment, and my problem
with int(port)/str(port), would you have offered a different solution
if I had asked for the relative complement of a small set?

a= ['a','b','c']
b= ['b']
c= a-b #set theoretic difference, a\b, a.~b, ['a','c']

If you want a set - just use a set:

pya = set(['a','b','c'])
pyb = set(['b'])
pyc = a-b
pyc
set(['a', 'c'])

--
Gabriel Genellina

Aug 24 '07 #7

P: n/a
bambam wrote:
Excellent. By symmetry, I see that "list" casts the set back into a list.

I wonder why list has not been extended with the same (difference,
interesection) methods? Casting to set looks a little kludgy:

c = list(set(a)-set(b))
I wonder if that is clearer than the explicit loop?
This isn't a "cast" in the sense of some less-strongly-typed languages;
it's just a conversion. The `list` function/type iterates over its
argument and turns it into a list. Sets are iterable, so that's all
that's really going on here.

The reason that lists don't have set-like methods is because lists
aren't sets -- lists can contain duplicate elements, whereas sets
cannot. You should use the proper type for your needs; if you want to
take two lists, remove duplicate elements, and then end up with a list,
then the sets-difference-and-then-make-a-list mechanism is appropriate.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
It [freedom] must be demanded by the oppressed.
-- Dr. Martin Luther King, Jr.
Aug 24 '07 #8

P: n/a
This isn't a "cast" in the sense of some less-strongly-typed languages;
it's just a conversion. The `list` function/type iterates over its
argument and turns it into a list. Sets are iterable, so that's all
that's really going on here.
oh :~). Learning experience happening here... Thank you.
The reason that lists don't have set-like methods is because
lists aren't sets -- lists can contain duplicate elements
Interesting point -- if that's all there is in it, then lists should
have difference and intersection methods. Not because they
are the same as sets -- because they are slightly different than
sets. In this case it doesn't matter - my lists don't contain
duplicate elements this time - but I have worked with lists in
money market and in inventory, and finding the intersection
and difference for matching off and netting out are standard
operations.
Still, any built in feature would probably be too simple to
use in any but the simplest cases.

Steve.

"Erik Max Francis" <ma*@alcyone.comwrote in message
news:Cq******************************@speakeasy.ne t...
bambam wrote:
>Excellent. By symmetry, I see that "list" casts the set back into a list.

I wonder why list has not been extended with the same (difference,
interesection) methods? Casting to set looks a little kludgy:

c = list(set(a)-set(b))
I wonder if that is clearer than the explicit loop?

This isn't a "cast" in the sense of some less-strongly-typed languages;
it's just a conversion. The `list` function/type iterates over its
argument and turns it into a list. Sets are iterable, so that's all
that's really going on here.

The reason that lists don't have set-like methods is because lists aren't
sets -- lists can contain duplicate elements, whereas sets cannot. You
should use the proper type for your needs; if you want to take two lists,
remove duplicate elements, and then end up with a list, then the
sets-difference-and-then-make-a-list mechanism is appropriate.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
It [freedom] must be demanded by the oppressed.
-- Dr. Martin Luther King, Jr.

Aug 24 '07 #9

P: n/a


bambam wrote:
>
In this case it doesn't matter - my lists don't contain
duplicate elements this time - but I have worked with lists in
money market and in inventory, and finding the intersection
and difference for matching off and netting out are standard
operations.
I would use a list comprehension for that case:

A = ['a','b','c','a','c','d']
U = ['a','b','e']
B = [x for x in A if x in U]

The result would be B==['a','b','a']

/MiO
Aug 24 '07 #10

P: n/a
That looks good, and perhaps a difference operator
would be too simple to be useful anyway.

Steve.

"Mikael Olofsson" <mi****@isy.liu.sewrote in message
news:ma**************************************@pyth on.org...
>

bambam wrote:
>>
In this case it doesn't matter - my lists don't contain
duplicate elements this time - but I have worked with lists in
money market and in inventory, and finding the intersection
and difference for matching off and netting out are standard
operations.

I would use a list comprehension for that case:

A = ['a','b','c','a','c','d']
U = ['a','b','e']
B = [x for x in A if x in U]

The result would be B==['a','b','a']

/MiO

Aug 27 '07 #11

P: n/a
En Sun, 26 Aug 2007 22:58:35 -0300, bambam <da***@asdf.asdfescribi�:
Ok, many environments are capable of cached evaluation
of functions without variable parameters so
range(5)
is cached, but
range(v) is re-evaluated every time. Is this defined
behaviour?
The range builtin function returns a list, and lists are mutable objects,
so it must return a *different* list each time.
That is, is it defined what Python does for
for i in f()
I'm sure it must be, but I haven't seen it yet. If I have
a user defined function returning a range, is it defined
that the range function is called on every loop? If I
have a function returning a range taking a parameter,
for i in f(v)
is it defined that the variable is evaluated for every loop?
Find all the (mostly negative) answers yourself in
<http://docs.python.org/ref/for.html>

--
Gabriel Genellina

Aug 27 '07 #12

P: n/a
bambam wrote:
That is, is it defined what Python does for
for i in f()
I'm sure it must be, but I haven't seen it yet. If I have
a user defined function returning a range, is it defined
that the range function is called on every loop? If I
have a function returning a range taking a parameter,
for i in f(v)
is it defined that the variable is evaluated for every loop?
Nope. Take the tutorial.

for i in f(v):
<suite>
is the same as:
iterator = iter(f(v))
for i in iterator:
<suite>

-Scott David Daniels
Sc***********@Acm.Org
Aug 27 '07 #13

P: n/a
Thank you, I have been through the tutorial several times, I guess
I'm just not smart enough. Perhaps I have been led astray by what
I read here?

My code started like this:

for i in range(self.parent.GetPageCount()):

I was asked:
>Does page count change? i.e. is it necessary to retrieve it in every loop

Is self.parent.GetPageCount() 'retrieved every loop'?

Steve.


"Gabriel Genellina" <ga*******@yahoo.com.arwrote in message
news:ma*************************************@pytho n.org...
En Sun, 26 Aug 2007 22:58:35 -0300, bambam <da***@asdf.asdfescribi?:
>Ok, many environments are capable of cached evaluation
of functions without variable parameters so
range(5)
is cached, but
range(v) is re-evaluated every time. Is this defined
behaviour?

The range builtin function returns a list, and lists are mutable objects,
so it must return a *different* list each time.
>That is, is it defined what Python does for
for i in f()
I'm sure it must be, but I haven't seen it yet. If I have
a user defined function returning a range, is it defined
that the range function is called on every loop? If I
have a function returning a range taking a parameter,
for i in f(v)
is it defined that the variable is evaluated for every loop?

Find all the (mostly negative) answers yourself in
<http://docs.python.org/ref/for.html>

--
Gabriel Genellina

Aug 27 '07 #14

P: n/a
Thank you, I have been through the tutorial several times, I guess
I'm just not smart enough. Python is quite different from the
languages I am familiar with.

My code sample started like this:
>>for i in range(self.parent.GetPageCount()):
I was asked:
>Does page count change? i.e. is it necessary to retrieve it in every loop

Is self.parent.GetPageCount() 'retrieved every loop'?

Steve.

"Scott David Daniels" <da*****@dsl-only.netwrote in message
news:13*************@corp.supernews.com...
bambam wrote:
>That is, is it defined what Python does for
for i in f()
I'm sure it must be, but I haven't seen it yet. If I have
a user defined function returning a range, is it defined
that the range function is called on every loop? If I
have a function returning a range taking a parameter,
for i in f(v)
is it defined that the variable is evaluated for every loop?

Nope. Take the tutorial.

for i in f(v):
<suite>
is the same as:
iterator = iter(f(v))
for i in iterator:
<suite>

-Scott David Daniels
Sc***********@Acm.Org

Aug 27 '07 #15

P: n/a
Is it safe to write

A = [x for x in A if x in U]

or is that undefined? I understand that the slice operation
can be used to make a temporary copy, so I could write

A=[x for x in A[:] if x in U]

but I've just copied that without any understanding.

Steve.
"bambam" <da***@asdf.asdfwrote in message
news:13*************@corp.supernews.com...
That looks good, and perhaps a difference operator
would be too simple to be useful anyway.

Steve.

"Mikael Olofsson" <mi****@isy.liu.sewrote in message
news:ma**************************************@pyth on.org...
>>

bambam wrote:
>>>
In this case it doesn't matter - my lists don't contain
duplicate elements this time - but I have worked with lists in
money market and in inventory, and finding the intersection
and difference for matching off and netting out are standard
operations.

I would use a list comprehension for that case:

A = ['a','b','c','a','c','d']
U = ['a','b','e']
B = [x for x in A if x in U]

The result would be B==['a','b','a']

/MiO


Aug 27 '07 #16

P: n/a
bambam <da***@asdf.asdfwrote:
Is it safe to write

A = [x for x in A if x in U]

or is that undefined? I understand that the slice operation
It's perfectly safe and well-defined, as the assignment rebinds the LHS
name only AFTER the RHS list comprehension is done.
Alex
Aug 27 '07 #17

P: n/a
bambam <da***@asdf.asdfwrote:
...
Bags don't seem to be built in to my copy of Python, and
A "bag" is a collections.defaultdict(int) [[you do have to import
collections -- it's in the standard library, NOT built-in]].
Alex
Aug 27 '07 #18

P: n/a
Thank you.

Steve.

"Alex Martelli" <al***@mac.comwrote in message
news:1i**************************@mac.com...
bambam <da***@asdf.asdfwrote:
>Is it safe to write

A = [x for x in A if x in U]

or is that undefined? I understand that the slice operation

It's perfectly safe and well-defined, as the assignment rebinds the LHS
name only AFTER the RHS list comprehension is done.
Alex

Aug 27 '07 #19

P: n/a
bambam a crit :
Thank you, I have been through the tutorial several times, I guess
I'm just not smart enough. Perhaps I have been led astray by what
I read here?

My code started like this:

for i in range(self.parent.GetPageCount()):

I was asked:
>Does page count change? i.e. is it necessary to retrieve it in every loop


Is self.parent.GetPageCount() 'retrieved every loop'?
If your question is 'is self.parent.GetPageCount()' called for each
iteration of this loop, then the answer is obviously 'no', and it's
quite easy to check it out:

Python 2.5.1 (r251:54863, May 2 2007, 16:56:35)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>def test():
.... print "test called"
.... return range(5)
....
>>for x in test(): print x
....
test called
0
1
2
3
4
>>>

Now if you need to use the result of self.parent.GetPageCount() more
than once in the same function and this result is not likely to change
during the function's execution, you're certainly better storing it in a
local variable - but now that's such a CS101 thing that it's probably
not even worth mentionning.

IOW, Zentrader's remark was at best misleading, at worst plain wrong...
Aug 27 '07 #20

P: n/a
On 2007-08-27, Neil Cerutti <ho*****@yahoo.comwrote:
This sort of suggests a direct solution:

for i in xrange(self.parent.GetPageCount()):
if i >= self.parent.GetPageCount():
break
# do stuff

At least that way you're spared the manual manipulation of i.
On second thought, that last suggestion is flawed, as a growing
page count would be ignored. Please ignore.

--
Neil Cerutti
Whenever I see a homeless guy, I always run back and give him money, because I
think: Oh my God, what if that was Jesus? --Pamela Anderson
Aug 27 '07 #21

P: n/a
Neil Cerutti <ho*****@yahoo.comwrites:
i = 0
while i < self.parent.GetPageCount():
# do stuff
i += 1
Alternatively:

from itertools import count

for i in count():
if i >= self.parent.GetPageCount():
break
...
Aug 27 '07 #22

This discussion thread is closed

Replies have been disabled for this discussion.