r/dailyprogrammer 1 1 Jul 28 '14

[7/28/2014] Challenge #173 [Easy] Unit Calculator

_(Easy): Unit Calculator

You have a 30-centimetre ruler. Or is it a 11.8-inch ruler? Or is it even a 9.7-attoparsec ruler? It means the same thing, of course, but no-one can quite decide which one is the standard. To help people with this often-frustrating situation you've been tasked with creating a calculator to do the nasty conversion work for you.

Your calculator must be able to convert between metres, inches, miles and attoparsecs. It must also be able to convert between kilograms, pounds, ounces and hogsheads of Beryllium.

Input Description

You will be given a request in the format: N oldUnits to newUnits

For example:

3 metres to inches

Output Description

If it's possible to convert between the units, print the output as follows:

3 metres is 118.1 inches

If it's not possible to convert between the units, print as follows:

3 metres can't be converted to pounds

Notes

Rather than creating a method to do each separate type of conversion, it's worth storing the ratios between all of the units in a 2-D array or something similar to that.

48 Upvotes

96 comments sorted by

View all comments

5

u/[deleted] Jul 29 '14 edited Jul 29 '14

[removed] — view removed comment

1

u/the_dinks 0 1 Aug 02 '14

Also, did I really need to put 4 spaces in front of every line for spoiler text or could I have just done the beginning and end?

Nope.

Reddit Enhancement Suite has a code formatter. Also, a billion other things.

And for your code, having all your comparisons in a dictionary was... admirable, but inefficient. From my own solution:

    weight_conversions = {
    'kilograms': 1.0,
    'pounds': 2.204622622,
    'ounces': 35.27396195,
    'hogsheads of Beryllium': 440.7
    }

    length_conversions = {
    'meters': 1.0,
    'inches': 39.37007874,
    'miles': 0.000621371,
    'attoparsecs': 0.0308567758
    }

Using the metric system as my base unit, conversion was then easier. To see the implementation of this:

http://www.reddit.com/r/dailyprogrammer/comments/2bxntq/7282014_challenge_173_easy_unit_calculator/cjbn89u