The Weekly Challenge 021

Calculate Euler's Number and URL Normalization

Solutions on GitHub

Task 1: Calculate Euler's Number

Write a script to calculate the value of $e$, also known as Euler’s number and Napier’s constant.

Example Output

The value of e for precision 15 is 2.718281828459045

Logic

Euler's number can be calculated using the Taylor series expansion: $$e = \sum_{n=0}^{\infty} \frac{1}{n!}$$ We iterate, calculating successive factorials and sum their reciprocals until the added terms are smaller than our targeted precision threshold. Alternatively, standard CPAN packages like Math::Big can compute it directly.

Perl Solution

ch-1.pl

use Math::Big qw{ euler }; my $precision = shift or die 'Usage: script precision'; say "The value of e for precision $precision is " . euler( 1, $precision );

Python Solution

ch-1.py

def calculate_e_iterative(precision: int = 15) -> float: e = 0.0 n = 0 while True: term = 1.0 / math.factorial(n) e += term if term < 10 ** (-precision): break n += 1 return e

Task 2: URL Normalization

Write a script for URL normalization based on RFC 3986.

Example

Original: http://www.example.com///test//foo/../bar Normalized: http://www.example.com/test/bar

Logic

Normalize schemes and hostnames to lowercase, remove default ports (e.g. 80 for HTTP, 443 for HTTPS), collapse duplicate path slashes, strip dot/parent path references (. and ..), and sort query parameters alphabetically.

Perl Solution

ch-2.pl

use URL::Normalize; my $url = shift or die 'Usage: script url'; my $normalizer = URL::Normalize->new( $url ); $normalizer->remove_social_query_parameters; $normalizer->make_canonical; say "The normalized value is ".$normalizer->url;

Python Solution

ch-2.py

from urllib.parse import urlparse, urlunparse, quote, unquote def normalize_url(url: str) -> str: parsed = urlparse(url) scheme = parsed.scheme.lower() netloc = parsed.netloc.lower() path = parsed.path # collapse slashes, handle parent dirs (..) and canonicalize path # ... (detailed in ch-2.py) return urlunparse((scheme, netloc, path, parsed.params, query, ""))