Knowledge is the Only Good
  • About

Why I like Python

Python
programming
Author

Stephen J. Mildenhall

Published

2024-11-27

I like love Python the language. The libraries are a bonus and the reason I use Python. Here are a few examples. Notice there are no imports, just pure Python. If “using Python” to you means using Pandas, numpy, TensorFlow, and matplotlib, this list is unlikely to resonate. But if you are looking for a programming language it just might. As ever, YMMV.

# lambda functions, factorial function, and arbitrary precision arithmetic
fact = lambda x: x == 0 or x * fact(x - 1)
x = fact(1000)
x
402387260077093773543702433923003985719374864210714632543799910429938512398629020592044208486969404800479988610197196058631666872994808558901323829669944590997424504087073759918823627727188732519779505950995276120874975462497043601418278094646496291056393887437886487337119181045825783647849977012476632889835955735432513185323958463075557409114262417474349347553428646576611667797396668820291207379143853719588249808126867838374559731746136085379534524221586593201928090878297308431392844403281231558611036976801357304216168747609675871348312025478589320767169132448426236131412508780208000261683151027341827977704784635868170164365024153691398281264810213092761244896359928705114964975419909342221566832572080821333186116811553615836546984046708975602900950537616475847728421889679646244945160765353408198901385442487984959953319101723355556602139450399736280750137837615307127761926849034352625200015888535147331611702103968175921510907788019393178114194545257223865541461062892187960223838971476088506276862967146674697562911234082439208160153780889893964518263243671616762179168909779911903754031274622289988005195444414282012187361745992642956581746628302955570299024324153181617210465832036786906117260158783520751516284225540265170483304226143974286933061690897968482590125458327168226458066526769958652682272807075781391858178889652208164348344825993266043367660176999612831860788386150279465955131156552036093988180612138558600301435694527224206344631797460594682573103790084024432438465657245014402821885252470935190620929023136493273497565513958720559654228749774011413346962715422845862377387538230483865688976461927383814900140767310446640259899490222221765904339901886018566526485061799702356193897017860040811889729918311021171229845901641921068884387121855646124960798722908519296819372388642614839657382291123125024186649353143970137428531926649875337218940694281434118520158014123344828015051399694290153483077644569099073152433278288269864602789864321139083506217095002597389863554277196742822248757586765752344220207573630569498825087968928162753848863396909959826280956121450994871701244516461260379029309120889086942028510640182154399457156805941872748998094254742173582401063677404595741785160829230135358081840096996372524230560855903700624271243416909004153690105933983835777939410970027753472000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
# dictionaries, comprehensions, and string manipulation
# count the frequency of digits in 1000!
x = str(x)
freq = {i: x.count(i) for i in '0123456789'}
freq
{'0': 472,
 '1': 239,
 '2': 248,
 '3': 216,
 '4': 229,
 '5': 213,
 '6': 231,
 '7': 217,
 '8': 257,
 '9': 246}
# string manipuation
last_first = characters = ["Corleone, Vito", "Adams, Kay", "Tessio, Salvatore", "Clemenza, Peter", "Hagen, Tom"]
first_last = [' '.join(i[::-1]) for i in [n.split(', ') for n in last_first]]
first_last
['Vito Corleone',
 'Kay Adams',
 'Salvatore Tessio',
 'Peter Clemenza',
 'Tom Hagen']
# slicing etc.
txt = ' '.join(first_last)
# reverse, alternate, etc.
txt[::-1], txt[::2]
('negaH moT aznemelC reteP oisseT erotavlaS smadA yaK enoelroC otiV',
 'Vt oloeKyAasSlaoeTsi ee lmnaTmHgn')
# built in classes
# almost all the programming I do builds classes
class MyClass():
    def __init__(self):
        self.fact = staticmethod(fact)
        self.y = 20

c = MyClass()
c.x = 10
c.x + c.y, c.fact(6)
(30, 720)
# tricks with classes and types: not text book, but clever it works
C = type('MyClass', (), {'fact': staticmethod(fact), 'y': 20})
c = C()
c.x = 10
c.x + c.y, c.fact(6)
(30, 720)
# introspection: all the non-internal methods of str
# love the depth of built in str support
methods = [s for s in dir(str) if s[0] != '_']
# print first 5
print('\n'.join(methods[:5]))
capitalize
casefold
center
count
encode
# get the help on the first 2, f-strings
print('\n\n'.join([f'{n}\n{"="*len(n)}\n{n.__doc__}' for n in methods[:2]]))
capitalize
==========
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.

casefold
========
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.
# flexible selection
[(first, len(z), last) for (first, *z, last) in last_first]
[('C', 12, 'o'), ('A', 8, 'y'), ('T', 15, 'e'), ('C', 13, 'r'), ('H', 8, 'm')]
# argv and kwargs, built in help
def f(x, y, *argv, **kwargs):
    """My example function with argv and kwargs"""
    # oh, and strings auto concatenate
    ans = (f'f called with {x=} {y=}, a vector of length {len(argv)}, '
           f'and keywords with keys {kwargs.keys()}')
    print(ans)

f(3, 'string', 'a', 1, 2, 'z', arg1='arg1', arg2=10)
f(42, 'bare')
f called with x=3 y='string', a vector of length 4, and keywords with keys dict_keys(['arg1', 'arg2'])
f called with x=42 y='bare', a vector of length 0, and keywords with keys dict_keys([])
help(f)
Help on function f in module __main__:

f(x, y, *argv, **kwargs)
    My example function with argv and kwargs
# decorators
def announce(f):
    def decf(*argv, **kwargs):
        print(f'Function f called with {argv=} and {kwargs=}')
        ans = f(*argv, *kwargs)
        print(f'Answer {ans}')
        return ans
    return decf

@announce
def my_func(x, y):
    return x * x + y * y

my_func(1, 2)
Function f called with argv=(1, 2) and kwargs={}
Answer 5
5
# sets, assertions
s1 = set('the quick brown fox jumped over the lazy dog')
assert len(s1) == 26
s2 = set('aeiou')
# set operations, e.g.
s1 - s2
{' ',
 'b',
 'c',
 'd',
 'f',
 'g',
 'h',
 'j',
 'k',
 'l',
 'm',
 'n',
 'p',
 'q',
 'r',
 't',
 'v',
 'w',
 'x',
 'y',
 'z'}
# complex numbers, not in love with the numerical issue
(-4)**.5
(1.2246467991473532e-16+2j)
# see into floats
.25.as_integer_ratio(), .3.as_integer_ratio()
((1, 4), (5404319552844595, 18014398509481984))

That’s enough to be going on with.

Stephen J. Mildenhall. License: CC BY-SA 2.0.

 

Website made with Quarto