Reputation: 2945
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])
Upvotes: 3
Views: 263
Reputation: 1021
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))])
Upvotes: -1
Reputation: 59974
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 :)
Upvotes: 0
Reputation: 43447
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}")
Upvotes: 2
Reputation: 10003
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)
Upvotes: 2
Reputation: 28370
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)
Upvotes: -1