Python Forum

Full Version: If elif else alternative
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
(Apr-11-2017, 12:07 PM)buran Wrote: [ -> ]
in addition one could use dict comprehension to construct the dict

d = {k+1:10**k for k in range(5)}

If you can do that you don't need the dic. In the original code you just use n=10**integer_length.
(Apr-12-2017, 08:06 AM)Ofnuts Wrote: [ -> ]If you can do that you don't need the dic. In the original code you just use n=10**integer_length.

Yeah, that's correct and I provided 2 such alternatives in my first post. Note that there is also catch all other case  (e.g. when integer_length>5).
However OP asks for a solution using dict and metulburr provided solution based on dict, which I changed further.
I have the code returning values which are always above the maxValue which was my goal. I have now decided I would like the value returned to be as follows; 
maxValue = 12.345 axis max = 15
maxValue = 452.38 axis max = 500
maxValue = 7612.2 axis max = 8000
maxValue = 628 axis max = 650

How can I do this?

import math

maxValue = 12.345 # maximum data value
integerPart = str(maxValue).split('.')[0] # if maxValue is a decimal this selects the integer part, ie. left of decimal
integerLength = len(integerPart) # length of integerPart

factor = {k+1:10**(k-2) for k in range(6)} # equivalent to below, 6 represents the maxValue integer length

n = factor.get(integerLength, 10000) # returns a value from the dictionary above dependent on integerLength
maxValueAdd = maxValue + n + 0.1 # n allows for a value to be returned that is higher by the same factor
d = math.ceil(maxValueAdd) # calculates the upper bound and returns an integer
e = int(round(d,-(integerLength-3)))

print "Maximum value = {}".format(maxValue)
print "Axis maximum = {}".format(e)
(Apr-12-2017, 08:02 AM)buran Wrote: [ -> ]@ankit - there is nothing pythonic in this
dict['rest'] if len([dict[i] for i in dict if i==n] )==0 else [dict[i] for i in dict if i==n][0]
Not only is it not Pythonic, it's inefficient. The whole point of a dictionary is that it's runtime is constant, but these comprehensions are linear both in time and space.
Pages: 1 2