FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

gh-72902: improve Fraction(str) speed (don't use regexp's) by skirpichev · Pull Request #133994 · python/cpython · GitHub

Repository navigation

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .py  (2) .rst  (1) All 2 file types selected
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
89 changes: 51 additions & 38 deletions Lib/fractions.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -53,20 +53,6 @@ def _hash_algorithm(numerator, denominator):
result = hash_ if numerator >= 0 else -hash_
return -2 if result == -1 else result

_RATIONAL_FORMAT = re.compile(r"""
\A\s* # optional whitespace at the start,
(?P<sign>[-+]?) # an optional sign, then
(?=\d|\.\d) # lookahead for digit or .digit
(?P<num>\d*|\d+(_\d+)*) # numerator (possibly empty)
(?: # followed by
(?:\s*/\s*(?P<denom>\d+(_\d+)*))? # an optional denominator
| # or
(?:\.(?P<decimal>\d*|\d+(_\d+)*))? # an optional fractional part
(?:E(?P<exp>[-+]?\d+(_\d+)*))? # and optional exponent
)
\s*\z # and optional whitespace to finish
""", re.VERBOSE | re.IGNORECASE)


# Helpers for formatting

Expand Down Expand Up @@ -251,31 +237,58 @@ def __new__(cls, numerator=0, denominator=None):

elif isinstance(numerator, str):
# Handle construction from strings.
m = _RATIONAL_FORMAT.match(numerator)
if m is None:
raise ValueError('Invalid literal for Fraction: %r' %
numerator)
numerator = int(m.group('num') or '0')
denom = m.group('denom')
if denom:
denominator = int(denom)
else:
denominator = 1
decimal = m.group('decimal')
if decimal:
decimal = decimal.replace('_', '')
scale = 10**len(decimal)
numerator = numerator * scale + int(decimal)
denominator *= scale
exp = m.group('exp')
if exp:
exp = int(exp)
if exp >= 0:
numerator *= 10**exp
fraction_literal = numerator
num, is_fraction_format, denom = fraction_literal.partition('/')
try:
num = num.strip()
denom = denom.strip()
if num and denom and denom[0].isdigit():
Comment thread
skirpichev marked this conversation as resolved.
denominator = int(denom)
numerator = int(num)
elif num and not is_fraction_format:
denominator = 1
num, is_exp_format, exp = num.replace('E', 'e').partition('e')
if is_exp_format and not exp:
raise ValueError
num, _, decimal = num.partition('.')
if num:
if num[0] in ('+', '-'):
sign = num[0] == '-'
num = num[1:]
else:
sign = 0
if num and not (num[-1].isdigit() and num[0].isdigit()):
raise ValueError
else:
denominator *= 10**-exp
if m.group('sign') == '-':
numerator = -numerator
sign = 0
if decimal:
if not decimal[0].isdigit() or not decimal[-1].isdigit():
raise ValueError
numerator = int(num or '0')
decimal_len = len(decimal.replace('_', ''))
decimal = int(decimal)
scale = 10**decimal_len
numerator = numerator*scale + decimal
denominator *= scale
else:
numerator = int(num)
if sign:
numerator = -numerator
if exp:
if not (exp[0] in ('+', '-') or exp[0].isdigit()):
raise ValueError
exp = int(exp)
if exp >= 0:
numerator *= 10**exp
else:
denominator *= 10**-exp
else:
raise ValueError
except ValueError as exc:
if exc.args and re.match('^Exceeds', exc.args[0]):
raise
raise ValueError('Invalid literal for Fraction: %r' %
fraction_literal)

elif isinstance(numerator, numbers.Rational):
self._numerator = numerator.numerator
Expand Down
2 changes: 2 additions & 0 deletions Lib/test/test_fractions.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,7 @@ def check_invalid(s):
# Imitate float's parsing.
check_invalid("+ 3/2")
check_invalid("- 3/2")
check_invalid("+ 343.33")
# Avoid treating '.' as a regex special character.
check_invalid("3a2")
# Don't accept combinations of decimals and rationals.
Expand All @@ -445,6 +446,7 @@ def check_invalid(s):
# No space around e.
check_invalid("3.2 e1")
check_invalid("3.2e 1")
check_invalid("232e\t2")
# Fractional part don't need a sign.
check_invalid("3.+2")
check_invalid("3.-2")
Expand Down
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Improve speed (x1.3-1.5) of the :class:`~fractions.Fraction` constructor for
string inputs.
Loading

Back | FazBrowse Home | New Git URL