Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions Bonus/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,15 +252,16 @@ def make_index(target_file, *source_list):
def make_files():
files_py = list(Path.cwd().glob("*.py"))
txt_builds = [
build_if_needed(pylit, f.with_suffix(f.suffix+'.txt'), f)
build_if_needed(pylit, f.with_suffix(f'{f.suffix}.txt'), f)
for f in files_py
]
for item in txt_builds:
logger.info(item)

index_build = build_if_needed(
make_index, Path("index.txt"),
*[f.with_suffix(f.suffix+'.txt') for f in files_py]
make_index,
Path("index.txt"),
*[f.with_suffix(f'{f.suffix}.txt') for f in files_py],
Comment on lines -255 to +264
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function make_files refactored with the following changes:

)
logger.info(index_build)

Expand Down
19 changes: 8 additions & 11 deletions Bonus/chi_sq.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,7 @@ def fact(k: int) -> int:
>>> fact(4)
24
"""
if k < 2:
return 1
return reduce(operator.mul, range(2,k+1))
return 1 if k < 2 else reduce(operator.mul, range(2,k+1))
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function fact refactored with the following changes:


# The implementation uses ``reduce( operator.mul, ... )`` to compute
# the product of a sequence of integer values.
Expand Down Expand Up @@ -121,14 +119,14 @@ def gamma(s: float, z: float) -> float:

def terms(s: float, z: float) -> Iterator[float]:
for k in range(1000):
term = ((-1)**k/fact(k))*(z**(s+k)/(s+k))
yield term

T_ = TypeVar("T_")
yield ((-1)**k/fact(k))*(z**(s+k)/(s+k))

T_ = TypeVar("T_")
def take_until(function: Callable[[T_], bool], source: Iterable[T_]) -> Iterator[T_]:
for v in source:
if function(v): return
yield v

Comment on lines -124 to +129
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function gamma refactored with the following changes:

ε = 1E-8
return sum(take_until(lambda t: abs(t) < ε, terms(s, z)))

Expand Down Expand Up @@ -498,11 +496,10 @@ def Gamma_Half(k: float) -> float:
0.8862269
"""
ε = 1E-6
if abs(k-int(k)-.5) < ε:
n = int(k-.5)
return fact(2*n)/(4**n*fact(n))*math.sqrt(math.pi)
else:
if abs(k - int(k) - 0.5) >= ε:
return float(Gamma2(k))
n = int(k-.5)
return fact(2*n)/(4**n*fact(n))*math.sqrt(math.pi)
Comment on lines -501 to +502
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Gamma_Half refactored with the following changes:


# If the value is an :math:`n+\dfrac{1}{2} \pm \epsilon`, we'll use the special
# close-form expression. If the value is not close to :math:`n+\dfrac{1}{2}`,
Expand Down
27 changes: 6 additions & 21 deletions Chapter01/ch01_ex1.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,15 @@


def sum_numeric(limit: int = 10) -> int:
s = 0
for n in range(1, limit):
if n % 3 == 0 or n % 5 == 0:
s += n
return s
return sum(n for n in range(1, limit) if n % 3 == 0 or n % 5 == 0)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function sum_numeric refactored with the following changes:



def test_sum_numeric() -> None:
assert sum_numeric() == 23


def sum_object_light(limit: int = 10) -> int:
m: list[int] = list()
for n in range(1, limit):
if n % 3 == 0 or n % 5 == 0:
m.append(n)
m: list[int] = [n for n in range(1, limit) if n % 3 == 0 or n % 5 == 0]
Comment on lines -20 to +16
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function sum_object_light refactored with the following changes:

return sum(m)


Expand Down Expand Up @@ -53,9 +46,7 @@ def test_full_oo() -> None:

def foldr(seq: Sequence[int], op: Callable[[int, int], int], init: int) -> int:
"""Recursive reduce operation, fold from right to left."""
if len(seq) == 0:
return init
return op(seq[0], foldr(seq[1:], op, init))
return init if len(seq) == 0 else op(seq[0], foldr(seq[1:], op, init))
Comment on lines -56 to +49
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function foldr refactored with the following changes:



def test_foldr() -> None:
Expand All @@ -67,9 +58,7 @@ def test_foldr() -> None:


def sumr(seq: Sequence[int]) -> int:
if len(seq) == 0:
return 0
return seq[0] + sumr(seq[1:])
return 0 if len(seq) == 0 else seq[0] + sumr(seq[1:])
Comment on lines -70 to +61
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function sumr refactored with the following changes:



REPL_sumr = """
Expand Down Expand Up @@ -198,15 +187,11 @@ def foldright(n, v=1):


def foldleft(n: int) -> list[int]:
if n == 0:
return []
return foldleft(n - 1) + [n]
return [] if n == 0 else foldleft(n - 1) + [n]
Comment on lines -201 to +190
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function foldleft refactored with the following changes:



def foldright(n: int, v: int = 1) -> list[int]:
if v == n:
return [v]
return [v] + foldright(n, v + 1)
return [v] if v == n else [v] + foldright(n, v + 1)
Comment on lines -207 to +194
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function foldright refactored with the following changes:



def test_fold_left_right() -> None:
Expand Down
4 changes: 1 addition & 3 deletions Chapter01/ch01_ex2.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,7 @@ def repeat(f: Callable[[float], float], a: float) -> Iterator[float]:
def within(ε: float, iterable: Iterator[float]) -> float:
def head_tail(ε: float, a: float, iterable: Iterator[float]) -> float:
b = next(iterable)
if abs(a - b) <= ε:
return b
return head_tail(ε, b, iterable)
return b if abs(a - b) <= ε else head_tail(ε, b, iterable)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function within refactored with the following changes:


return head_tail(ε, next(iterable), iterable)

Expand Down
6 changes: 2 additions & 4 deletions Chapter01/ch01_ex3.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,12 @@ def distance(
def redundant(
lat1: float, lon1: float, lat2: float, lon2: float, R: float = 360 * 60 / math.tau
) -> float:
d = math.hypot(
return math.hypot(
R
* (math.radians(lon1) - math.radians(lon2))
* math.cos((math.radians(lat1) + math.radians(lat2)) / 2),
R * (math.radians(lat1) - math.radians(lat2)),
)
return d
Comment on lines -24 to -30
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function redundant refactored with the following changes:



def imperative(
Expand All @@ -52,8 +51,7 @@ def imperative(
x2 = x ** 2
y2 = y ** 2
x2y2 = x2 + y2
d = math.sqrt(x2y2)
return d
return math.sqrt(x2y2)
Comment on lines -55 to +54
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function imperative refactored with the following changes:



from pytest import approx
Expand Down
18 changes: 7 additions & 11 deletions Chapter01/ch01_ex4.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,15 @@ def main(source_path: Path = DEFAULT_PATH) -> None:
with source_path.open() as source:
rdr = csv.DictReader(source)
for row in rdr:
if "-" in row["ZIP"]:
text_zip = row["ZIP"]
text_zip = row["ZIP"]
if "-" in text_zip:
missing_zeroes = 10 - len(text_zip)
if missing_zeroes:
text_zip = missing_zeroes * "0" + text_zip
elif 5 < len(text_zip) < 9:
missing_zeroes = 9 - len(text_zip)
else:
text_zip = row["ZIP"]
if 5 < len(row["ZIP"]) < 9:
missing_zeroes = 9 - len(text_zip)
else:
missing_zeroes = 5 - len(text_zip)
if missing_zeroes:
text_zip = missing_zeroes * "0" + text_zip
missing_zeroes = 5 - len(text_zip)
if missing_zeroes:
text_zip = missing_zeroes * "0" + text_zip
Comment on lines -21 to +29
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:

frequency[text_zip] += 1
print(frequency)

Expand Down
31 changes: 13 additions & 18 deletions Chapter02/ch02_ex1.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,7 @@ def sum_to(limit: int) -> int:
def isprimer(n: int) -> bool:
def iscoprime(k: int, a: int, b: int) -> bool:
"""Is k coprime with a value in the given range?"""
if a == b:
return True
return (k % a != 0) and iscoprime(k, a + 1, b)
return True if a == b else (k % a != 0) and iscoprime(k, a + 1, b)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function isprimer refactored with the following changes:


return iscoprime(n, 2, int(math.sqrt(n)) + 1)

Expand All @@ -135,17 +133,12 @@ def test_isprimer() -> None:

def isprimei(n: int) -> bool:
"""Is n prime?"""
if n < 2:
if n < 2 or n != 2 and n % 2 == 0:
return False
elif n == 2:
return True
elif n % 2 == 0:
return False
else:
for i in range(3, 1 + int(math.sqrt(n)), 2):
if n % i == 0:
return False
return True
return all(n % i != 0 for i in range(3, 1 + int(math.sqrt(n)), 2))
Comment on lines -138 to +141
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function isprimei refactored with the following changes:



def test_isprimei() -> None:
Expand Down Expand Up @@ -186,7 +179,7 @@ def isprimeg(n: int) -> bool:
return True
if n % 2 == 0:
return False
return not any(n % p == 0 for p in range(3, int(math.sqrt(n)) + 1, 2))
return all(n % p != 0 for p in range(3, int(math.sqrt(n)) + 1, 2))
Comment on lines -189 to +182
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function isprimeg refactored with the following changes:



def test_isprimeg() -> None:
Expand Down Expand Up @@ -401,9 +394,11 @@ def limit_of_performance() -> None:


def strip_head(source: TextIO, line: str) -> tuple[TextIO, str]:
if len(line.strip()) == 0:
return source, source.readline()
return strip_head(source, source.readline())
return (
strip_head(source, source.readline())
if line.strip()
else (source, source.readline())
)
Comment on lines -404 to +401
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function strip_head refactored with the following changes:



def get_columns(source: TextIO, line: str) -> Iterator[str]:
Expand Down Expand Up @@ -432,17 +427,17 @@ def performance() -> None:
assert len(primes) == 1000

start = time.perf_counter()
for repeat in range(1000):
for _ in range(1000):
assert all(isprimei(x) for x in primes)
print(f"all() {time.perf_counter() - start:.3f}")

start = time.perf_counter()
for repeat in range(1000):
assert not any(not isprimei(x) for x in primes)
for _ in range(1000):
assert all(isprimei(x) for x in primes)
print(f"not any() {time.perf_counter() - start:.3f}")

start = time.perf_counter()
for repeat in range(1000):
for _ in range(1000):
Comment on lines -435 to +440
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function performance refactored with the following changes:

assert reduce(lambda x, y: x and y, (isprimei(x) for x in primes))
print(f"reduce(and,...) {time.perf_counter() - start:.3f}")

Expand Down
10 changes: 4 additions & 6 deletions Chapter03/ch03_ex1.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,7 @@ def shifty(b: int) -> int:


def multy(b: int) -> int:
if b == 0:
return 1
return 2 * multy(b - 1)
return 1 if b == 0 else 2 * multy(b - 1)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function multy refactored with the following changes:



def faster(b: int) -> int:
Expand All @@ -95,9 +93,9 @@ def faster(b: int) -> int:


def test_mults() -> None:
assert shifty(17) - 1 == 131071
assert multy(17) - 1 == 131071
assert faster(17) - 1 == 131071
assert shifty(17) == 131072
assert multy(17) == 131072
assert faster(17) == 131072
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function test_mults refactored with the following changes:



# Implementations of Mersenne with strategy objects plugged in properly.
Expand Down
8 changes: 2 additions & 6 deletions Chapter03/ch03_ex2.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,11 @@ def test_clean_decimal_2() -> None:

def remove(text: str, chars: str) -> str:
"""Remove all of the given chars from a string."""
if chars:
return remove(text.replace(chars[0], ""), chars[1:])
return text
return remove(text.replace(chars[0], ""), chars[1:]) if chars else text
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function remove refactored with the following changes:



def clean_decimal_3(text: str | None) -> Decimal | None:
if text is None:
return None
return Decimal(remove(text, "$,"))
return None if text is None else Decimal(remove(text, "$,"))
Comment on lines -52 to +50
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function clean_decimal_3 refactored with the following changes:



def test_clean_decimal_3() -> None:
Expand Down
2 changes: 1 addition & 1 deletion Chapter03/ch03_ex3.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def pfactorsr(x: int) -> Iterator[int]:
"""Pure Recursion factors. Limited to numbers below about 4,000,000"""

def factor_n(x: int, n: int) -> Iterator[int]:
if n * n > x:
if n**2 > x:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function pfactorsr refactored with the following changes:

yield x
return
if x % n == 0:
Expand Down
5 changes: 2 additions & 3 deletions Chapter03/ch03_ex4.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@ def float_none(data: str) -> float | None:
1.23
"""
try:
data_f = float(data)
return data_f
return float(data)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function float_none refactored with the following changes:

except ValueError:
return None

Expand All @@ -58,7 +57,7 @@ def float_row(row: list[str]) -> R_Float:
return list(map(float_none, row))

def all_numeric(row: R_Float) -> bool:
return not any(v is None for v in row)
return all(v is not None for v in row)
Comment on lines -61 to +60
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function head_map_filter refactored with the following changes:


return cast(Iterator[list[float]], filter(all_numeric, map(float_row, row_iter)))

Expand Down
20 changes: 6 additions & 14 deletions Chapter03/ch03_ex5.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,19 +121,14 @@ def color_GPL_r(file_obj: TextIO) -> Iterator[Color]:
def read_head(file_obj: TextIO) -> tuple[TextIO, str, str, str]:
headers = "".join(file_obj.readline() for _ in range(4))
if match := header_pat.match(headers):
return (
file_obj,
match.group(1),
match.group(2),
file_obj.readline().rstrip(),
)
return file_obj, match[1], match[2], file_obj.readline().rstrip()
else:
raise ValueError(f"invalid {headers!r}")

def read_tail(
file_obj: TextIO, palette_name: str, columns: str, next_line: str
) -> Iterator[Color]:
if len(next_line) == 0:
file_obj: TextIO, palette_name: str, columns: str, next_line: str
) -> Iterator[Color]:
if not next_line:
Comment on lines -124 to +131
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function color_GPL_r refactored with the following changes:

return
r, g, b, *name = next_line.split()
yield Color(int(r), int(g), int(b), " ".join(name))
Expand Down Expand Up @@ -163,7 +158,7 @@ def row_iter_gpl(file_obj: TextIO) -> tuple[str, str, Iterator[list[str]]]:
def read_head(file_obj: TextIO) -> tuple[str, str, TextIO]:
headers = "".join(file_obj.readline() for _ in range(4))
if match := header_pat.match(headers):
return match.group(1), match.group(2), file_obj
return match[1], match[2], file_obj
Comment on lines -166 to +161
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function row_iter_gpl refactored with the following changes:

else:
raise ValueError(f"invalid {headers!r}")

Expand Down Expand Up @@ -206,10 +201,7 @@ def load_colors(row_iter_gpl: tuple[str, str, Iterator[list[str]]]) -> dict[str,
colors = tuple(
Color(int(r), int(g), int(b), " ".join(name)) for r, g, b, *name in row_iter
)
# print( colors )
mapping = dict((c.name, c) for c in colors)
# print( mapping )
return mapping
return {c.name: c for c in colors}
Comment on lines -209 to +204
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function load_colors refactored with the following changes:

This removes the following comments ( why? ):

# print( colors )
# print( mapping )



REPL_test_gpl = """
Expand Down
4 changes: 1 addition & 3 deletions Chapter04/ch04_ex1.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,9 +280,7 @@ def legs_filter(
) -> Leg_Iter:
begin = next(lat_lon_iter)
for end in lat_lon_iter:
if rejection_rule(begin, end):
pass
else:
if not rejection_rule(begin, end):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function legs_filter refactored with the following changes:

yield begin, end
begin = end

Expand Down
Loading