import argparse # Parse arguments. parser = argparse.ArgumentParser(description='Calculate the missing number in a ratio equation.') parser.add_argument('numbers', metavar='N', type=str, nargs='+', help='An integer in the ratio equation. There must be three numbers and either an x or a ? in the set to calculate the missing value. E.g.: 2 4 ? 10') parser.add_argument('-r', '--round', metavar='N', type=int, default=2, help='How many decimal places to which the result will be rounded. Default: 2') parser.add_argument('-v', '--verbose', action='store_true', default=False, help='Returns ratio equation with missing ratio highlighted, instead of just missing number. E.g.: 1/2 [2]/4') arguments = parser.parse_args() # Extract numbers from arguments. numbers = { 'a' : arguments.numbers[0], 'b' : arguments.numbers[1], 'c' : arguments.numbers[2], 'd' : arguments.numbers[3] } # Shorter variables for readability in equations. a = numbers['a'] b = numbers['b'] c = numbers['c'] d = numbers['d'] # Find which of the four numbers is missing. for key, value in numbers.items(): if value == '?' or value == 'x': missing_number = key # Perform the appropriate calculation. if missing_number == 'a': result = float(b) * (float(c)/float(d)) result = round(result, arguments.round) verbose_result = '[' + str(result) + ']' + '/' + b + ' = ' + c + '/' + d if missing_number == 'b': result = float(a) / (float(c)/float(d)) result = round(result, arguments.round) verbose_result = a + '/' + '[' + str(result) + ']' + ' = ' + c + '/' + d if missing_number == 'c': result = float(d) * (float(a)/float(b)) result = round(result, arguments.round) verbose_result = a + '/' + b + ' = ' + '[' + str(result) + ']' + '/' + d if missing_number == 'd': result = float(c) / (float(a)/float(b)) result = round(result, arguments.round) verbose_result = a + '/' + b + ' = ' + c + '/' + '[' + str(result) + ']' # If verbose output was requested, give it. If not, just give the number. if arguments.verbose: print verbose_result else: print result
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question