3

I am dealing with an issue that involves multiple if and elif conditining..precisely stating, my case goes as follows:

if len(g) == 2:
   a = 'rea: 300'
   b = 'ref: "%s": {"sds": 200},"%s": {"sds": 300}' % (g[0],g[1])

elif len(g) == 3:
   a = 'rea: 400'
   b = 'ref: "%s": {"sds": 200},"%s": {"sds": 300},"%s": {"sds": 400}' % (g[0],g[1],g[2])
....

And this elif conditioning is supposed to go up to elif len(g) == 99...so I suppose there should be some elegant way to do this. Moreover, if you observe, there is a pattern with which the 'rea' and 'ref' are progressing, which can be stated as:

 if len(g) == x:
    a = 'rea: (x*100)+100'
    b = 'ref: "%s": {"sds": 200},"%s": {"sds": 300},"%s": {"sds": (x*100)+100}' % (g[0],g[1],g[2])
1
  • is b supposed to be a dictionary? Why recreate it as as string? Commented Jun 30, 2013 at 7:31

5 Answers 5

2

Maybe something like this:

g_len = len(g)
a = "rea: {}".format((g_len + 1) * 100)
b = "ref: "
for i, g_i in enumerate(g):
    b += ' "{}": {{"sds": {}}},'.format(g_i, (i+2) * 100)
Sign up to request clarification or add additional context in comments.

5 Comments

This is by far the most elegant one..thanks Mishik and Burhan! :-)
one more thing guys..how to implement this on Python 2.6 or 2.4? There maybe a little syntax change i believe..
I don't really remember much of 2.6 issues. What's not working?
IT is raising this exception: b += ' "{}": {{"sds": {}}},'.format(g_i, (i+2) * 100) ValueError: zero length field name in format
Hm... I guess it does not like {}. Try using "{0}": {{"sds": {1}}},
2

Try this method:

def func(g):
    if not 1 < len(g) < 100:
        raise ValueError('inadequate length')
    d = {x:{'sds':(i+2)*100} for i, x in enumerate(g)}
    a = 'rea: %s00' % (len(g)+1)
    b = 'ref: %s' % str(d)[1:-1]
    return (a, b)

I don't know why you are creating a string b which looks very much like a dictionary, but I am sure you have your reasons...

>>> func(range(3))
('rea: 400', "ref: 0: {'sds': 200}, 1: {'sds': 300}, 2: {'sds': 400}")

Comments

0

Use a dictionary:

x = 100
d = {}
for i in xrange(2, len(g)+1):
    d[i] = ['rea: {}'.format(100+x*i), 'ref: '+ ('%s: {"sds": 200}, ' *(i-1) + ' %s: {"sds": 200}') % tuple(g[:i])]

Now, d will look something like:

{2: ['rea: 300',
     'ref: "depends_on_g": {"sds": 200}, "depends_on_g": {"sds": 300}'],
 3: ['rea: 400',
     'ref: "depends_on_g": {"sds": 200}, "depends_on_g": {"sds": 300}', "depends_on_g": {"sds": 300}]
 ...
}

Then, to access it:

a, b = d.get(len(g))

No if-statements needed :)

5 Comments

"ref" value should be increasing for each i
@mishik I just notcied that :)
And you now have a dict of n^2 size, storing all the non required values :)
@mishik What :p? Firstly, my dict is length 98, and secondly, it gets the contents from g fine.
The dict is 98 length alright, but d[1] is X long, d[1] is 2X long, etc... d[99] ix 99X long :) X + 2X + ... + 99X = 4950X
-1

Personally I would go for something functional at the time that the length was known like:

def do_Condition(g):
    """ Condtion the result based on the length of g """
    l = len(g)
    a = 'rea: %d' % (100 + 100*l)
    items = ['ref: "%s"' % (g[0])]
    n = 100
    for i in g[1:]:
        n += 100
        items.append('{"sds": %d},"%s"' % (n, i))
    b = ': '.join(items)
    return (a, b)

1 Comment

You don't need to store the len(g) as a variable, the length is always calculated and calling the length method on a container does not re-evaluate each time, it only retrieves the value, it is actually slower to store length as a separate value.
-1

this seems to work:

a = 'rea: %d00' % (len(g)+1)
b = ",".join(['ref: "%s": {"sds": %d00}' % (i, j) for i, j in  zip(g, range(2,len(g)+2))])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.