473,581 Members | 2,224 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Better writing in python

I'm just wondering, if I could write a in a "better" way this code

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.appe nd(arg)
else:
lOptional.appen d(arg)
return (lMandatory, lOptional)

I think there is a better way, but I can't see how...

Oct 24 '07 #1
19 1857
On Wed, 24 Oct 2007 12:09:40 +0000, Alexandre Badez wrote:
I'm just wondering, if I could write a in a "better" way this code

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.appe nd(arg)
else:
lOptional.appen d(arg)
return (lMandatory, lOptional)

I think there is a better way, but I can't see how...
Drop the prefixes. `l` is for list? `d` is for what!? Can't be
dictionary because the code doesn't make much sense.

Where is `cls` coming from?

Ciao,
Marc 'BlackJack' Rintsch
Oct 24 '07 #2
On Oct 24, 1:09 pm, Alexandre Badez <alexandre.ba.. .@gmail.comwrot e:
I'm just wondering, if I could write a in a "better" way this code

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.appe nd(arg)
else:
lOptional.appen d(arg)
return (lMandatory, lOptional)

I think there is a better way, but I can't see how...
import operator
return filter(cls.dArg uments), filter(operator .not_, cls.dArguments)

Or just:

mandatory = [arg for arg in cls.dArguments in arg]
optional = [arg for arg in cls.dArguments in not arg]
return mandatory, optional

--
Paul Hankin

Oct 24 '07 #3
On Oct 24, 1:09 pm, Alexandre Badez <alexandre.ba.. .@gmail.comwrot e:
I'm just wondering, if I could write a in a "better" way this code

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.appe nd(arg)
else:
lOptional.appen d(arg)
return (lMandatory, lOptional)

I think there is a better way, but I can't see how...
import operator
return filter(cls.dArg uments), filter(operator .not_, cls.dArguments)

Or just:

mandatory = [arg for arg in cls.dArguments in arg]
optional = [arg for arg in cls.dArguments in not arg]
return mandatory, optional

--
Paul Hankin

Oct 24 '07 #4
On Oct 24, 1:09 pm, Alexandre Badez <alexandre.ba.. .@gmail.comwrot e:
I'm just wondering, if I could write a in a "better" way this code

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.appe nd(arg)
else:
lOptional.appen d(arg)
return (lMandatory, lOptional)

I think there is a better way, but I can't see how...
import operator
return filter(cls.dArg uments), filter(operator .not_, cls.dArguments)

Or just:

mandatory = [arg for arg in cls.dArguments in arg]
optional = [arg for arg in cls.dArguments in not arg]
return mandatory, optional

--
Paul Hankin

Oct 24 '07 #5
On Oct 24, 7:09 am, Alexandre Badez <alexandre.ba.. .@gmail.comwrot e:
I'm just wondering, if I could write a in a "better" way this code

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.appe nd(arg)
else:
lOptional.appen d(arg)
return (lMandatory, lOptional)

I think there is a better way, but I can't see how...
You might look into list comprehensions. You could probably do this
with two of them:

<code>
# completely untested
lMandatory = [arg for arg in cls.dArguments if arg is True]
lOptional = [arg for arg in cls.dArguments if arg is False]
</code>

Something like that. I'm not the best with list comprehensions, so I
may have the syntax just slightly off. See the following links for
more information:

http://www.secnetix.de/olli/Python/l...ehensions.hawk
http://docs.python.org/tut/node7.html

Mike

Oct 24 '07 #6
On 2007-10-24, Alexandre Badez <al************ *@gmail.comwrot e:
I'm just wondering, if I could write a in a "better" way this
code

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.appe nd(arg)
else:
lOptional.appen d(arg)
return (lMandatory, lOptional)

I think there is a better way, but I can't see how...
I don't think there's much improvement to be made. What are your
particular concerns? Is it too slow? Too verbose? Does it not
work correctly?

It appears to be an application of itertools.group by, but that'll
almost certainly be less efficient. To use groupby, you have to
sort by your predicate, and build lists to save results. Your for
loop avoids the sorting.

Here's some instrumentality for ya:

from itertools import groupby
from operator import truth
from collections import defaultdict

result = defaultdict(lis t)
for k, g in groupby(sorted( cls.dArguments, key=truth), truth):
result[k].extend(g)

I like your initial attempt better.

P.S. I didn't realize until working out this example that extend
could consume an iterator.

--
Neil Cerutti
The word "genius" isn't applicable in football. A genius is a guy like Norman
Einstein. --Joe Theisman
Oct 24 '07 #7
Hi Alexandre,

On Oct 24, 2:09 pm, Alexandre Badez <alexandre.ba.. .@gmail.comwrot e:
I'm just wondering, if I could write a in a "better" way this code
Please tell us, what it is you want to achieve. And give us some
context
for this function.
lMandatory = []
lOptional = []
for arg in cls.dArguments:
if arg is True:
lMandatory.appe nd(arg)
else:
lOptional.appen d(arg)
return (lMandatory, lOptional)
This snippet will seperate d.Arguments into two lists: one that
holds all elements that are references to True(!) and another list
that holds the rest. The condition 'if args is True' will only
be hold if arg actually _is_ the object _True_. This is probably
not what you want. Apart from that, you might go with

lMandatory = [ arg for arg in cls.dArguments if condition() ]
lOptional = [ arg for arg in cls.dArguments if not condition() ]

the second line could be rewritten

lOptional = list(set(cls.dA rguments)-set(lMandatory) )

If lMandatory and lOptional do not need to be lists, you can also
write

lMandatory = set(arg for arg in cls.dArguments if condition())
lOptional = set(cls.dArgume nts) - lMandatory

But please, give us some more context of what you want to do.

- harold -

Oct 24 '07 #8
Thanks for your try Cliff, I was very confused :P
More over I made some mistake when I post (to make it easiest).

Here is my real code:

with
dArguments = {
'argName' : {
'mandatory' : bool, # True or False
[...], # other field we do not care here
}
}

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if cls.dArguments[arg]['mandatory']:
lMandatory.appe nd(arg)
else:
lOptional.appen d(arg)
return (lMandatory, lOptional)

So, as you see, we agree each other about "if bool" or "if bool is
True" ;)

So, my question was how to give it a better 'python like' look ?
Any idea ?

Oct 24 '07 #9
Alexandre Badez <al************ *@gmail.comwrot e:
Thanks for your try Cliff, I was very confused :P
More over I made some mistake when I post (to make it easiest).

Here is my real code:

with
dArguments = {
'argName' : {
'mandatory' : bool, # True or False
[...], # other field we do not care here
}
}

lMandatory = []
lOptional = []
for arg in cls.dArguments:
if cls.dArguments[arg]['mandatory']:
lMandatory.appe nd(arg)
else:
lOptional.appen d(arg)
return (lMandatory, lOptional)

So, as you see, we agree each other about "if bool" or "if bool is
True" ;)

So, my question was how to give it a better 'python like' look ?
Any idea ?

For a 'python like' look lose the Hungarian notation (even Microsoft
have largely stopped using it), increase the indentation to 4 spaces,
and also get rid of the spurious parentheses around the result.
Otherwise it is fine: clear and to the point.

If you really wanted you could write something like:

m, o = [], []
for arg in cls.dArguments:
(m if cls.dArguments[arg]['mandatory'] else o).append(arg)
return m, o

Or even:
m, o = [], []
action = [o.append, m.append]
for arg in cls.dArguments:
action[bool(cls.dArgum ents[arg]['mandatory'])](arg)
return m, o

but it just makes the code less clear, so why bother?
Oct 24 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
2135
by: Bengt Richter | last post by:
>>> hex(-5) __main__:1: FutureWarning: hex()/oct() of negative int will return a signed string in Python 2.4 and up '0xfffffffb' >>> hex(-5) '0xfffffffb' >>> hex(-5L) '-0x5L' That is sooo ugly. I suppose it is for a backwards compatible repr, but couldn't we
220
18931
by: Brandon J. Van Every | last post by:
What's better about Ruby than Python? I'm sure there's something. What is it? This is not a troll. I'm language shopping and I want people's answers. I don't know beans about Ruby or have any preconceived ideas about it. I have noticed, however, that every programmer I talk to who's aware of Python is also talking about Ruby. So it...
6
1664
by: Michael | last post by:
Hi, I'm fairly new at Python, and have the following code that works but isn't very concise, is there a better way of writing it?? It seems much more lengthy than python code i have read..... :-) (takes a C++ block and extracts the namespaces from it) def ExtractNamespaces(data): print("Extracting Namespaces")
2
3771
by: Bryan Olson | last post by:
The current Python standard library provides two cryptographic hash functions: MD5 and SHA-1 . The authors of MD5 originally stated: It is conjectured that it is computationally infeasible to produce two messages having the same message digest. That conjecture is false, as demonstrated by Wang, Feng, Lai and Yu in 2004 . Just recently,...
6
1450
by: Dan Jacobson | last post by:
Can I feel even better about using perl vs. python, as apparently python's dependence of formatting, indentation, etc. vs. perl's "(){};" etc. makes writing python programs perhaps very device dependent. Whereas perl can be written on a tiny tiny screen, and can withstand all kinds of users with various disabilities, etc.? Also perl is easier...
6
1449
by: Anton Vredegoor | last post by:
Since a few days I've been experimenting with a construct that enables me to send the sourcecode of the web page I'm reading through a Python script and then into a new tab in Mozilla. The new tab is automatically opened so the process feels very natural, although there's a lot of reading, filtering and writing behind the scene. I want to...
7
1791
by: apollonius2 | last post by:
Greetings, I have been working on a little project today to help me better understand classes in Python (I really like Python). I am a self taught programmer and consider myself to fall in the "beginner" category for sure. It was initially sparked by reading about "state machines". This was my attempt at it however I feel it is not quite...
3
1528
by: koutoo | last post by:
I have a code that writes to 2 seperate files. I keep getting a "list index out of range" error. The strange part is that when checking the files that I'm writing too, the script has already iterated through and finished writing, yet the error stated implies that it hasn't? So how can it be, that my script has written to the files, yet the...
13
1164
by: Marco Bizzarri | last post by:
Sorry... pressed enter but really didn't want to. As I said, let's say I have a class class A: def __init__(self): self.x = None
0
8144
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8301
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7894
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8169
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5670
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5361
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3803
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2300
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1400
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.