Skip to content

Instantly share code, notes, and snippets.

@WorryingWonton
Created March 19, 2019 16:28
Show Gist options
  • Select an option

  • Save WorryingWonton/8eeec56b7cee4e7b0f8b14fe1ff31214 to your computer and use it in GitHub Desktop.

Select an option

Save WorryingWonton/8eeec56b7cee4e7b0f8b14fe1ff31214 to your computer and use it in GitHub Desktop.
Temperature Converter
def temp_converter(temps, mode, reversed):
return {'f': lambda x, y: [((temp - 32) * 5/9 + 273.15 if not y else (temp - 273.15) * 9/5 + 32) for temp in x],
'k': lambda x, y: x,
'c': lambda x, y: [temp + (273.15 if not y else -273.15) for temp in x]}[mode](temps, reversed)
def format_outputs(temps, mode):
return f'°{mode[-1].upper()}, '.join(map(lambda temp: str(round(temp, 2)), temps)) + f'°{mode[-1].upper()}'
if __name__ == '__main__':
mode = input('What temperature scales would you like to convert between? ').lower()
temperatures = list(map(lambda x: float(x), input('Enter temperatures separated by a space: ').split(' ')))
target_temps = temp_converter(temps=temp_converter(temps=temperatures, mode=mode[0], reversed=False), mode=mode[1], reversed=True)
print(format_outputs(target_temps, mode[-1]))
@WorryingWonton
Copy link
Author

Rough Alternate Version which removes the need for the 'reversed' parameter in temp_converter:

def temp_converter(temps, mode):
    conversions = [
        ("k", -273.15, lambda v, c: v + c, lambda v, c: c - v),
        ("c", 9/5, lambda v, c: v * c, lambda v, c: c / v),
        ("f", 32, lambda v, c: v + c, lambda v, c: c - v)]
    indexes = []
    for unit in mode:
        for conversion in conversions:
            if conversion[0] == unit:
                indexes.append(conversions.index(conversion))
    if indexes[0] == indexes[1]:
        return temps
    conversion_chain = conversions[indexes[0]:indexes[1] + 1] if indexes[1] > indexes[0] else list(reversed(conversions[indexes[1]:indexes[0] + 1]))
    for cf in conversion_chain:
        if indexes[0] < indexes[1]:
            temps = [cf[2](cf[1], temp) for temp in temps]
        else:
            temps = [cf[3](cf[1], temp) for temp in temps]
    return temps

def format_outputs(temps, mode):
    return f'°{mode[-1].upper()}, '.join(map(lambda temp: str(round(temp, 2)), temps)) + f'°{mode[-1].upper()}'

if __name__ == '__main__':
    mode = input('What temperature scales would you like to convert between? ').lower()
    temperatures = list(map(lambda x: float(x), input('Enter temperatures separated by a space: ').split(' ')))
    target_temps = temp_converter(temperatures, mode)
    print(format_outputs(target_temps, mode[-1]))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment