veronica,
@veronica@mastodon.online avatar

Someone made a joke about numerals, and I remembered I don't need to know them because I have a function for that. 😁

The code is based on some numerical example I saw somewhere. I made a few improvements.

JoeP,
@JoeP@mastodon.world avatar

@veronica I had the misfortune to code that in php about 18 years ago. And then have to update it when the site needed numbers above 4,999. And it's still in use.

veronica, (edited )
@veronica@mastodon.online avatar

The algorithm is quite simple, and neat IMO:

*You loop through all "units" from largest numerical value, to smallest. here called "divisor" and "symbol"

  • The "n" value does an integer division, so say you have 3456, where n = 3456//1000 = 3.
  • You then append 3 "M"s to the string named "roman".
  • The you subtract n times that divisor from value, so value = value - n*1000 = 456,
  • You do this until you have nothing left in your "value" variable.

veronica, (edited )
@veronica@mastodon.online avatar

So, with 3456 as input, you'll get per loop:

  1. value = 3456 - 1000 = 456 => "MMM"
  2. pass (n = 0)
  3. pass (n = 0)
  4. value = 456 - 400 = 56 => "MMMCD"
  5. pass (n = 0)
  6. pass (n = 0)
  7. value = 56 - 50 = 6 => "MMMCDL"
  8. pass (n = 0)
  9. pass (n = 0)
  10. pass (n = 0)
  11. value = 6 - 5 = 1 => "MMMCDLV"
  12. pass (n = 0)
  13. value = 1 - 1 = 0 => "MMMCDLVI", break
ptmcg,
@ptmcg@fosstodon.org avatar

@veronica I do this in the pyparsing examle romanNumerals.py, that creates then parses and evaluates Roman numerals from 1-5000. https://github.com/pyparsing/pyparsing/blob/c09eb6e4bb283b375e53cfe851bb6a63ed3957bb/examples/romanNumerals.py#L46

veronica,
@veronica@mastodon.online avatar

@ptmcg Ah, nice. Not sure where I found the code I started from, but I remember modifying it a bit, and not even sure it was Python, although the principle is the same.

That function i posted is part of an app, and is used for labelling chapters and pages as Roman numerals.

ptmcg,
@ptmcg@fosstodon.org avatar

@veronica That code is kind of old, and pre-dates the PEP8-ification of pyparsing's API. Also, after I created the railroad diagram for it, it seems like a very liberal parser, accepting any string combination of I's V's, X's, M's, etc. I have a stricter version parser almost ready.

  • All
  • Subscribed
  • Moderated
  • Favorites
  • philosophy
  • Durango
  • DreamBathrooms
  • thenastyranch
  • magazineikmin
  • tacticalgear
  • InstantRegret
  • Youngstown
  • ngwrru68w68
  • slotface
  • rosin
  • tester
  • everett
  • kavyap
  • cubers
  • JUstTest
  • cisconetworking
  • khanakhh
  • GTA5RPClips
  • mdbf
  • osvaldo12
  • Leos
  • modclub
  • normalnudes
  • anitta
  • ethstaker
  • megavids
  • provamag3
  • lostlight
  • All magazines