Home » Python » python – How to optimize weighted values and output to least amount of lines and characters?-Exceptionshub

# python – How to optimize weighted values and output to least amount of lines and characters?-Exceptionshub

Questions:
``````def finalvalue(a,b,c,d):
o=round(450-a-(b*2+c+d)*.75+.3)
return ("Impossible, you " if(o)>100 else "You ")+"would need a "+str(o)+"%"
``````

So here I have a function that calculates the weighted score of each of the inputs and what the final score someone will have to earn in order to get at least 90% overall. If the value is NOT an integer, in this case “o”, then round to the nearest upper integer. If the score is greater than 100 return a different message with “impossible” instead.

I have already put the return statement with the if clause.

So my question is, how would I optimize this and do this in a fewer lines of code?

Here is a 144 character solution:

``````import math
def finalvalue(a,b,c,d):
o=math.ceil(450-a-(b*2+c+d)*.75)
return("Impossible, y"if o>100 else"Y")+"ou would need a "+str(o)+"%"
``````

If `a`,`b`,`c` and `d` are integers then you can simplify further by noting the smallest fraction you can get on `o` is 1/4 i.e. 0.25, so we can add 0.3 and round:

``````def finalvalue(a,b,c,d):
o=round(450-a-(b*2+c+d)*.75+.3)
return("Impossible, y"if o>100else"Y")+"ou would need a "+str(o)+"%"
``````

This comes in at 127 characters.

You can also simplify further using old-style string formatting and get rid of the round:

``````def finalvalue(a,b,c,d):
o=450.9-a-(b*2+c+d)*.75
return("Impossible, y"if o>100else"Y")+"ou would need a %d%%"%o
``````

I think this is 114.

If you have access to Python 3.8, you can use a lambda expression and the walrus operator to reduce to 104 characters:

``````finalvalue=lambda a,b,c,d:("Y","Impossible, y")[(o:=450.9-a-(b*2+c+d)*.75)>100]+"ou would need a %d%%"%o
``````