Skip to content

Instantly share code, notes, and snippets.

@HakimCassimallyBBC
Created November 10, 2020 09:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HakimCassimallyBBC/bcedf121f1f57e90f7bac23261df0b2c to your computer and use it in GitHub Desktop.
Save HakimCassimallyBBC/bcedf121f1f57e90f7bac23261df0b2c to your computer and use it in GitHub Desktop.
Rather "un-pythonic" FP-ish (but with explicit array access) snippet, discovered in an algorithm book
import functools
def roman_to_integer(s: str) -> int:
T = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
return functools.reduce(
lambda val, i: val + (-T[s[i]] if T[s[i]] < T[s[i+1]] else T[s[i]]),
reversed(range(len(s)-1)), T[s[-1]])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment