473,395 Members | 1,613 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

beginner, idiomatic python

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


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
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
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
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
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
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
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
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
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
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Art | last post by:
NEWBIE ALERT! Esteemed List Participants and Lurkers: (System: P-II 350, 192 meg, Win98 SE, Python 2.2.3, wxPythonWIN32-2.4.1.2-Py22.exe) I'm having a lot of fun getting started with Python...
1
by: sarmin | last post by:
Hi Gurus... I am using pythonwin to write the programming code and boa constructor to build the GUI... the GUI and the python code work fine when run through pythonwin platform... i m now...
6
by: Atip Asvanund | last post by:
Dear sirs, I am trying to learn how to use Boehm's garbage collector: http://www.hpl.hp.com/personal/Hans_Boehm/gc/ on a Linux machine. I am a beginner, and I find its documentation inadequate....
6
by: Alex | last post by:
Hello I am intersting in developing and my background is VBA used in Excel and a brief intro to Java. I am interested in learning beyond VB and feel that C++ would be a very good language to...
6
by: Qun Cao | last post by:
Hi Everyone, I am a beginner on cross language development. My problem at hand is to build a python interface for a C++ application built on top of a 3D game engine. The purpose of this python...
4
by: Steven W. Orr | last post by:
I understand that two leading underscores in a class attribute make the attribute private. But I often see things that are coded up with one underscore. Unless I'm missing something, there's a...
2
by: Steven W. Orr | last post by:
On Friday, Feb 23rd 2007 at 11:12 -0500, quoth Steven W. Orr: =>I understand that two leading underscores in a class attribute make the =>attribute private. But I often see things that are coded...
11
by: bambam | last post by:
Would someone like to suggest a replacement for this? This is a function that returns different kinds of similar objects, depending on what is asked for. PSP and PWR are classes. I don't really...
3
by: James Fassett | last post by:
Hi all, Simple question really on a best practice. I want to avoid adding duplicates to a list. my_list = dup_map = {} for item in my_list: dup_map = True
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.