Skip to content

Commit

Permalink
Clean up ordinals (#1596)
Browse files Browse the repository at this point in the history
  • Loading branch information
AndreasArvidsson authored Nov 13, 2024
1 parent 588990d commit c5f32ad
Showing 1 changed file with 14 additions and 29 deletions.
43 changes: 14 additions & 29 deletions core/numbers/ordinals.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,5 @@
from talon import Context, Module


def ordinal(n):
"""
Convert an integer into its ordinal representation::
ordinal(0) => '0th'
ordinal(3) => '3rd'
ordinal(122) => '122nd'
ordinal(213) => '213th'
"""
n = int(n)
suffix = ["th", "st", "nd", "rd", "th"][min(n % 10, 4)]
if 11 <= (n % 100) <= 13:
suffix = "th"
return str(n) + suffix


# The primitive ordinal words in English below a hundred.
ordinal_words = {
0: "zeroth",
Expand Down Expand Up @@ -52,6 +36,7 @@ def ordinal(n):
# ordinal_numbers maps ordinal words into their corresponding numbers.
ordinal_numbers = {}
ordinal_small = {}

for n in range(1, 100):
if n in ordinal_words:
word = ordinal_words[n]
Expand All @@ -60,28 +45,28 @@ def ordinal(n):
assert 1 < tens < 10, "we have already handled all ordinals < 20"
assert 0 < units, "we have already handled all ordinals divisible by ten"
word = f"{tens_words[tens]} {ordinal_words[units]}"

if n <= 20:
ordinal_small[word] = n
ordinal_numbers[word] = n
ordinal_small[word] = str(n)
ordinal_numbers[word] = str(n)


mod = Module()
ctx = Context()
mod.list("ordinals", desc="list of ordinals")
mod.list("ordinals_small", desc="list of ordinals small (1-20)")

ctx.lists["self.ordinals"] = ordinal_numbers.keys()
ctx.lists["self.ordinals_small"] = ordinal_small.keys()
mod.list("ordinals", "List of ordinals (1-99)")
mod.list("ordinals_small", "List of small ordinals (1-20)")

ctx.lists["user.ordinals"] = ordinal_numbers
ctx.lists["user.ordinals_small"] = ordinal_small


@mod.capture(rule="{self.ordinals}")
@mod.capture(rule="{user.ordinals}")
def ordinals(m) -> int:
"""Returns a single ordinal as a digit"""
return int(ordinal_numbers[m[0]])
"""Returns a single ordinal as an integer"""
return int(m.ordinals)


@mod.capture(rule="{self.ordinals_small}")
@mod.capture(rule="{user.ordinals_small}")
def ordinals_small(m) -> int:
"""Returns a single ordinal as a digit"""
return int(ordinal_numbers[m[0]])
"""Returns a single small ordinal as an integer"""
return int(m.ordinals_small)

0 comments on commit c5f32ad

Please sign in to comment.