3

I want to convert a float between 0.0 and 39.9 into a string. Replace the tens digit with an L, T or Y if it's a 1, 2 or 3 respectively. And append an M if it's in the ones. For example, 22.3 would return T2.3 and 8.1 would return M8.1 and so forth. Otherwise, return the float.

This code works of course, but I wondering if there was a simpler (if not one-liner) solution. Here's the code:

def specType(SpT):
  if 0 <= SpT <= 9.9:
    return 'M{}'.format(SpT)
  elif 10.0 <= SpT <= 19.9:
    return 'L{}'.format(SpT - 10)
  elif 20.0 <= SpT <= 29.9:
    return 'T{}'.format(SpT - 20)
  elif 30.0 <= SpT <= 39.9:
    return 'Y{}'.format(SpT - 30) 
  else:
    return SpT

Thanks!

3
  • 6
    You've got to be careful with all those float comparisons (SpT <= 9.9 etc) Commented Dec 17, 2012 at 19:49
  • 1
    +1, NPE. What is the desired output when SpT is 9.95? Because it's greater than 9.9 and less than 10.0, it falls through the cracks and reaches the return SpT line. Commented Dec 17, 2012 at 19:53
  • That's a good point. It's best if I account for that but in truth, it will never come up in the application. Commented Dec 18, 2012 at 15:42

1 Answer 1

10

How about:

def specType(SpT):
    return '{}{}'.format('MLTY'[int(SpT//10)], SpT % 10) if 0.0 <= SpT <= 39.9 else SpT

which gives

>>> specType(0.0)
'M0.0'
>>> specType(8.1)
'M8.1'
>>> specType(14.5)
'L4.5'
>>> specType(22.3)
'T2.3'
>>> specType(34.7)
'Y4.7'

[As noted in the comments, you'll want to think about what to do with numbers which can sneak through your boundaries -- I made one guess; modify as appropriate.]

Sign up to request clarification or add additional context in comments.

4 Comments

:O Mind = Blown! I never knew you could do //!
@yentup You can also use divmod :)
@yentup That't a good read :) Another two from my bookmark bar: built-in types and data model (the latter may be a little more advanced).
Fantastic! That's exactly it. Thanks!

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.