hi
in my code, i use dict(a) to make to "a" into a dictionary , "a" comes
from user input, so my program does not know in the first place. Then
say , it becomes
a = { '-A' : 'value1' , '-B' : "value2" , "-C" : "value3" , '-D' :
'value4' }
somewhere next in my code, i will check for these..:
1) -A and -B cannot exist together
2) -A and -C cannot exist together
3) -A and -B and -D cannot exist together
4) and lots of other combinations to check for....
how can i efficiently check for the above? At first as i do simple
checks , i use if and else.
But as i began to check for more combinatoiuns, it gets messy....
thanks. 5 1679
def all(s):
for x in s:
if not x: return False
return True
bad_combos = [['-A', '-B'], ['-A', '-C'], ...]
for bad_combo in bad_combos:
assert not all([bad_elem in a for bad_elem in bad_combo]) mi*******@hotma il.com wrote: hi in my code, i use dict(a) to make to "a" into a dictionary , "a" comes from user input, so my program does not know in the first place. Then say , it becomes
a = { '-A' : 'value1' , '-B' : "value2" , "-C" : "value3" , '-D' : 'value4' }
somewhere next in my code, i will check for these..:
1) -A and -B cannot exist together 2) -A and -C cannot exist together 3) -A and -B and -D cannot exist together 4) and lots of other combinations to check for....
how can i efficiently check for the above? At first as i do simple checks , i use if and else. But as i began to check for more combinatoiuns, it gets messy....
thanks. mi*******@hotma il.com a écrit : hi in my code, i use dict(a) to make to "a" into a dictionary , "a" comes from user input, so my program does not know in the first place. Then say , it becomes
a = { '-A' : 'value1' , '-B' : "value2" , "-C" : "value3" , '-D' : 'value4' }
somewhere next in my code, i will check for these..:
1) -A and -B cannot exist together 2) -A and -C cannot exist together 3) -A and -B and -D cannot exist together 4) and lots of other combinations to check for....
Looks like an option parser... If so, there's all you need in the
standard lib (look for the optparse module). how can i efficiently check for the above? At first as i do simple checks , i use if and else. But as i began to check for more combinatoiuns, it gets messy....
First : use boolean logic (truth table, Kernaugh diagram, etc) to
simplify things. As an example, rule #3 is useless - it's a subset of
rule #1 (-A and -B and -D implies -A and -B). This should greatly reduce
the number of needed tests.
Then, write a simple rule system describing either valid inputs or
invalid inputs (preferably the smallest set !-). FWIW, it can be as
simple as a list of lambdas/error messages pairs, with lambdas being
predicate taking dict keys as params:
_RULES = [
(lambda keys : '-A' in keys and '-B' in keys,
"can't have both options -A and -B"),
(lambda keys : '-A' in keys and '-C' in keys,
"can't have both options -A and -C"),
# etc...
]
def validate(option s, rules):
keys = options.keys()
for predicate, message in rules:
if not predicate(keys) :
raise ValueError(mess age)
On 5/06/2006 10:46 PM, Bruno Desthuilliers wrote: mi*******@hotma il.com a écrit : hi in my code, i use dict(a) to make to "a" into a dictionary , "a" comes from user input, so my program does not know in the first place. Then say , it becomes
a = { '-A' : 'value1' , '-B' : "value2" , "-C" : "value3" , '-D' : 'value4' }
somewhere next in my code, i will check for these..:
1) -A and -B cannot exist together 2) -A and -C cannot exist together 3) -A and -B and -D cannot exist together 4) and lots of other combinations to check for.... Looks like an option parser... If so, there's all you need in the standard lib (look for the optparse module).
how can i efficiently check for the above? At first as i do simple checks , i use if and else. But as i began to check for more combinatoiuns, it gets messy....
First : use boolean logic (truth table, Kernaugh diagram, etc) to simplify things. As an example, rule #3 is useless - it's a subset of rule #1 (-A and -B and -D implies -A and -B). This should greatly reduce the number of needed tests.
Good idea, but doesn't scale well. Simple code can weed out redundant
rules, including any accidental duplicates that may creep into a long
list. See code listing at end. Then, write a simple rule system describing either valid inputs or invalid inputs (preferably the smallest set !-). FWIW, it can be as simple as a list of lambdas/error messages pairs, with lambdas being predicate taking dict keys as params:
_RULES = [ (lambda keys : '-A' in keys and '-B' in keys, "can't have both options -A and -B"), (lambda keys : '-A' in keys and '-C' in keys, "can't have both options -A and -C"), # etc... ]
The evil HR director won't let the PHB pay me on a per LOC basis, so
I've had to come up with a compact table-driven approach :-)
def validate(option s, rules): keys = options.keys() for predicate, message in rules: if not predicate(keys) : raise ValueError(mess age)
Cheers,
John
C:\junk>type option_combos.p y
bad_combos = ['ABD', 'AC', 'AB', 'CA']
def rule_compaction (bc_list, verbose=False):
# The next few lines are admittedly oldfashioned :-)
bc_sets = [set(x) for x in bc_list]
deco = [(len(y), y) for y in bc_sets]
deco.sort()
bc_sets = [z[1] for z in deco]
del deco
if verbose:
print "bc_sets #1:", bc_sets
for k in xrange(len(bc_s ets)-1, 0, -1):
candidate = bc_sets[k]
for ko in bc_sets[:k]:
if ko <= candidate:
if verbose:
print candidate, "knocked out by", ko
del bc_sets[k]
break
if verbose:
print "bc_sets #2:", bc_sets
return bc_sets
option_rules = rule_compaction (bad_combos, verbose=True)
def combo_disallowe d_by(opt_set, rules):
for rule in rules:
if opt_set >= rule:
return rule
return None # redundantly, for emphasis
if __name__ == "__main__":
import sys
for opt_string in sys.argv[1:]:
failer = combo_disallowe d_by(set(opt_st ring), option_rules)
if failer:
print repr(opt_string ), "disallowed by", failer
else:
print repr(opt_string ), "is OK"
=== a test ===
C:\junk>option_ combos.py A AB AC AD BC ABD ABX XBA BX
bc_sets #1: [set(['A', 'C']), set(['A', 'B']), set(['A', 'C']),
set(['A', 'B', 'D'])]
set(['A', 'B', 'D']) knocked out by set(['A', 'B'])
set(['A', 'C']) knocked out by set(['A', 'C'])
bc_sets #2: [set(['A', 'C']), set(['A', 'B'])]
'A' is OK
'AB' disallowed by set(['A', 'B'])
'AC' disallowed by set(['A', 'C'])
'AD' is OK
'BC' is OK
'ABD' disallowed by set(['A', 'B'])
'ABX' disallowed by set(['A', 'B'])
'XBA' disallowed by set(['A', 'B'])
'BX' is OK
=== the end ===
John Machin wrote: On 5/06/2006 10:46 PM, Bruno Desthuilliers wrote:
mi*******@hotma il.com a écrit :
hi in my code, i use dict(a) to make to "a" into a dictionary , "a" comes from user input, so my program does not know in the first place. Then say , it becomes
a = { '-A' : 'value1' , '-B' : "value2" , "-C" : "value3" , '-D' : 'value4' }
somewhere next in my code, i will check for these..:
1) -A and -B cannot exist together 2) -A and -C cannot exist together 3) -A and -B and -D cannot exist together 4) and lots of other combinations to check for....
Looks like an option parser... If so, there's all you need in the standard lib (look for the optparse module).
how can i efficiently check for the above? At first as i do simple checks , i use if and else. But as i began to check for more combinatoiuns, it gets messy....
First : use boolean logic (truth table, Kernaugh diagram, etc) to simplify things. As an example, rule #3 is useless - it's a subset of rule #1 (-A and -B and -D implies -A and -B). This should greatly reduce the number of needed tests.
Good idea, but doesn't scale well.
Does it need to scale ? If there are lot of rules and frequently
changing, yes, automating the process will be a good idea - but if it's
about a program options, just using one's brain might be enough. At
least it forces one to think about what's going on...
Simple code can weed out redundant rules,
Simple code can weed out redundant *simple* rules !-)
(snip) Then, write a simple rule system describing either valid inputs or invalid inputs (preferably the smallest set !-). FWIW, it can be as simple as a list of lambdas/error messages pairs, with lambdas being predicate taking dict keys as params:
_RULES = [ (lambda keys : '-A' in keys and '-B' in keys, "can't have both options -A and -B"), (lambda keys : '-A' in keys and '-C' in keys, "can't have both options -A and -C"), # etc... ]
The evil HR director won't let the PHB pay me on a per LOC basis, so I've had to come up with a compact table-driven approach :-)
<ot>I'm my own evil HR director and PHB !-)</ot>
Don't like table-driven programming, John ?
This solution takes very few lines, and while it's surely not a
full-blown rule engine, it's at least reasonably flexible.
(Not to say it's better than yours - it's of course a matter of
effective use case). def validate(option s, rules): keys = options.keys() for predicate, message in rules: if not predicate(keys) : raise ValueError(mess age) C:\junk>type option_combos.p y bad_combos = ['ABD', 'AC', 'AB', 'CA']
def rule_compaction (bc_list, verbose=False): # The next few lines are admittedly oldfashioned :-) bc_sets = [set(x) for x in bc_list] deco = [(len(y), y) for y in bc_sets] deco.sort() bc_sets = [z[1] for z in deco] del deco if verbose: print "bc_sets #1:", bc_sets for k in xrange(len(bc_s ets)-1, 0, -1): candidate = bc_sets[k] for ko in bc_sets[:k]: if ko <= candidate: if verbose: print candidate, "knocked out by", ko del bc_sets[k] break if verbose: print "bc_sets #2:", bc_sets return bc_sets
Nice code - but how does it handle more complex predicates ? Seems you
can only deal with 'and' rules here. <nitpick>"Doesn 't scale well", you
said ?-)</nitpick>
(snip)
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
On 6/06/2006 8:38 PM, bruno at modulix wrote: John Machin wrote: On 5/06/2006 10:46 PM, Bruno Desthuilliers wrote:
mi*******@hotma il.com a écrit :
hi in my code, i use dict(a) to make to "a" into a dictionary , "a" comes from user input, so my program does not know in the first place. Then say , it becomes
a = { '-A' : 'value1' , '-B' : "value2" , "-C" : "value3" , '-D' : 'value4' }
somewhere next in my code, i will check for these..:
1) -A and -B cannot exist together 2) -A and -C cannot exist together 3) -A and -B and -D cannot exist together 4) and lots of other combinations to check for....
Looks like an option parser... If so, there's all you need in the standard lib (look for the optparse module).
how can i efficiently check for the above? At first as i do simple checks , i use if and else. But as i began to check for more combinatoiuns, it gets messy....
First : use boolean logic (truth table, Kernaugh diagram, etc) to simplify things. As an example, rule #3 is useless - it's a subset of rule #1 (-A and -B and -D implies -A and -B). This should greatly reduce the number of needed tests. Good idea, but doesn't scale well.
Does it need to scale ? If there are lot of rules and frequently changing, yes, automating the process will be a good idea - but if it's about a program options, just using one's brain might be enough. At least it forces one to think about what's going on...
Simple code can weed out redundant rules,
Simple code can weed out redundant *simple* rules !-)
(snip)
Then, write a simple rule system describing either valid inputs or invalid inputs (preferably the smallest set !-). FWIW, it can be as simple as a list of lambdas/error messages pairs, with lambdas being predicate taking dict keys as params:
_RULES = [ (lambda keys : '-A' in keys and '-B' in keys, "can't have both options -A and -B"), (lambda keys : '-A' in keys and '-C' in keys, "can't have both options -A and -C"), # etc... ] The evil HR director won't let the PHB pay me on a per LOC basis, so I've had to come up with a compact table-driven approach :-)
<ot>I'm my own evil HR director and PHB !-)</ot>
<ot> You must have some interesting conversations with yourself !-) </ot> Don't like table-driven programming, John ?
I love table-driven programming. You seem to misunderstand; In this case
the "bad combos" list *is* the table. This solution takes very few lines, and while it's surely not a full-blown rule engine, it's at least reasonably flexible.
(Not to say it's better than yours - it's of course a matter of effective use case).
[snip] Nice code - but how does it handle more complex predicates ? Seems you can only deal with 'and' rules here.
More complex predicates are not in the OP's spec ... this is a defence I
learned from somebody in this newsgroup recently :-)
<nitpick>"Doesn 't scale well", you said ?-)</nitpick>
I understand 'scale' to relate to size, not to complexity.
Cheers,
John This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: none |
last post by:
or is it just me?
I am having a problem with using a dictionary as an attribute of a
class. This happens in python 1.5.2 and 2.2.2 which I am accessing
through pythonwin builds 150 and 148 respectively
In the sample code you see that I have class Item and class Dict
class Dict contains a dictionary called items. The items dictionary
will contain instances of Item that are keyed off of the Item name. In
__main__ I create two...
|
by: Egor Bolonev |
last post by:
why functions created with lambda forms cannot contain statements?
how to get unnamed function with statements?
|
by: Rakesh |
last post by:
Hi,
For a particular problem of mine, I want to sort <key, value> pairs
by its value.
Eg:
Input:
A, 4
B, 5
|
by: Noah |
last post by:
I have a dictionary that I would like to expand to satisfy a
function's agument list. I can used the ** syntax to pass a dictionary,
but
this only works if each key in the dictionary matches an argument.
I cannot pass a dictionary that has more keys than the function has
arguments.
# Example 1 - This works:
# Prints "hello world!"
def foo (arg1='greetings', arg2='planet', arg3='.'):
|
by: jg |
last post by:
I was trying to get custom dictionary class that can store generic or
string; So I started with the example given by the visual studio 2005 c#
online help for simpledictionay object
That seem to miss a few things including #endregion directive and the ending
class }
Is there not a simple way like in dotnet vb?
I managed to get the sample to code to this:
| |
by: Christoph Zwerschke |
last post by:
Ok, the answer is easy: For historical reasons - built-in sets exist
only since Python 2.4.
Anyway, I was thinking about whether it would be possible and desirable
to change the old behavior in future Python versions and let dict.keys()
and dict.values() both return sets instead of lists.
If d is a dict, code like:
for x in d.keys():
|
by: vatamane |
last post by:
This has been bothering me for a while. Just want to find out if it
just me or perhaps others have thought of this too: Why shouldn't the
keyset of a dictionary be represented as a set instead of a list? I
know that sets were introduced a lot later and lists/dictionaries were
used instead but I think "the only correct way" now is for the
dictionary keys and values to be sets. Presently {1:0,2:0,3:0}.keys()
will produce but it could also...
|
by: John |
last post by:
I am coding a radix sort in python and I think that Python's dictionary may
be a choice for bucket.
The only problem is that dictionary is a mapping without order. But I just
found that if the keys are numeric, the keys themselves are ordered in the
dictionary.
part of my code is like this:
radix={}
for i in range(256):
|
by: Bob Altman |
last post by:
Hi all,
I'm trying to do something that should be really easy, but I can't think of an
obvious way to do it. I have a dictionary whose value is a "value type" (as
opposed to a reference type -- in this case, a Boolean):
Dim dic As New Dictionary(Of Int32, Boolean)
dic(123) = True
I want to set all of the existing entries in the dictionary to False. The
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
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.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
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 most users, this new feature is actually very convenient. If you want to control the update process,...
|
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |