pupy docs

# PUPY ~ Pretty Useful Python

This package (pupy) is full of Pretty Useful Python.

## These things

[![Build Status](https://travis-ci.org/jessekrubin/pupy.svg?branch=master)](https://travis-ci.org/jessekrubin/pupy) [![Wheel](https://img.shields.io/pypi/wheel/pupy.svg)](https://img.shields.io/pypi/wheel/pupy.svg) [![Version](https://img.shields.io/pypi/v/pupy.svg)](https://img.shields.io/pypi/v/pupy.svg) [![py_versions](https://img.shields.io/pypi/pyversions/pupy.svg)](https://img.shields.io/pypi/pyversions/pupy.svg)

## Installin’

Installing is EZPZ…

pip install pupy

If you plan on using Jason you can install ujson for a speed boost (if you wanna go fast; pupy uses the python-stdlib json if you wanna go slow)

pip install ujson

But wait theres more! Pupy has several optional dependencies for savings and loads which you can install with…

pip install ruamel.yaml # If ya mel in your spare time pip install msgpack # If you wanna pack messages pip install toml # toml (aka ‘that other markup language’(?)) pip install aiofiles # if you wanna do async stuff

## Testimonials

‘Ahead of the curve.’ -Haley who goes to Harvard

‘huh?’ -Tim Apple

‘If I were stranded on a dessert island and had to pick between having a copy pupy or a thing of water I would pick the water, but if I didn’t have to pick it wouldn’t hurt to have.’ -Ryan of the fro with his fro

‘I can’t say google wouldn’t not go down if it weren’t for pupy.’ -Ben W from the g-suite

‘A literary masterpiece on par with my second greatest work finite jest.’ -Bananas Foster Wallace

‘Best place for python savings and loads in the tri-content area.’ -Genghis Khan

Modules

amazon_prime

class pupy.amazon_prime.OctopusPrime(plim: int = 100)[source]

OctopusPrime, the 8-leg autobot, here to help you find PRIMES

───────────▄▄▄▄▄▄▄▄▄─────────── ────────▄█████████████▄──────── █████──█████████████████──█████ ▐████▌─▀███▄───────▄███▀─▐████▌ ─█████▄──▀███▄───▄███▀──▄█████─ ─▐██▀███▄──▀███▄███▀──▄███▀██▌─ ──███▄▀███▄──▀███▀──▄███▀▄███── ──▐█▄▀█▄▀███─▄─▀─▄─███▀▄█▀▄█▌── ───███▄▀█▄██─██▄██─██▄█▀▄███─── ────▀███▄▀██─█████─██▀▄███▀──── ───█▄─▀█████─█████─█████▀─▄█─── ───███────────███────────███─── ───███▄────▄█─███─█▄────▄███─── ───█████─▄███─███─███▄─█████─── ───█████─████─███─████─█████─── ───█████─████─███─████─█████─── ───█████─████─███─████─█████─── ───█████─████▄▄▄▄▄████─█████─── ────▀███─█████████████─███▀──── ──────▀█─███─▄▄▄▄▄─███─█▀────── ─────────▀█▌▐█████▌▐█▀───────── ────────────███████────────────
insert(index, object)[source]
Parameters:
  • index
  • object
primes_below(upper_bound)[source]

Lists primes, p, such that p < upper_bound

Parameters:upper_bound (int) – exclusive upper bound
Returns:-> primes less than upper_bound
Return type:list
primes_between(lower_bound: int, upper_bound: int) → List[int][source]

Lists primes, p, such that, lower_bound < p < upper_bound

Parameters:
  • lower_bound (int) – exclusive lower bound
  • upper_bound (int) – exclusive upper bound
Returns:

-> primes between lower_bound and upper_bound

Return type:

list

pupy.amazon_prime.is_prime(number: int) → bool[source]

Checks if a number is prime given that number as a param

Parameters:number (int) – number to check if is prime
Returns:-> True if number is prime
Return type:bool
>>> is_prime(1)
False
>>> is_prime(2)
True
>>> is_prime(3)
True
>>> is_prime(4)
False
>>> is_prime(5)
True
>>> is_prime(6)
False
>>> is_prime(7)
True
>>> is_prime(100)
False
>>> is_prime(89)
True
pupy.amazon_prime.prime_factorization_gen(n: int) → Iterator[int][source]

generates all numbers in the prime factorization of n

Parameters:n (int) – number to be factored
>>> list(prime_factorization_gen(12))
[2, 2, 3]
>>> list(prime_factorization_gen(16))
[2, 2, 2, 2]
pupy.amazon_prime.prime_factors_gen(n: int) → Iterator[Any][source]

prime factors generator

Parameters:n (int) – number to be factorized
>>> list(prime_factors_gen(12))
[2, 3]
>>> list(prime_factors_gen(16))
[2]
pupy.amazon_prime.prime_gen(plim: int = 0, kprimes: Union[None, Iterable[int]] = None) → Iterator[int][source]

Infinite (within reason) prime number generator

My big modification is the pdiv_dictionary() function that recreats the dictionary of divisors so that you can continue to generate prime numbers from a (sorted) list of prime numbers.

Based on:
eratosthenes by David Eppstein, UC Irvine, 28 Feb 2002 http://code.activestate.com/recipes/117119/ and the thread at the url
Parameters:
  • plim (int) – prime_limit; default=0 makes for an infinite generator
  • kprimes (iter) – known_primes as an iterable (Default value = None)
>>> list(prime_gen(50))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
>>> list(prime_gen(10))
[2, 3, 5, 7]

foreign

Iter Funks

foreign => ‘for … in …’ (its a pun)

pupy.foreign.chunks(it: Union[List[int], str], chunk_size: int) → Iterable[Any][source]

Yields chunks of something slicable with length <= chunk_size

Parameters:
  • it
  • chunk_size (int) – size of the chunks
pupy.foreign.digits_list(number: int) → List[int][source]

Returns a list of the digits in num

Parameters:number (int) – number w/ digits to be listsed
Returns:-> digits in a list
Return type:list
pupy.foreign.dirs_gen(dirpath: str = '.', abspath: bool = True) → Iterable[str][source]

Yields paths beneath dirpath param; dirpath defaults to os.getcwd()

Parameters:
  • dirpath – Directory path to walking down/through.
  • abspath – Yield the absolute path
Returns:

Generator object that yields dir-paths (absolute or relative)

pupy.foreign.exhaust(it: Iterable[Any]) → None[source]

Exhaust an interable / use it up; useful for evaluating a map object.

Parameters:it – iterable object to run through
Returns:None
pupy.foreign.files_gen(dirpath: str = ', ', abspath: bool = True) → Iterable[str][source]

Yields paths beneath dirpath param; dirpath defaults to os.getcwd()

Parameters:
  • dirpath – Directory path to walking down/through.
  • abspath – Yield the absolute path
Returns:

Generator object that yields filepaths (absolute or relative)

pupy.foreign.int_from_digits(digits: Iterable[int]) → int[source]

Converts an iterable of digits digits to a number

The iteratble can be ints or strings/chars

Return type:int
pupy.foreign.is_permutation(a: Union[int, List[int], str], b: Union[int, List[int], str]) → bool[source]

Checks if two integers or lists are permutations lists are permutations

Parameters:
  • a (int or list) – possible perumtation of b
  • b (int or list) – possible perumtation of a
Returns:

True if a and b are permutations of one another; False otherwise

Return type:

bool

It works for list!!!

>>> a = [1, 2, 3, 4]
>>> b = [4, 3, 2, 1]
>>> is_permutation(a, b)
True
>>> a = [1, 3, 2, 4]
>>> b = [4, 3, 2, 1]
>>> is_permutation(a, b)
True
>>> a = [1, 3, 2, 4]
>>> b = [4, 3, 2, 1, 1]
>>> is_permutation(a, b) # False cuz of the extra 'one'
False

It works for integers!?!?!?

>>> a = 1234
>>> b = 4321
>>> is_permutation(a, b)
True
>>> a = 12344
>>> b = 43212
>>> is_permutation(a, b)
False

It also works for strings!!!

>>> a = 'abcd'
>>> b = 'dbca'
>>> is_permutation(a, b) # False cuz of the extra 'one'
True
>>> a = 'pood'
>>> b = 'doop'
>>> is_permutation(a, b) # False cuz of the extra 'one'
True
>>> a = 'snorkel'
>>> b = 'doop'
>>> is_permutation(a, b) # False cuz of the extra 'one'
False
pupy.foreign.iter_product(l: Iterable[int]) → Union[int, float][source]

Product of all the elements in a list or tuple

Parameters:l – list with integer elements
Returns:product of all the elements in a list
Return type:int
pupy.foreign.rotate(rlist: List[int], rn: int = 1, left_rotate: bool = True) → List[int][source]

Rotate a list (rlist) by rn indices to the left or right

Parameters:
  • rlist (list or tuple) – list/toople or slicable to be rotated
  • rn (int) – steps bywhich to rotate (Default value = 1)
  • left_rotate (bool) – True (default) left rotates; False right rotates.
Returns:

rotated list

Return type:

list

>>> rotate([1, 2, 3, 4], left_rotate=True)
[2, 3, 4, 1]
>>> rotate([1, 2, 3, 4], left_rotate=False)
[4, 1, 2, 3]
>>> rotate([1, 2, 3, 4], rn=4, left_rotate=False)
[1, 2, 3, 4]
pupy.foreign.rotations_gen(rlist: Iterable[Any]) → Iterable[Any][source]

Yields all rotations of a list

Parameters:rlist
pupy.foreign.spliterable(iterable: Iterable[Any], funk: Callable[[Any], bool]) → Tuple[Iterable[Any], Iterable[Any]][source]
Parameters:
  • iterable
  • funk
Returns:

Return type:

maths

class pupy.maths.Trigon(pt1: Tuple[int, int], pt2: Tuple[int, int], pt3: Tuple[int, int])[source]

Trigon object composed of three points connected by lines.

area() → float[source]
static area_from_points(pt1, pt2, pt3)[source]
Parameters:
  • pt1
  • pt2
  • pt3
contains_origin() → bool[source]

True if the origin (0,0) lies within the Triangle

classmethod from_points(pts: List[Tuple[int, int]])[source]
Parameters:pts – return:
inner_triangles(point)[source]

Triangle funk that returns the three triangles w/ a point

The point (p) is connected to each point of a triangle. with points, a, b, and c. The three triangles are t1=(a, b, p), t2=(a, c, p), and t3 = (b, c, p).

Parameters:point (tuple or Vuple) – point to connect to Triangle Vertices
Returns:t1, t2, t3-> Three triangles
is_perimeter_point(point: Tuple[int, int]) → bool[source]
Parameters:point
points()[source]
class pupy.maths.Vuple[source]

VUPLE == Vector+Tuple

static angle(v1: Any, v2: Any, radians: bool = False) → float[source]
Parameters:
  • v1
  • v2
  • radians – (Default value = False)
static cross(v1: Any, v2: Any) → int[source]

Cross product of two 2d vectors

Parameters:
  • v1 – first vector
  • v2 – second vector
Returns:

cross product of v1 and v2

static dot(a: Any, b: Any) → Union[int, float][source]
Parameters:
  • a
  • b
get_mag() → float[source]
get_mag_sqrd()[source]
is_disjoint(them)[source]
Parameters:them
static mag(voop: Union[Tuple[int, int], Any]) → float[source]
Parameters:voop
static mag_sqrd(voop: Union[Tuple[int, int], Any]) → int[source]
Parameters:voop
normalize() → Any[source]

Normalizes the Vuple ST self.magnitude == 1

Returns:Unit Vuple
product() → int[source]

Multiplies all elements in the Vuple

Returns:
>>> v = Vuple((1, 2, 3, 4))
>>> v.product()
24
>>> v = Vuple((100, 1, -1, 2))
>>> v.product()
-200
>>> v = Vuple((100, -1, -1, 2))
>>> v.product()
200
static unit_vuple(voop: Any) → Any[source]
Parameters:voop
pupy.maths.degrees_2_radians(degs: float) → float[source]

Converts degrees to radians

Parameters:degs
>>> from math import pi
>>> degrees_2_radians(360.0) == 2*pi
True
pupy.maths.disjoint(a: Union[List[int], List[Union[str, int]]], b: Union[List[int], List[Union[str, int]]]) → bool[source]
Parameters:
  • a
  • b
>>> a = [1, 2, 3, 4]
>>> b = [2, 3, 4, 5]
>>> disjoint(a, b)
False
>>> a = [1, 2, 3, 4]
>>> b = [5, 6, 7, 8]
>>> disjoint(a, b)
True
>>> a = ['joe', 'frank', 3, 4]
>>> b = [5, 6, 7, 'frank']
>>> disjoint(a, b)
False
pupy.maths.divisors_gen(n: int) → Iterator[int][source]

Divisors generator

Parameters:n (int) – number w/ divisors to be generated
>>> list(divisors_gen(1))
[1]
>>> list(divisors_gen(4))
[1, 2, 4]
>>> list(divisors_gen(16))
[1, 2, 4, 8, 16]
pupy.maths.expo(d: int, n: int) → int[source]

greatest exponent for a divisor of n

Parameters:
  • d (int) – divisor
  • n (int) – number be divided
Returns:

number of times a divisor divides n

Return type:

int

>>> expo(100, 2)
2
>>> expo(12, 5)
0
>>> expo(12, 2)
2
>>> expo(160, 4)
2
>>> expo(1000, 4)
1
pupy.maths.fib_r(n: int) → int[source]

Recursively the nth fibonacci number

Parameters:n (int) – nth fibonacci sequence number
Returns:the nth fibonacci number
Return type:int
>>> fib_r(1)
1
>>> fib_r(2)
2
>>> fib_r(6)
13
pupy.maths.gcd_it(a: int, b: int) → int[source]

iterative gcd

Parameters:
  • a
  • b
    >>> from pupy.maths import gcd_it
    >>> from pupy.maths import gcd_r
    >>> gcd_it(1, 4) == gcd_r(1, 4)
    True
    >>> gcd_it(2, 6) == gcd_r(2, 6)
    True
    >>> gcd_it(3, 14) == gcd_r(3, 14)
    True
    >>> gcd_it(4, 300) == gcd_r(4, 300)
    True
    
pupy.maths.gcd_r(a: int, b: int) → int[source]

recursive greatest common divisor

Parameters:
  • a
  • b
>>> from pupy.maths import gcd_it
>>> from pupy.maths import gcd_r
>>> gcd_it(1, 4) == gcd_r(1, 4)
True
>>> gcd_it(2, 6) == gcd_r(2, 6)
True
>>> gcd_it(3, 14) == gcd_r(3, 14)
True
>>> gcd_it(4, 300) == gcd_r(4, 300)
True
pupy.maths.n_choose_r(n, r)[source]
Parameters:
  • n
  • r
pupy.maths.n_permutations_with_replacements(it: Union[Tuple[int, int, int, int], Tuple[int, int, int, int, int, int, int], Tuple[int, int, int, int, int], Tuple[int, int, int, int, int, int]]) → int[source]
>>> n_permutations_with_replacements((1, 2, 3, 4))
24
>>> n_permutations_with_replacements((1, 2, 3, 4, 3))
60
>>> n_permutations_with_replacements((1, 2, 3, 4, 3, 3))
120
>>> n_permutations_with_replacements((1, 2, 3, 4, 3, 4, 4))
420
pupy.maths.partitions_gen(numero: int, min_p: int = 1, max_p: Optional[int] = None)[source]

Partitions generator

Adapted from: code.activestate.com/recipes/218332-generator-for-integer-partitions/min_p

Parameters:
  • numero (int) – number for which to yield partiton tuples
  • min_p (int) – smallest part size (Default value = 1)
  • max_p (int) – largest part size (Default value = None)
pupy.maths.power_mod(number: int, exponent: int, mod: int) → int[source]
Parameters:
  • number
  • exponent
  • mod
>>> power_mod(2, 4, 3)
2
>>> power_mod(12, 3, 4)
144
>>> power_mod(123, 2, 3)
123
>>> power_mod(120, 6, 10)
14400
>>> power_mod(120, 6, 1)
14400
pupy.maths.pytriple_gen(max_c: int) → Iterator[Tuple[int, int, int]][source]

primative pythagorean triples generator

special thanks to 3Blue1Brown’s video on pythagorean triples https://www.youtube.com/watch?v=QJYmyhnaaek&t=300s

Parameters:max_c (int) – max value of c to yeild triples up to
pupy.maths.radians_2_degrees(rads: float) → float[source]

Converts radians to degrees

Parameters:rads
>>> from math import pi
>>> radians_2_degrees(2*pi) == 360.0
True
>>> radians_2_degrees(2*pi)
360.0
pupy.maths.reverse_num(n: int) → int[source]

Reverses a number

Parameters:n (int) – number to be reversed
Returns:reversed of a number
Return type:int
>>> reverse_num(1)
1
>>> reverse_num(12345)
54321
>>> reverse_num(54321)
12345
>>> reverse_num(54321000)
12345
pupy.maths.rfactorial(n: int) → int[source]

Recursive factorial function

Parameters:n
pupy.maths.set_cmp(a: Union[Set[int], List[int]], b: Union[Set[int], List[int]]) → Tuple[Set[int], Set[int], Set[int]][source]

Compare the elements of two iterables (a and b)

Parameters:
  • a – first iterable to compare elements of
  • b – second iterable to compare elements of
Returns:

tuple of sets of the form (common elements, in a only, in b only)

>>> a = [n for n in range(6)]
>>> a
[0, 1, 2, 3, 4, 5]
>>> b = list(range(3, 9))
>>> b
[3, 4, 5, 6, 7, 8]
>>> set_cmp(a, b)
({3, 4, 5}, {0, 1, 2}, {8, 6, 7})

Savings & Loads

Savings & Loads

Common funks for ur everyday savings and loads.

If you are a friend of Jasm/Json/Jason-Greenberg like myself, ‘pip install ujson’ for a better time.

If you need it… you can always… pip install (msgpack, toml, ruamel.yaml) for the whole shebang.

pupy.savings_n_loads.lbytes(filepath: str) → None[source]

Read bytes from file path

Parameters:filepath – filepath as as string to read bites from
Returns:some bytes…
pupy.savings_n_loads.ljasm(filepath: str) → Union[None, bool, int, float, str, List[Any], Dict[str, Any]][source]

Alias for ljson (which stands for ‘load-json’)

pupy.savings_n_loads.ljson(filepath: str) → Union[None, bool, int, float, str, List[Any], Dict[str, Any]][source]

Load a json file given a filepath and return the file-data

Parameters:filepath – path to the jasm file you want to load
Returns:Loaded file contents
pupy.savings_n_loads.load_jasm(filepath: str) → Union[None, bool, int, float, str, List[Any], Dict[str, Any]][source]

Alias for ljson (which stands for ‘load-json’)

pupy.savings_n_loads.lstr(filepath: str) → str[source]

Alias for lstring

pupy.savings_n_loads.lstring(filepath: str) → str[source]

(lstring) Read and return the file-contents as a string given a filepath

Parameters:filepath – Path to a file to read
Returns:Content of the file read as a string
pupy.savings_n_loads.safepath(path_str: str) → str[source]

Checks if a file/dir path is save/unused; returns an unused path.

Parameters:path_str – file or dir path
Returns:A file/dir path that does not exist and contains the given path
pupy.savings_n_loads.save_jasm(filepath: str, data: Union[None, bool, int, float, str, List[Any], Dict[str, Any]], minify: bool = False) → None[source]

Alias for sjson (which stands for ‘save-json’)

pupy.savings_n_loads.savings(filepath: str, string: str) → None[source]

Alias for sstring

pupy.savings_n_loads.shebang(filepath: str) → Union[None, str][source]

returns the shebang path given a filepath or None if it does not exist.

Parameters:filepath – path to a file w/ a shebange line
Returns:shebang line or None
pupy.savings_n_loads.sjasm(filepath: str, data: Union[None, bool, int, float, str, List[Any], Dict[str, Any]], minify: bool = False) → None[source]

Alias for sjson (which stands for ‘save-json’)

pupy.savings_n_loads.sjson(filepath: str, data: Union[None, bool, int, float, str, List[Any], Dict[str, Any]], minify: bool = False) → None[source]

Save json-serial-ize-able data to a specific filepath.

Parameters:
  • filepath – destination filepath
  • data – json cereal-izable dictionary/list/thing
  • minify – Bool flag – minify the json file
Returns:

None

pupy.savings_n_loads.sstr(filepath: str, string: str) → None[source]

Alias for sstring

pupy.savings_n_loads.sstring(filepath: str, string: str) → None[source]

Writes a string to filepath

Parameters:
  • filepath – Filepath save location
  • string – File as a string to be saved
Returns:

None? what do you want? confirmation?

Note

Decorated w/ @mkdirs Function is decorated with @mkdirs decorator; @mkdirs creates parent directories for the given filepath if they do not already exist.

pupy.savings_n_loads.touch(filepath: str) → None[source]

Touches a file just like touch on the command line

Parameters:filepath – filepath to ‘touch’ in a unix-y sense
Returns:None

Werd

Changelog

2.0.0 (2018-11-29)

  • 2nd release on PyPI.

Indices and tables

# PUPY ~ Pretty Useful Python

This package (pupy) is full of Pretty Useful Python.

## These things

[![Build Status](https://travis-ci.org/jessekrubin/pupy.svg?branch=master)](https://travis-ci.org/jessekrubin/pupy) [![Wheel](https://img.shields.io/pypi/wheel/pupy.svg)](https://img.shields.io/pypi/wheel/pupy.svg) [![Version](https://img.shields.io/pypi/v/pupy.svg)](https://img.shields.io/pypi/v/pupy.svg) [![py_versions](https://img.shields.io/pypi/pyversions/pupy.svg)](https://img.shields.io/pypi/pyversions/pupy.svg)

## Installin’

Installing is EZPZ…

pip install pupy

If you plan on using Jason you can install ujson for a speed boost (if you wanna go fast; pupy uses the python-stdlib json if you wanna go slow)

pip install ujson

But wait theres more! Pupy has several optional dependencies for savings and loads which you can install with…

pip install ruamel.yaml # If ya mel in your spare time pip install msgpack # If you wanna pack messages pip install toml # toml (aka ‘that other markup language’(?)) pip install aiofiles # if you wanna do async stuff

## Testimonials

‘Ahead of the curve.’ -Haley who goes to Harvard

‘huh?’ -Tim Apple

‘If I were stranded on a dessert island and had to pick between having a copy pupy or a thing of water I would pick the water, but if I didn’t have to pick it wouldn’t hurt to have.’ -Ryan of the fro with his fro

‘I can’t say google wouldn’t not go down if it weren’t for pupy.’ -Ben W from the g-suite

‘A literary masterpiece on par with my second greatest work finite jest.’ -Bananas Foster Wallace

‘Best place for python savings and loads in the tri-content area.’ -Genghis Khan