Python: Using pandas library[edit]
# to install pandas library go to cmd prompt and type:
# cd %USERPROFILE%\AppData\Local\Programs\Python\Python38-32\Scripts\
# pip install pandas
import pandas as pd

# load data from csv files
df_patients = pd.read_csv (r'patients.csv', sep = ",", decimal=".")
df_visits = pd.read_csv (r'visits.csv', sep = ",", decimal=".")

''' # load data hard coded, create data frames
import io
str_patients = """PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz
"""
df_patients = pd.read_csv(io.StringIO(str_patients), sep = ",", decimal=".")
str_visits = """PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3
"""
df_visits = pd.read_csv(io.StringIO(str_visits), sep = ",", decimal=".")
'''

# typecast from string to datetime so .agg can 'max' it
df_visits['VISIT_DATE'] = pd.to_datetime(df_visits['VISIT_DATE'])

# merge on PATIENT_ID
df_merge = df_patients.merge(df_visits, on='PATIENT_ID', how='left')

# groupby is an intermediate object
df_group = df_merge.groupby(['PATIENT_ID','LASTNAME'], as_index=False)

# note: you can use 'sum' instead of the lambda function but that returns NaN as 0 (zero)
df_result = df_group.agg({'VISIT_DATE': 'max', 'SCORE': [lambda x: x.sum(min_count=1),'mean']})

print(df_result)

  PATIENT_ID LASTNAME LAST_VISIT      SCORE
                             max <lambda_0> mean
0       1001   Hopper 2020-11-19       17.4  5.8
1       2002  Gosling 2020-10-08        6.8  6.8
2       3003   Kemeny 2020-11-12        NaN  NaN
3       4004    Wirth 2020-11-05       15.4  7.7
4       5005    Kurtz        NaT        NaN  NaN

Python: Stdlib csv only[edit]

import csv

fnames = 'patients.csv  patients_visits.csv'.split()

def csv2list(fname):
    with open(fname) as f:
        rows = list(csv.reader(f))
    return rows

patients, visits = data = [csv2list(fname) for fname in fnames]
result = [record.copy() for record in patients]
result[1:] = sorted(result[1:])
#%%
result[0].append('LAST_VISIT')
last = {p: vis for p, vis, *score in visits[1:]}
for record in result[1:]:
    p = record[0]
    record.append(last.get(p, ''))
#%%
result[0] += ['SCORE_SUM', 'SCORE_AVG']
n = {p: 0 for p, *_ in patients[1:]}
tot = n.copy()
for record in visits[1:]:
    p, _, score = record
    if score:
        n[p] += 1
        tot[p] += float(score)
for record in result[1:]:
    p = record[0]
    if n[p]:
        record += [f"{tot[p]:5.1f}", f"{tot[p] / n[p]:5.2f}"]
    else:
        record += ['', '']
#%%
for record in result:
    print(f"| {' | '.join(f'{r:^10}' for r in record)} |")

The code merges and aggregates two datasets from .csv files, specifically 'patients.csv' and 'visits.csv'. It groups the data by patient id and last name, calculates the maximum visit date, and computes the sum and average of the scores per patient. The result is either stored in-memory or displayed on the screen or file. The code is particularly suitable for data science and data processing programming languages like F#, Python, R, SPSS, MATLAB etc., and uses standard libraries and the csv and sqlite3 modules for input parsing and output calculation respectively.


Works with: Python  version 2.7.14
Library: PIL
from PIL import Image

img = Image.new('RGB', (320, 240))
pixels = img.load()
pixels[100,100] = (255,0,0)
img.show()

"Creates a 320x240 window and draws a single red pixel at position (100, 100)."


def readconf(fn):
    ret = {}
    with file(fn) as fp:
        for line in fp:
            # Assume whitespace is ignorable
            line = line.strip()
            if not line or line.startswith('#'): continue

            boolval = True
            # Assume leading ";" means a false boolean
            if line.startswith(';'):
                # Remove one or more leading semicolons
                line = line.lstrip(';')
                # If more than just one word, not a valid boolean
                if len(line.split()) != 1: continue
                boolval = False

            bits = line.split(None, 1)
            if len(bits) == 1:
                # Assume booleans are just one standalone word
                k = bits[0]
                v = boolval
            else:
                # Assume more than one word is a string value
                k, v = bits
            ret[k.lower()] = v
    return ret

if __name__ == '__main__':
    import sys
    conf = readconf(sys.argv[1])
    for k, v in sorted(conf.items()):
        print k, '=', v

The code reads a standard configuration file, ignores lines starting with a hash or semicolon, and blank lines. It sets variables based on the configuration parameters, preserving case sensitivity for parameter data. It also handles optional equals sign used for separating parameter data from the option name and multiple parameters separated by commas. The variables set are 'fullname', 'favouritefruit', 'needspeeling', 'seedsremoved', and 'otherfamily' which is an array.


from math import radians, sin, cos, sqrt, asin

def haversine(lat1, lon1, lat2, lon2):
    R = 6372.8  # Earth radius in kilometers

    dLat = radians(lat2 - lat1)
    dLon = radians(lon2 - lon1)
    lat1 = radians(lat1)
    lat2 = radians(lat2)

    a = sin(dLat / 2)**2 + cos(lat1) * cos(lat2) * sin(dLon / 2)**2
    c = 2 * asin(sqrt(a))

    return R * c

>>> haversine(36.12, -86.67, 33.94, -118.40)
2887.2599506071106
>>>

Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.


Python 3

import urllib.request
print(urllib.request.urlopen("http://rosettacode.org").read())

from http.client import HTTPConnection
conn = HTTPConnection("example.com")
# If you need to use set_tunnel, do so here.
conn.request("GET", "/")
# Alternatively, you can use connect(), followed by the putrequest, putheader and endheaders functions.
result = conn.getresponse()
r1 = result.read() # This retrieves the entire contents.

Python 2

import urllib
print urllib.urlopen("http://rosettacode.org").read()

import urllib2
print urllib2.urlopen("http://rosettacode.org").read()

Library: Requests
Works with: Python version 2.7, 3.4–3.7
import requests
print(requests.get("http://rosettacode.org").text)

The code uses urllib.request, http.client, urllib and urllib2 libraries to access a URL's content and print it to the console. Note that this task does not cover HTTPS requests.


The code validates credit card numbers using the Luhn test. It first reverses the order of the digits in the number, then sums every other odd digit to form a partial sum s1. It then multiplies every other even digit by two, summing the digits if the result is greater than nine to form partial sums for the even digits and sum these to form s2. If the sum of s1 and s2 ends in zero, the number is deemed a valid credit card number. The code includes a function that validates a number with the Luhn test and uses it to validate a set of given numbers. It also offers alternative methods using itertools cycle with map and reduce, or defining the Luhn predicate over strings rather than integers, and cycling lambdas rather than integers.


>>> def j(n, k):
	p, i, seq = list(range(n)), 0, []
	while p:
		i = (i+k-1) % len(p)
		seq.append(p.pop(i))
	return 'Prisoner killing order: %s.\nSurvivor: %i' % (', '.join(str(i) for i in seq[:-1]), seq[-1])

>>> print(j(5, 2))
Prisoner killing order: 1, 3, 0, 4.
Survivor: 2
>>> print(j(41, 3))
Prisoner killing order: 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 38, 0, 4, 9, 13, 18, 22, 27, 31, 36, 40, 6, 12, 19, 25, 33, 39, 7, 16, 28, 37, 10, 24, 1, 21, 3, 34, 15.
Survivor: 30
>>>

Faster way[edit]

>>>def josephus(n, k):
        r = 0
        for i in xrange(1, n+1):
            r = (r+k)%i
        return 'Survivor: %d' %r

>>> print(josephus(5, 2))
Survivor: 2
>>> print(josephus(41, 3))
Survivor: 30
>>>

Alternate solution with a circular linked list[edit]

def josephus(n, k):
    a = list(range(1, n + 1))
    a[n - 1] = 0
    p = 0
    v = []
    while a[p] != p:
        for i in range(k - 2):
            p = a[p]
        v.append(a[p])
        a[p] = a[a[p]]
        p = a[p]
    v.append(p)
    return v

josephus(10, 2)
[1, 3, 5, 7, 9, 2, 6, 0, 8, 4]

josephus(41, 3)[-1]
30

learning iter in python[edit]
from itertools import compress, cycle
def josephus(prisoner, kill, surviver):
    p = range(prisoner)
    k = [0] * kill
    k[kill-1] = 1
    s = [1] * kill
    s[kill -1] = 0
    queue = p

    queue = compress(queue, cycle(s))
    try:
        while True:
            p.append(queue.next())
    except StopIteration:
        pass

    kil=[]
    killed = compress(p, cycle(k))
    try:
        while True:
            kil.append(killed.next())
    except StopIteration:
        pass

    print 'The surviver is: ', kil[-surviver:]
    print 'The kill sequence is ', kil[:prisoner-surviver]

josephus(41,3,2)
The surviver is:  [15, 30]
The kill sequence is  [2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 38, 0, 4, 9, 13, 18, 22, 27, 31, 36, 40, 6, 12, 19, 25, 33, 39, 7, 16, 28, 37, 10, 24, 1, 21, 3, 34]
josephus(5,2,1)
The surviver is:  [2]
The kill sequence is  [1, 3, 0, 4]

The code implements the Josephus problem, determining the final survivor when n prisoners are arranged in a circle and every k-th prisoner is executed until only one remains. It also provides a method to calculate the prisoner at any given position in the killing sequence. The prisoners can be numbered from either 0 to n-1 or 1 to n. The code returns the killing order, with the last prisoner in the list being the survivor.


"ha" * 5  # ==> "hahahahaha"

5 * "ha"  # ==> "hahahahaha"
Using a Function[edit]
def repeat(s, times):
    return s * times

print(repeat("ha", 5))

The code takes a string or a character and repeats it a specified number of times. For instance, repeat("ha", 5) will output "hahahahaha". Similarly, repeat-char("*", 5) will output "*****". It treats characters as strings of length one.


import re

string = "This is a string"

if re.search('string$', string):
    print("Ends with string.")

string = re.sub(" a ", " another ", string)
print(string)

"Matches a string with a regular expression and performs substitution on a part of the string using the same regular expression."


x = int(raw_input("Number 1: "))
y = int(raw_input("Number 2: "))

print "Sum: %d" % (x + y)
print "Difference: %d" % (x - y)
print "Product: %d" % (x * y)
print "Quotient: %d" % (x / y)     #  or x // y  for newer python versions.
                                   # truncates towards negative infinity
print "Remainder: %d" % (x % y)    # same sign as second operand
print "Quotient: %d with Remainder: %d" % divmod(x, y)
print "Power: %d" % x**y

## Only used to keep the display up when the program ends
raw_input( )

def getnum(prompt):
    while True: # retrying ...
        try:
            n = int(raw_input(prompt))
        except ValueError:
            print "Input could not be parsed as an integer. Please try again."\
            continue
        break
    return n

x = getnum("Number1: ")
y = getnum("Number2: ")
...

quotient, remainder = divmod(355,113)

Python 3.0 compatible code[edit]
def arithmetic(x, y):
    for op in "+ - * // % **".split():
        expr = "%(x)s %(op)s %(y)s" % vars()
        print("%s\t=> %s" % (expr, eval(expr)))

arithmetic(12, 8)
arithmetic(input("Number 1: "), input("Number 2: "))

The code takes two integers as input from the user and calculates their sum, difference, product, integer quotient, remainder, and exponentiation. It also indicates how the quotient is rounded and the sign of the remainder. The code does not include error handling. It also provides an example of the 'divmod' operator.


>>> "the three truths".count("th")
3
>>> "ababababab".count("abab")
2

The code defines a function to count the number of non-overlapping occurrences of a given substring within a larger string. The function takes two arguments: the main string and the substring to search for. It returns an integer representing the count of non-overlapping occurrences. The function prioritizes the highest number of non-overlapping matches, typically matching from left-to-right or right-to-left.


Recursive[edit]
def hanoi(ndisks, startPeg=1, endPeg=3):
    if ndisks:
        hanoi(ndisks-1, startPeg, 6-startPeg-endPeg)
        print(f"Move disk {ndisks} from peg {startPeg} to peg {endPeg}")
        hanoi(ndisks-1, 6-startPeg-endPeg, endPeg)

hanoi(4)

The following codes solve the Towers of Hanoi problem using recursion and also generate a simple visualization of the solution. The code also includes a refactored version that separates the data definition from its display. Additionally, it references a 3D Hanoi game example from VPython and GitHub.


Imperative[edit]
def binomialCoeff(n, k):
    result = 1
    for i in range(1, k+1):
        result = result * (n-i+1) / i
    return result

if __name__ == "__main__":
    print(binomialCoeff(5, 3))

The code calculates any binomial coefficient using the provided formula. It is specifically designed to output the binomial coefficient of 5 choose 3, which equals 10. The code also considers different scenarios such as combinations and permutations, order importance, and replacement. It also allows for abstracting for legibility and ease of reuse, and includes Python comments and type hints for clarity.


Translation of: Java

def shell(seq):
    inc = len(seq) // 2
    while inc:
        for i, el in enumerate(seq[inc:], inc):
            while i >= inc and seq[i - inc] > el:
                seq[i] = seq[i - inc]
                i -= inc
            seq[i] = el
        inc = 1 if inc == 2 else inc * 5 // 11

implement the Shell sort algorithm to sort an array of elements. The algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size is reduced after each pass until it reaches 1, at which point the data is almost sorted. The method sorts in place, so a copy should be made if the original unsorted list needs to be preserved.


Works with: Python version 3.1

# String masquerading as ppm file (version P3)
import io
ppmfileout = io.StringIO('')

def togreyscale(self):
    for h in range(self.height):
        for w in range(self.width):
            r, g, b = self.get(w, h)
            l = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
            self.set(w, h, Colour(l, l, l))

Bitmap.togreyscale = togreyscale

# Draw something simple
bitmap = Bitmap(4, 4, white)
bitmap.fillrect(1, 0, 1, 2, Colour(127, 0, 63))
bitmap.set(3, 3, Colour(0, 127, 31))
print('Colour:')
# Write to the open 'file' handle
bitmap.writeppmp3(ppmfileout)
print(ppmfileout.getvalue())
print('Grey:')
bitmap.togreyscale()
ppmfileout = io.StringIO('')
bitmap.writeppmp3(ppmfileout)
print(ppmfileout.getvalue())

'''
The print statement above produces the following output :

Colour:
P3
# generated from Bitmap.writeppmp3
4 4
255
   255 255 255   255 255 255   255 255 255     0 127  31
   255 255 255   255 255 255   255 255 255   255 255 255
   255 255 255   127   0  63   255 255 255   255 255 255
   255 255 255   127   0  63   255 255 255   255 255 255

Grey:
P3
# generated from Bitmap.writeppmp3
4 4
254
   254 254 254   254 254 254   254 254 254    93  93  93
   254 254 254   254 254 254   254 254 254   254 254 254
   254 254 254    31  31  31   254 254 254   254 254 254
   254 254 254    31  31  31   254 254 254   254 254 254

'''

extend the data storage type to support grayscale images, convert color images to grayscale and vice versa using the CIE recommended formula for luminance calculation. The code also ensures that rounding errors in floating-point arithmetic do not cause run-time issues or distorted results.


Using PyQt[edit]
Library: PyQt5
#!/usr/bin/env python3
import sys

from PyQt5.QtCore import QBasicTimer, Qt
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import QApplication, QLabel

class Marquee(QLabel):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.right_to_left_direction = True
        self.initUI()
        self.timer = QBasicTimer()
        self.timer.start(80, self)

    def initUI(self):
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setText("Hello World! ")
        self.setFont(QFont(None, 50, QFont.Bold))
        # make more irritating for the authenticity with <marquee> element
        self.setStyleSheet("QLabel {color: cyan; }")

    def timerEvent(self, event):
        i = 1 if self.right_to_left_direction else -1
        self.setText(self.text()[i:] + self.text()[:i])  # rotate

    def mouseReleaseEvent(self, event):  # change direction on mouse release
        self.right_to_left_direction = not self.right_to_left_direction

    def keyPressEvent(self, event):  # exit on Esc
        if event.key() == Qt.Key_Escape:
            self.close()

app = QApplication(sys.argv)
w = Marquee()
# center widget on the screen
w.adjustSize()  # update w.rect() now
w.move(QApplication.instance().desktop().screen().rect().center()
       - w.rect().center())
w.show()
sys.exit(app.exec())

Using pygame[edit]
Library: pygame
import pygame, sys
from pygame.locals import *
pygame.init()

YSIZE = 40
XSIZE = 150

TEXT = "Hello World! "
FONTSIZE = 32

LEFT = False
RIGHT = True

DIR = RIGHT

TIMETICK = 180
TICK = USEREVENT + 2

TEXTBOX = pygame.Rect(10,10,XSIZE,YSIZE)

pygame.time.set_timer(TICK, TIMETICK)

window = pygame.display.set_mode((XSIZE, YSIZE))
pygame.display.set_caption("Animation")

font = pygame.font.SysFont(None, FONTSIZE)
screen = pygame.display.get_surface()

def rotate():
    index = DIR and -1 or 1
    global TEXT
    TEXT = TEXT[index:]+TEXT[:index]

def click(position):
    if TEXTBOX.collidepoint(position):
        global DIR
        DIR = not DIR

def draw():
    surface = font.render(TEXT, True, (255,255,255), (0,0,0))
    global TEXTBOX
    TEXTBOX = screen.blit(surface, TEXTBOX)

def input(event):
    if event.type == QUIT:
        sys.exit(0)
    elif event.type == MOUSEBUTTONDOWN:
        click(event.pos)
    elif event.type == TICK:
        draw()
        rotate()

while True:
    input(pygame.event.wait())
    pygame.display.flip()

Using Tkinter[edit]
import Tkinter as tki

def scroll_text(s, how_many):
    return s[how_many:] + s[:how_many]

direction = 1
tk = tki.Tk()
var = tki.Variable(tk)

def mouse_handler(point):
    global direction
    direction *= -1

def timer_handler():
    var.set(scroll_text(var.get(),direction))
    tk.after(125, timer_handler)

var.set('Hello, World! ')
tki.Label(tk, textvariable=var).pack()
tk.bind("<Button-1>", mouse_handler)
tk.after(125, timer_handler)
tk.title('Python Animation')
tki.mainloop()

Create a GUI animation where the string "Hello World! " appears to rotate right by periodically moving the last letter to the front. The direction of rotation reverses when the user clicks on the text.


val = 0
while True:
   val +=1
   print val
   if val % 6 == 0: break

val = 1
print val
while val % 6 != 0:
   val += 1
   print val

Initializes a value at 0, then enters a loop where it increments the value by 1 and prints it each iteration. The loop continues until the value modulo 6 equals 0. The loop is guaranteed to execute at least once. Python's lack of a do-while loop means the loop body is executed before the condition is checked.


2.x[edit]

Byte Length[edit]
Works with: Python version 2.x

print len('ascii')
# 5

# The letter Alef
print len(u'\u05d0'.encode('utf-8'))
# 2
print len(u'\u05d0'.encode('iso-8859-8'))
# 1

#!/bin/env python
# -*- coding: UTF-8 -*-
s = u"møøse"
assert len(s) == 5
assert len(s.encode('UTF-8')) == 7
assert len(s.encode('UTF-16-BE')) == 10 # There are 3 different UTF-16 encodings: LE and BE are little endian and big endian respectively, the third one (without suffix) adds 2 extra leading bytes: the byte-order mark (BOM).
Character Length[edit]
Works with: Python version 2.4

import sys
sys.maxunicode # 1114111 on a wide build, 65535 on a narrow build

print len('ascii')
# 5
print len(u'\u05d0') # the letter Alef as unicode literal
# 1
print len('\xd7\x90'.decode('utf-8')) # Same encoded as utf-8 string
# 1
print hex(sys.maxunicode), len(unichr(0x1F4A9))
# ('0x10ffff', 1)

print hex(sys.maxunicode), len(unichr(0x1F4A9))
# ('0xffff', 2)
3.x[edit]

Byte Length[edit]

print(len(b'Hello, World!'))
# 13

# The letter Alef
print(len('\u05d0'.encode())) # the default encoding is utf-8 in Python3
# 2
print(len('\u05d0'.encode('iso-8859-8')))
# 1

#!/bin/env python
# -*- coding: UTF-8 -*-
s = "møøse"
assert len(s) == 5
assert len(s.encode('UTF-8')) == 7
assert len(s.encode('UTF-16-BE')) == 10 # There are 3 different UTF-16 encodings: LE and BE are little endian and big endian respectively, the third one (without suffix) adds 2 extra leading bytes: the byte-order mark (BOM).
u="𝔘𝔫𝔦𝔠𝔬𝔡𝔢"
assert len(u.encode()) == 28
assert len(u.encode('UTF-16-BE')) == 28
Character Length[edit]

print(len("𝔘𝔫𝔦𝔠𝔬𝔡𝔢"))
# 7

import sys
sys.maxunicode # 1114111 on a wide build, 65535 on a narrow build
print(len('ascii'))
# 5
print(len('\u05d0')) # the letter Alef as unicode literal
# 1

print(len(b'\xd7\x90'.decode('utf-8'))) # Alef encoded as utf-8 byte sequence
# 1
print(hex(sys.maxunicode), len(unichr(0x1F4A9)))
# ('0x10ffff', 1)

print(hex(sys.maxunicode), len(unichr(0x1F4A9)))
# ('0xffff', 2)

The code calculates the character and byte length of a string, taking into account different encodings like UTF-8 and UTF-16. It handles Unicode code points and non-BMP code points correctly, providing actual character counts in code points. It also provides the string length in graphemes if possible. In Python 2.x, it differentiates between regular and Unicode strings, and in Python 3.x, it handles Unicode strings and byte sequences. It also accounts for different Python build options and their impact on string length calculation.


import random
rand = random.SystemRandom()
rand.randint(1,10)

demonstrate how to generate a random 32-bit number using the system's built-in mechanism, not just a software algorithm.


print "knight"[1:]     # strip first character
print "socks"[:-1]     # strip last character
print "brooms"[1:-1]   # strip both first and last characters

from functools import (reduce)

def main():
    for xs in transpose(
        (chunksOf(3)(
            ap([tail, init, compose(init)(tail)])(
                ['knights', 'socks', 'brooms']
            )
        ))
    ):
        print(xs)

# GENERIC -------------------------------------------------

# tail :: [a] -> [a]
def tail(xs):
    return xs[1:]

# init::[a] - > [a]
def init(xs):
    return xs[:-1]

# ap (<*>) :: [(a -> b)] -> [a] -> [b]
def ap(fs):
    return lambda xs: reduce(
        lambda a, f: a + reduce(
            lambda a, x: a + [f(x)], xs, []
        ), fs, []
    )

# chunksOf :: Int -> [a] -> [[a]]
def chunksOf(n):
    return lambda xs: reduce(
        lambda a, i: a + [xs[i:n + i]],
        range(0, len(xs), n), []
    ) if 0 < n else []

# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
    return lambda f: lambda x: g(f(x))

# transpose :: [[a]] -> [[a]]
def transpose(xs):
    return list(map(list, zip(*xs)))

if __name__ == '__main__':
    main()

demonstrate how to remove the first, last, or both first and last characters from a string, ensuring compatibility with any valid Unicode code point in UTF-8 or UTF-16 encoding. The program references logical characters, not code units. Handling all Unicode characters for other encodings is not required.


Linux (including cygwin) and Mac OSX Leopard[edit]
Works with: Python version 2.6

import __main__, os

def isOnlyInstance():
    # Determine if there are more than the current instance of the application
    # running at the current time.
    return os.system("(( $(ps -ef | grep python | grep '[" +
                     __main__.__file__[0] + "]" + __main__.__file__[1:] +
                     "' | wc -l) > 1 ))") != 0

The code checks if an application instance is already running. If so, it displays a message and exits. It uses a lock file or directory to ensure only one instance runs at a time. This code must be run from an application, not an interpreter.


#!/usr/bin/env python3

import tkinter as tk # import the module.

root = tk.Tk() # Create an instance of the class.
root.state('zoomed') # Maximized the window.
root.update_idletasks() # Update the display.
tk.Label(root, text=(str(root.winfo_width())+ " x " +str(root.winfo_height())),
         font=("Helvetica", 25)).pack() # add a label and set the size to text.
root.mainloop()

1366 x 706

"Determines the maximum height and width of a window that can fit within the physical display area of the screen, considering adjustments for window decorations and menubars. It also considers scenarios with multiple monitors and tiling window managers."


def initiate():
    box.append([0, 1, 2, 9, 10, 11, 18, 19, 20])
    box.append([3, 4, 5, 12, 13, 14, 21, 22, 23])
    box.append([6, 7, 8, 15, 16, 17, 24, 25, 26])
    box.append([27, 28, 29, 36, 37, 38, 45, 46, 47])
    box.append([30, 31, 32, 39, 40, 41, 48, 49, 50])
    box.append([33, 34, 35, 42, 43, 44, 51, 52, 53])
    box.append([54, 55, 56, 63, 64, 65, 72, 73, 74])
    box.append([57, 58, 59, 66, 67, 68, 75, 76, 77])
    box.append([60, 61, 62, 69, 70, 71, 78, 79, 80])
    for i in range(0, 81, 9):
        row.append(range(i, i+9))
    for i in range(9):
        column.append(range(i, 80+i, 9))

def valid(n, pos):
    current_row = pos/9
    current_col = pos%9
    current_box = (current_row/3)*3 + (current_col/3)
    for i in row[current_row]:
        if (grid[i] == n):
            return False
    for i in column[current_col]:
        if (grid[i] == n):
            return False
    for i in box[current_box]:
        if (grid[i] == n):
            return False
    return True

def solve():
    i = 0
    proceed = 1
    while(i < 81):
        if given[i]:
            if proceed:
                    i += 1
            else:
                i -= 1
        else:
            n = grid[i]
            prev = grid[i]
            while(n < 9):
              if (n < 9):
                  n += 1
              if valid(n, i):
                  grid[i] = n
                  proceed = 1
                  break
            if (grid[i] == prev):
               grid[i] = 0
               proceed = 0
            if proceed:
               i += 1
            else:
               i -=1

def inputs():
    nextt = 'T'
    number = 0
    pos = 0
    while(not(nextt == 'N' or nextt == 'n')):
        print "Enter the position:",
        pos = int(raw_input())
        given[pos - 1] = True
        print "Enter the numerical:",
        number = int(raw_input())
        grid[pos - 1] = number
        print "Do you want to enter another given?(Y, for yes: N, for no)"
        nextt = raw_input()

grid = [0]*81
given = [False]*81
box = []
row = []
column = []
initiate()
inputs()
solve()
for i in range(9):
    print grid[i*9:i*9+9]
raw_input()

implement a Sudoku solver for a 9x9 grid, displaying the result in a human-readable format. The solution uses a simple backtrack algorithm, which may take longer for grids larger than 9x9. The code also references the Algorithmics of Sudoku and Python Sudoku Solver Computerphile video for implementation guidance.


from random import randrange

def knuth_shuffle(x):
    for i in range(len(x)-1, 0, -1):
        j = randrange(i + 1)
        x[i], x[j] = x[j], x[i]

x = list(range(10))
knuth_shuffle(x)
print("shuffled:", x)

implement the Knuth shuffle algorithm, also known as the Fisher-Yates shuffle, which randomly shuffles the elements of an array. The algorithm modifies the input array in-place, but can be adjusted to return a new shuffled array if necessary. It can also be amended to iterate from left to right for convenience. The Python standard library function random.shuffle uses this algorithm.


import calendar

def last_fridays(year):
    for month in range(1, 13):
        last_friday = max(week[calendar.FRIDAY]
            for week in calendar.monthcalendar(year, month))
        print('{:4d}-{:02d}-{:02d}'.format(year, month, last_friday))

The code takes a year as input and outputs the dates of the last Fridays of each month for that year.


import sys
sys.stdout.write("Goodbye, World!")

Works with: Python version 3.x
print("Goodbye, World!", end="")

"Display the string 'Goodbye, World!' without appending a newline at the end."


Works with: Python version 2.5
Library: Tkinter
import Tkinter,tkSimpleDialog

root = Tkinter.Tk()
root.withdraw()

number = tkSimpleDialog.askinteger("Integer", "Enter a Number")
string = tkSimpleDialog.askstring("String", "Enter a String")

Works with: Python version 3.7
Library: Tkinter
import tkinter
import tkinter.simpledialog as tks

root = tkinter.Tk()
root.withdraw()

number = tks.askinteger("Integer", "Enter a Number")
string = tks.askstring("String", "Enter a String")

tkinter.messagebox.showinfo("Results", f"Your input:\n {number} {string}")

"Implement functionality to accept a string and the integer 75000 as inputs from a graphical user interface."


def caesar(s, k, decode = False):
	if decode: k = 26 - k
	return "".join([chr((ord(i) - 65 + k) % 26 + 65)
				for i in s.upper()
				if ord(i) >= 65 and ord(i) <= 90 ])

msg = "The quick brown fox jumped over the lazy dogs"
print msg
enc = caesar(msg, 11)
print enc
print caesar(enc, 11, decode = True)

implement both encoding and decoding of a Caesar cipher. The cipher uses a key from 1 to 25 to rotate the letters of the alphabet, replacing each letter with the next 1st to 25th letter. The codes also include a variant with memoization of translation tables as an alternate solution. The Caesar cipher is identical to the Vigenère cipher with a key of length 1 and to the Rot-13 cipher with a key of 13.


Functional[edit]
gcd[edit]

>>> import fractions
>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0

>>> lcm(12, 18)
36
>>> lcm(-6, 14)
42
>>> assert lcm(0, 2) == lcm(2, 0) == 0
>>>

'''Least common multiple'''

from inspect import signature

# lcm :: Int -> Int -> Int
def lcm(x):
    '''The smallest positive integer divisible
       without remainder by both x and y.
    '''
    return lambda y: 0 if 0 in (x, y) else abs(
        y * (x // gcd_(x)(y))
    )

# gcd_ :: Int -> Int -> Int
def gcd_(x):
    '''The greatest common divisor in terms of
       the divisibility preordering.
    '''
    def go(a, b):
        return go(b, a % b) if 0 != b else a
    return lambda y: go(abs(x), abs(y))

# TEST ----------------------------------------------------
# main :: IO ()
def main():
    '''Tests'''

    print(
        fTable(
            __doc__ + 's of 60 and [12..20]:'
        )(repr)(repr)(
            lcm(60)
        )(enumFromTo(12)(20))
    )

    pairs = [(0, 2), (2, 0), (-6, 14), (12, 18)]
    print(
        fTable(
            '\n\n' + __doc__ + 's of ' + repr(pairs) + ':'
        )(repr)(repr)(
            uncurry(lcm)
        )(pairs)
    )

# GENERIC -------------------------------------------------

# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
    '''Integer enumeration from m to n.'''
    return lambda n: list(range(m, 1 + n))

# uncurry :: (a -> b -> c) -> ((a, b) -> c)
def uncurry(f):
    '''A function over a tuple, derived from
       a vanilla or curried function.
    '''
    if 1 < len(signature(f).parameters):
        return lambda xy: f(*xy)
    else:
        return lambda xy: f(xy[0])(xy[1])

# unlines :: [String] -> String
def unlines(xs):
    '''A single string derived by the intercalation
       of a list of strings with the newline character.
    '''
    return '\n'.join(xs)

# FORMATTING ----------------------------------------------

# fTable :: String -> (a -> String) ->
#                     (b -> String) -> (a -> b) -> [a] -> String
def fTable(s):
    '''Heading -> x display function -> fx display function ->
                     f -> xs -> tabular string.
    '''
    def go(xShow, fxShow, f, xs):
        ys = [xShow(x) for x in xs]
        w = max(map(len, ys))
        return s + '\n' + '\n'.join(map(
            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
            xs, ys
        ))
    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
        xShow, fxShow, f, xs
    )

# MAIN ---
if __name__ == '__main__':
    main()

The code calculates the least common multiple (LCM) of two integers, m and n. It identifies the smallest positive integer that is a factor of both m and n. If either m or n is zero, the LCM is zero. The code may use the greatest common divisor (gcd) formula or merge the prime decompositions of m and n to find the LCM.


Procedural[edit]

#!/usr/bin/env python3

import math

def cusip_check(cusip):
    if len(cusip) != 9:
        raise ValueError('CUSIP must be 9 characters')

    cusip = cusip.upper()
    total = 0
    for i in range(8):
        c = cusip[i]
        if c.isdigit():
            v = int(c)
        elif c.isalpha():
            p = ord(c) - ord('A') + 1
            v = p + 9
        elif c == '*':
            v = 36
        elif c == '@':
            v = 37
        elif c == '#':
            v = 38

        if i % 2 != 0:
            v *= 2

        total += int(v / 10) + v % 10
    check = (10 - (total % 10)) % 10
    return str(check) == cusip[-1]

if __name__ == '__main__':
    codes = [
            '037833100',
            '17275R102',
            '38259P508',
            '594918104',
            '68389X106',
            '68389X105'
            ]
    for code in codes:
        print(f'{code} -> {cusip_check(code)}')

037833100 -> True
17275R102 -> True
38259P508 -> True
594918104 -> True
68389X106 -> False
68389X105 -> True

Composition of pure functions[edit]
Works with: Python version 3.7

'''CUSIP'''

from itertools import (cycle, islice, starmap)
from functools import (reduce)
from operator import (add)
from enum import (Enum)

# isCusip :: Dict -> String -> Bool
def isCusip(dct):
    '''Test for the validity of a CUSIP string in the
       context of a supplied dictionary of char values'''
    def go(s):
        ns = [dct[c] for c in list(s) if c in dct]
        return 9 == len(ns) and (
            ns[-1] == (
                10 - (
                    sum(zipWith(
                        lambda f, x: add(*divmod(f(x), 10))
                    )(cycle([identity, double]))(
                        take(8)(ns)
                    )) % 10
                )
            ) % 10
        )
    return go

# cusipCharDict :: () -> Dict Char Int
def cusipCharDict():
    '''Dictionary of integer values for CUSIP characters'''
    def kv(a, ic):
        i, c = ic
        a[c] = i
        return a
    return reduce(
        kv,
        enumerate(
            enumFromTo('0')('9') + (
                enumFromTo('A')('Z') + list('*&#')
            )
        ),
        {}
    )

# TEST -------------------------------------------------
# main :: IO ()
def main():
    '''Tests'''

    # cusipTest :: String -> Bool
    cusipTest = isCusip(cusipCharDict())

    print(
        tabulated('Valid as CUSIP string:')(
            cusipTest
        )([
            '037833100',
            '17275R102',
            '38259P508',
            '594918104',
            '68389X106',
            '68389X105'
        ])
    )

# GENERIC -------------------------------------------------

# double :: Num -> Num
def double(x):
    '''Wrapped here as a function for the zipWith expression'''
    return 2 * x

# enumFromTo :: Enum a => a -> a -> [a]
def enumFromTo(m):
    '''Enumeration of values [m..n]'''
    def go(x, y):
        t = type(m)
        i = fromEnum(x)
        d = 0 if t != float else (x - i)
        return list(map(
            lambda x: toEnum(t)(d + x),
            range(i, 1 + fromEnum(y))
        ) if int != t else range(x, 1 + y))
    return lambda n: go(m, n)

# fromEnum :: Enum a => a -> Int
def fromEnum(x):
    '''Index integer for enumerable value.'''
    return ord(x) if str == type(x) else (
        x.value if isinstance(x, Enum) else int(x)
    )

# mul :: Num -> Num -> Num
def mul(x):
    '''Function version of (*) operator;
       a curried equivalent of operator.mul'''
    return lambda y: x * y

# identity :: a -> a
def identity(x):
    '''The identity function.
       The usual 'id' is reserved in Python.'''
    return x

# tabulated :: String -> (a -> b) -> [a] -> String
def tabulated(s):
    '''heading -> function -> input List -> tabulated output string'''
    def go(f, xs):
        def width(x):
            return len(str(x))
        w = width(max(xs, key=width))
        return s + '\n' + '\n'.join([
            str(x).rjust(w, ' ') + ' -> ' + str(f(x)) for x in xs
        ])
    return lambda f: lambda xs: go(f, xs)

# take :: Int -> [a] -> [a]
# take :: Int -> String -> String
def take(n):
    '''The prefix of xs of length n,
       or xs itself if n > length xs.'''
    return lambda xs: (
        xs[0:n]
        if isinstance(xs, list)
        else list(islice(xs, n))
    )

# toEnum :: Type -> Int -> a
def toEnum(t):
    '''Enumerable value from index integer'''
    dct = {
        int: int,
        float: float,
        str: chr,
        bool: bool
    }
    return lambda x: dct[t](x) if t in dct else t(x)

# zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
def zipWith(f):
    '''Zipping with a custom (rather than tuple) function'''
    return lambda xs: lambda ys: (
        list(starmap(f, zip(xs, ys)))
    )

# MAIN ---
if __name__ == '__main__':
    main()

The code verifies the correctness of the last digit (check digit) in a CUSIP code, which is a nine-character alphanumeric code that identifies a North American financial security. It takes an 8-character CUSIP as input and calculates the check digit using the given algorithm, comparing it with the actual check digit to ensure accuracy. The code uses Python 3.6 and includes a number of general and reusable abstractions.


>>> import platform, sys, socket
>>> platform.architecture()
('64bit', 'ELF')
>>> platform.machine()
'x86_64'
>>> platform.node()
'yourhostname'
>>> platform.system()
'Linux'
>>> sys.byteorder
little
>>> socket.gethostname()
'yourhostname'
>>>

"Outputs the word size and endianness of the host machine."


Python: Using web scraping[edit]

import requests
import re

response = requests.get("http://rosettacode.org/wiki/Category:Programming_Languages").text
languages = re.findall('title="Category:(.*?)">',response)[:-3] # strip last 3

response = requests.get("http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000").text
response = re.sub('(\d+),(\d+)',r'\1'+r'\2',response)           # strip ',' from popular languages above 999 members
members  = re.findall('
]+>([^<]+)[^(]*[(](\\d+) member[s]*[)]
',response) # find language and members

for cnt, (language, members) in enumerate(sorted(members, key=lambda x: -int(x[1]))[:15]): # show only top 15 languages
    if language in languages:
        print("{:4d} {:4d} - {}".format(cnt+1, int(members), language))

Output (as of Dec 21, 2020):
  1 1306 - Go
  2 1275 - Phix
  3 1265 - Julia
  4 1257 - Raku
  5 1196 - Python
  6 1182 - Perl
  7 1107 - Kotlin
  8 1080 - C
  9 1074 - Java
 10 1061 - Racket
 11 1022 - REXX
 12 1012 - Zkl
 13 1002 - J
 14  983 - Ruby
 15  972 - Haskell

Python: Using MediaWiki API method[edit]
import requests
import operator
import re

api_url    = 'http://rosettacode.org/mw/api.php'
languages  = {}

parameters = {
    'format':       'json',
    'action':       'query',
    'generator':    'categorymembers',
    'gcmtitle':     'Category:Programming Languages',
    'gcmlimit':     '200',
    'gcmcontinue':  '',
    'continue':     '',
    'prop':         'categoryinfo'
}

while(True):
    response = requests.get(api_url, params=parameters).json()
    for k,v in response['query']['pages'].items():
        if 'title' in v and 'categoryinfo' in v:
          languages[v['title']]=v['categoryinfo']['size']
    if 'continue' in response:
        gcmcontinue = response['continue']['gcmcontinue']
#        print(gcmcontinue)
        parameters.update({'gcmcontinue': gcmcontinue})
    else:
        break

# report top 15 languages
for i, (language, size) in enumerate(sorted(languages.items(), key=operator.itemgetter(1), reverse=True)[:15]):
    print("{:4d} {:4d} - {}".format(i+1, size, re.sub('Category:','',language))) # strip Category: from language

Output (as of Dec 21, 2020):
  1 1306 - Go
  2 1275 - Phix
  3 1265 - Julia
  4 1257 - Raku
  5 1196 - Python
  6 1182 - Perl
  7 1107 - Kotlin
  8 1080 - C
  9 1074 - Java
 10 1061 - Racket
 11 1022 - REXX
 12 1012 - Zkl
 13 1002 - J
 14  983 - Ruby
 15  972 - Haskell

The code sorts the most popular computer programming languages based on the number of members in Rosetta Code categories. It uses either web scraping or API methods to access the data. The code also has the option to filter incorrect results. The final output is a complete ranked list of all programming languages.


for i in collection:
   print i

lines = words = characters = 0
f = open('somefile','r')
for eachline in f:
    lines += 1
    for eachword in eachline.split():
        words += 1
        for eachchar in eachword:
            characters += 1

print lines, words, characters

d = {3: "Earth", 1: "Mercury", 4: "Mars", 2: "Venus"}
for k in sorted(d):
    print("%i: %s" % (k, d[k]))

d = {"London": "United Kingdom", "Berlin": "Germany", "Rome": "Italy", "Paris": "France"}
for k in sorted(d):
    print("%s: %s" % (k, d[k]))
Works with: Python version 2.x
d = {"fortytwo": 42, 3.14159: "pi", 23: "twentythree", "zero": 0, 13: "thirteen"}
for k in sorted(d):
    print("%s: %s" % (k, d[k]))

Iterates and prints each element in a collection in order using a "for each" loop or another loop if "for each" is not available. In Python, this includes iterating over lists, tuples, strings, dictionaries, files, etc. The order of iteration depends on the inherent order of the collection. For dictionaries, the iteration can be done in alphabetic or numeric key order by sorting the keys.


Works with: Python version 2.5Works with: Python version 3.0
text = "Hello,How,Are,You,Today"
tokens = text.split(',')
print ('.'.join(tokens))

print ('.'.join('Hello,How,Are,You,Today'.split(',')))

Tokenizes a string by commas into an array, and displays the words to the user separated by a period. May display a trailing period.


Built-in[edit]
Works with: Python version 2.6+
from fractions import gcd
Works with: Python version 3.7

from math import gcd
Iterative Euclid algorithm[edit]
def gcd_iter(u, v):
    while v:
        u, v = v, u % v
    return abs(u)
Recursive Euclid algorithm[edit]

def gcd(u, v):
    return gcd(v, u % v) if v else abs(u)
Tests[edit]
>>> gcd(0,0)
0
>>> gcd(0, 10) == gcd(10, 0) == gcd(-10, 0) == gcd(0, -10) == 10
True
>>> gcd(9, 6) == gcd(6, 9) == gcd(-6, 9) == gcd(9, -6) == gcd(6, -9) == gcd(-9, 6) == 3
True
>>> gcd(8, 45) == gcd(45, 8) == gcd(-45, 8) == gcd(8, -45) == gcd(-8, 45) == gcd(45, -8) == 1
True
>>> gcd(40902, 24140) # check Knuth :)
34

Iterative binary algorithm[edit]

def gcd_bin(u, v):
    u, v = abs(u), abs(v) # u >= 0, v >= 0
    if u < v:
        u, v = v, u # u >= v >= 0
    if v == 0:
        return u

    # u >= v > 0
    k = 1
    while u & 1 == 0 and v & 1 == 0: # u, v - even
        u >>= 1; v >>= 1
        k <<= 1

    t = -v if u & 1 else u
    while t:
        while t & 1 == 0:
            t >>= 1
        if t > 0:
            u = t
        else:
            v = -t
        t = u - v
    return u * k
Notes on performance[edit]

are designed to find the greatest common divisor (GCD), also known as the greatest common factor (gcf) or greatest common measure, of two integers. The codes include different methods such as Euclid, iterative, and binary, with varying execution times. The codes are written in Python 2.5, as fractions.gcd is deprecated in Python 3.


Works with: Python version 2.3 or above
import SocketServer

HOST = "localhost"
PORT = 12321

# this server uses ThreadingMixIn - one thread per connection
# replace with ForkMixIn to spawn a new process per connection

class EchoServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    # no need to override anything - default behavior is just fine
    pass

class EchoRequestHandler(SocketServer.StreamRequestHandler):
    """
    Handles one connection to the client.
    """
    def handle(self):
        print "connection from %s" % self.client_address[0]
        while True:
            line = self.rfile.readline()
            if not line: break
            print "%s wrote: %s" % (self.client_address[0], line.rstrip())
            self.wfile.write(line)
        print "%s disconnected" % self.client_address[0]

# Create the server
server = EchoServer((HOST, PORT), EchoRequestHandler)

# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
print "server listening on %s:%s" % server.server_address
server.serve_forever()

Works with: Python version 3.5 or above
#!/usr/bin/env python
# $ printf 'echo\r\n' | nc localhost 12321
# echo
import asyncio
import logging
import os

logger = logging.getLogger('echoserver')

async def echo_handler(reader, writer):
  address = writer.get_extra_info('peername')
  logger.debug('accept: %s', address)
  message = await reader.readline()
  writer.write(message)
  await writer.drain()
  writer.close()

if __name__ == '__main__':
  logging.basicConfig()
  logger.setLevel(logging.DEBUG)
  loop = asyncio.get_event_loop()
  factory = asyncio.start_server(
    echo_handler,
    os.environ.get('HOST'),
    os.environ.get('PORT', 12321)
  )
  server = loop.run_until_complete(factory)
  try:
    loop.run_forever()
  except KeyboardInterrupt:
    pass
  server.close()
  loop.run_until_complete(server.wait_closed())
  loop.close()

Works with: Python version 2 and 3

    #!usr/bin/env python
    import socket
    import threading

    HOST = 'localhost'
    PORT = 12321
    SOCKET_TIMEOUT = 30

    # This function handles reading data sent by a client, echoing it back
    # and closing the connection in case of timeout (30s) or "quit" command
    # This function is meant to be started in a separate thread
    # (one thread per client)
    def handle_echo(client_connection, client_address):
        client_connection.settimeout(SOCKET_TIMEOUT)
        try:
            while True:
                data = client_connection.recv(1024)
                # Close connection if "quit" received from client
                if data == b'quit\r\n' or data == b'quit\n':
                    print('{} disconnected'.format(client_address))
                    client_connection.shutdown(1)
                    client_connection.close()
                    break
                # Echo back to client
                elif data:
                    print('FROM {} : {}'.format(client_address,data))
                    client_connection.send(data)
        # Timeout and close connection after 30s of inactivity
        except socket.timeout:
            print('{} timed out'.format(client_address))
            client_connection.shutdown(1)
            client_connection.close()

    # This function opens a socket and listens on specified port. As soon as a
    # connection is received, it is transfered to another socket so that the main
    # socket is not blocked and can accept new clients.
    def listen(host, port):
        # Create the main socket (IPv4, TCP)
        connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        connection.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        connection.bind((host, port))
        # Listen for clients (max 10 clients in waiting)
        connection.listen(10)
        # Every time a client connects, allow a dedicated socket and a dedicated
        # thread to handle communication with that client without blocking others.
        # Once the new thread has taken over, wait for the next client.
        while True:
            current_connection, client_address = connection.accept()
            print('{} connected'.format(client_address))
            handler_thread = threading.Thread( \
                target = handle_echo, \
                args = (current_connection,client_address) \
            )
            # daemon makes sure all threads are killed if the main server process
            # gets killed
            handler_thread.daemon = True
            handler_thread.start()

    if __name__ == "__main__":
        try:
            listen(HOST, PORT)
        except KeyboardInterrupt:
            print('exiting')
            pass

The code implements an echo server that listens on TCP port 12321. It accepts and handles multiple simultaneous connections from localhost only, echoing back complete lines to the clients. It uses low-level socket and threading modules, and can handle more than a single line per connection. It also supports timing out inactive clients and logs connection information to standard output. The server continues to respond to other clients even if one client sends a partial line or stops reading responses.


Python: Simple int/float[edit]
def is_numeric(s):
    try:
        float(s)
        return True
    except (ValueError, TypeError):
        return False

is_numeric('123.0')

'123'.isdigit()
Python: Most numeric literals[edit]

def is_numeric(literal):
    """Return whether a literal can be parsed as a numeric value"""
    castings = [int, float, complex,
        lambda s: int(s,2),  #binary
        lambda s: int(s,8),  #octal
        lambda s: int(s,16)] #hex
    for cast in castings:
        try:
            cast(literal)
            return True
        except ValueError:
            pass
    return False

def numeric(literal):
    """Return value of numeric literal or None if can't parse a value"""
    castings = [int, float, complex,
        lambda s: int(s,2),  #binary
        lambda s: int(s,8),  #octal
        lambda s: int(s,16)] #hex
    for cast in castings:
        try:
            return cast(literal)
        except ValueError:
            pass
    return None

tests = [
    '0', '0.', '00', '123', '0123', '+123', '-123', '-123.', '-123e-4', '-.8E-04',
    '0.123', '(5)', '-123+4.5j', '0b0101', ' +0B101 ', '0o123', '-0xABC', '0x1a1',
    '12.5%', '1/2', '½', '3¼', 'π', 'Ⅻ', '1,000,000', '1 000', '- 001.20e+02',
    'NaN', 'inf', '-Infinity']

for s in tests:
    print("%14s -> %-14s %-20s is_numeric: %-5s  str.isnumeric: %s" % (
        '"'+s+'"', numeric(s), type(numeric(s)), is_numeric(s), s.isnumeric() ))

"Create a function to check if a given string represents a numeric value, including floating point, negative numbers, and positive integers, as well as complex, hex, binary, and octal numeric literals. The function returns a boolean value and also demonstrates the use of the standard method str.isnumeric()."


send a GET request to the URL "https://www.w3.org/" without authentication, check the host certificate for validity, and print the response to the console using Python's urllib.request library with SSL support.


def clip(subjectPolygon, clipPolygon):
   def inside(p):
      return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])

   def computeIntersection():
      dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ]
      dp = [ s[0] - e[0], s[1] - e[1] ]
      n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]
      n2 = s[0] * e[1] - s[1] * e[0]
      n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])
      return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3]

   outputList = subjectPolygon
   cp1 = clipPolygon[-1]

   for clipVertex in clipPolygon:
      cp2 = clipVertex
      inputList = outputList
      outputList = []
      s = inputList[-1]

      for subjectVertex in inputList:
         e = subjectVertex
         if inside(e):
            if not inside(s):
               outputList.append(computeIntersection())
            outputList.append(e)
         elif inside(s):
            outputList.append(computeIntersection())
         s = e
      cp1 = cp2
   return(outputList)

implement the Sutherland-Hodgman polygon clipping algorithm. The code takes a closed polygon and a rectangle as inputs, clips the polygon by the rectangle, and outputs the sequence of points that define the resulting clipped polygon. For extra credit, the code also displays all three polygons on a graphical surface, using different colors for each polygon and filling the resulting polygon. The orientation of the display can be either north-west or south-west.


def mc_rank(iterable, start=1):
    """Modified competition ranking"""
    lastresult, fifo = None, []
    for n, item in enumerate(iterable, start-1):
        if item[0] == lastresult:
            fifo += [item]
        else:
            while fifo:
                yield n, fifo.pop(0)
            lastresult, fifo = item[0], fifo + [item]
    while fifo:
        yield n+1, fifo.pop(0)

def sc_rank(iterable, start=1):
    """Standard competition ranking"""
    lastresult, lastrank = None, None
    for n, item in enumerate(iterable, start):
        if item[0] == lastresult:
            yield lastrank, item
        else:
            yield n, item
            lastresult, lastrank = item[0], n

def d_rank(iterable, start=1):
    """Dense ranking"""
    lastresult, lastrank = None, start - 1,
    for item in iterable:
        if item[0] == lastresult:
            yield lastrank, item
        else:
            lastresult, lastrank = item[0], lastrank + 1
            yield lastrank, item

def o_rank(iterable, start=1):
    """Ordinal  ranking"""
    yield from enumerate(iterable, start)

def f_rank(iterable, start=1):
    """Fractional ranking"""
    last, fifo = None, []
    for n, item in enumerate(iterable, start):
        if item[0] != last:
            if fifo:
                mean = sum(f[0] for f in fifo) / len(fifo)
                while fifo:
                    yield mean, fifo.pop(0)[1]
        last = item[0]
        fifo.append((n, item))
    if fifo:
        mean = sum(f[0] for f in fifo) / len(fifo)
        while fifo:
            yield mean, fifo.pop(0)[1]

if __name__ == '__main__':
    scores = [(44, 'Solomon'),
              (42, 'Jason'),
              (42, 'Errol'),
              (41, 'Garry'),
              (41, 'Bernard'),
              (41, 'Barry'),
              (39, 'Stephen')]

    print('\nScores to be ranked (best first):')
    for s in scores:
        print('        %2i %s' % (s ))
    for ranker in [sc_rank, mc_rank, d_rank, o_rank, f_rank]:
        print('\n%s:' % ranker.__doc__)
        for rank, score in ranker(scores):
            print('  %3g, %r' % (rank, score))

"Implement functions for five different ranking methods: Standard, Modified, Dense, Ordinal, and Fractional. Each function takes an ordered list of competition scores and applies the respective ranking method. The Standard method shares the first ordinal number for ties, the Modified method shares the last ordinal number for ties, the Dense method shares the next available integer for ties, the Ordinal method assigns the next available integer without special treatment for ties, and the Fractional method shares the mean of the ordinal numbers for ties."


Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> from math import degrees, radians, sin, cos, tan, asin, acos, atan, pi
>>> rad, deg = pi/4, 45.0
>>> print("Sine:", sin(rad), sin(radians(deg)))
Sine: 0.7071067811865475 0.7071067811865475
>>> print("Cosine:", cos(rad), cos(radians(deg)))
Cosine: 0.7071067811865476 0.7071067811865476
>>> print("Tangent:", tan(rad), tan(radians(deg)))
Tangent: 0.9999999999999999 0.9999999999999999
>>> arcsine = asin(sin(rad))
>>> print("Arcsine:", arcsine, degrees(arcsine))
Arcsine: 0.7853981633974482 44.99999999999999
>>> arccosine = acos(cos(rad))
>>> print("Arccosine:", arccosine, degrees(arccosine))
Arccosine: 0.7853981633974483 45.0
>>> arctangent = atan(tan(rad))
>>> print("Arctangent:", arctangent, degrees(arctangent))
Arctangent: 0.7853981633974483 45.0
>>>

demonstrate the use of trigonometric functions such as sine, cosine, tangent, and their inverses in a specific programming language. The functions are applied to the same angle in both radians and degrees. For non-inverse functions, the same angle is used for each radian/degree pair. For inverse functions, the same number is converted to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities. Python's math module is used for these operations, which only accepts radians, necessitating conversion when using degrees.


from itertools import groupby
from collections import namedtuple

def anyvalidcomb(items, maxwt, val=0, wt=0):
    ' All combinations below the maxwt '
    if not items:
        yield [], val, wt
    else:
        this, *items = items            # car, cdr
        for n in range(this.number + 1):
            w = wt  + n * this.weight
            if w > maxwt:
                break
            v = val + n * this.value
            this_comb = [this] * n
            for comb, value, weight in anyvalidcomb(items, maxwt, v, w):
                yield this_comb + comb, value, weight

maxwt = 400
COMB, VAL, WT = range(3)
Item  = namedtuple('Items', 'name weight value number')
items = [ Item(*x) for x in
          (
            ("map", 9, 150, 1),
            ("compass", 13, 35, 1),
            ("water", 153, 200, 3),
            ("sandwich", 50, 60, 2),
            ("glucose", 15, 60, 2),
            ("tin", 68, 45, 3),
            ("banana", 27, 60, 3),
            ("apple", 39, 40, 3),
            ("cheese", 23, 30, 1),
            ("beer", 52, 10, 3),
            ("suntan cream", 11, 70, 1),
            ("camera", 32, 30, 1),
            ("t-shirt", 24, 15, 2),
            ("trousers", 48, 10, 2),
            ("umbrella", 73, 40, 1),
            ("waterproof trousers", 42, 70, 1),
            ("waterproof overclothes", 43, 75, 1),
            ("note-case", 22, 80, 1),
            ("sunglasses", 7, 20, 1),
            ("towel", 18, 12, 2),
            ("socks", 4, 50, 1),
            ("book", 30, 10, 2),
           ) ]

bagged = max( anyvalidcomb(items, maxwt), key=lambda c: (c[VAL], -c[WT])) # max val or min wt if values equal
print("Bagged the following %i items" % len(bagged[COMB]))
print('\n\t'.join('%i off: %s' % (len(list(grp)), item.name) for item, grp in groupby(sorted(bagged[COMB]))))
print("for a total value of %i and a total weight of %i" % bagged[1:])

The code determines the optimal combination of items that a tourist can carry in his knapsack, given a maximum weight limit of 4 kg. It takes into account the weight, value, and quantity of each item. The code uses a dynamic programming approach to solve the zero-one knapsack problem, ensuring the total weight does not exceed the limit and the total value is maximized.


import time

def counter():
    n = 0
    t1 = time.time()
    while True:
        try:
            time.sleep(0.5)
            n += 1
            print n
        except KeyboardInterrupt, e:
            print 'Program has run for %5.3f seconds.' % (time.time() - t1)
            break

counter()

import time

def intrptWIN():
   procDone = False
   n = 0

   while not procDone:
      try:
         time.sleep(0.5)
         n += 1
         print n
      except KeyboardInterrupt, e:
         procDone = True

t1 = time.time()
intrptWIN()
tdelt = time.time() - t1
print 'Program has run for %5.3f seconds.' % tdelt

import signal, time, threading
done = False
n = 0

def counter():
   global n, timer
   n += 1
   print n
   timer = threading.Timer(0.5, counter)
   timer.start()

def sigIntHandler(signum, frame):
   global done
   timer.cancel()
   done = True

def intrptUNIX():
   global timer
   signal.signal(signal.SIGINT, sigIntHandler)

   timer = threading.Timer(0.5, counter)
   timer.start()
   while not done:
      signal.pause()

t1 = time.time()
intrptUNIX()
tdelt = time.time() - t1
print 'Program has run for %5.3f seconds.' % tdelt

import time, signal

class WeAreDoneException(Exception):
    pass

def sigIntHandler(signum, frame):
    signal.signal(signal.SIGINT, signal.SIG_DFL) # resets to default handler
    raise WeAreDoneException

t1 = time.time()

try:
    signal.signal(signal.SIGINT, sigIntHandler)
    n = 0
    while True:
        time.sleep(0.5)
        n += 1
        print n
except WeAreDoneException:
    pass

tdelt = time.time() - t1
print 'Program has run for %5.3f seconds.' % tdelt

The code outputs an integer every half second and handles SIGINT or SIGQUIT signals. On receiving these signals, it stops outputting integers, displays the runtime duration in seconds, and then terminates. The code uses a signal handler and is compatible across all platforms, though the pause() mechanism is not supported on Windows.


Works with: Python version 2.3 through 3.4
next = str(int('123') + 1)

# Dropping or keeping any non-numerics in the string

# succString :: Bool -> String -> String
def succString(blnPruned):
    def go(x):
        try:
            return [str(1 + (float(x) if '.' in x else int(x)))]
        except ValueError:
            return [] if blnPruned else [x]
    return lambda s: ' '.join(concatMap(go)(s.split()))

# TEST ----------------------------------------------------
def main():
    print(
        '\n'.join(
            [succString(bln)(
                '41.0 pine martens in 1491 -1.5 mushrooms ≠ 136'
            ) for bln in [False, True]]
        )
    )

# GENERIC ---------------------------------------------------

# concatMap :: (a -> [b]) -> [a] -> [b]
def concatMap(f):
    return lambda xs: (
        [ys[0] for ys in [f(x) for x in xs] if ys]
    )

# MAIN ---
if __name__ == '__main__':
    main()

"Increment a numerical string, with options to handle both integer and floating point values, manage noisy or multi-number strings, and retain or remove non-numeric parts."


>>> import os
>>> os.path.commonpath(['/home/user1/tmp/coverage/test',
                        '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])
'/home/user1/tmp'

>>> import os
>>> os.path.commonprefix(['/home/user1/tmp/coverage/test',
                          '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])
'/home/user1/tmp/cove'

>>> def commonprefix(args, sep='/'):
	return os.path.commonprefix(args).rpartition(sep)[0]

>>> commonprefix(['/home/user1/tmp/coverage/test',
                  '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])
'/home/user1/tmp'

>>> paths = ['/home/user1/tmp/coverage/test', '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members']
>>> os.path.dirname(os.path.commonprefix(paths))
'/home/user1/tmp'

>>> from itertools import takewhile
>>> def allnamesequal(name):
	return all(n==name[0] for n in name[1:])

>>> def commonprefix(paths, sep='/'):
	bydirectorylevels = zip(*[p.split(sep) for p in paths])
	return sep.join(x[0] for x in takewhile(allnamesequal, bydirectorylevels))

>>> commonprefix(['/home/user1/tmp/coverage/test',
                  '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])
'/home/user1/tmp'
>>> # And also
>>> commonprefix(['/home/user1/tmp', '/home/user1/tmp/coverage/test',
                  '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])
'/home/user1/tmp'
>>>

Create a function to find the common directory path from a set of directory paths using a specified directory separator. The function should return a valid directory path, not just the longest common string. The function is tested with '/' as the directory separator and three specific strings as input paths. The Python os.path.commonpath function can be used for this task, but the os.path.commonprefix function is not recommended as it may return invalid directory paths.


implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm works by iterating from the last index to the first, selecting a random index within the range, and swapping the elements at these two indices. The algorithm modifies the input array in-place, but can be adjusted to return a new array or iterate from left to right if necessary. The key distinction from the Knuth shuffle is the range from which the random index is selected.


Works with: Python version 2.4 and 2.5
from SOAPpy import WSDL
proxy = WSDL.Proxy("http://example.com/soap/wsdl")
result = proxy.soapFunc("hello")
result = proxy.anotherSoapFunc(34234)

implement a SOAP client that accesses and calls the functions soapFunc() and anotherSoapFunc() from http://example.com/soap/wsdl using the SOAPpy module. Please note, the task details may be subject to change pending further clarification.


The code calculates the median value of a vector of floating-point numbers. It handles even number of elements by returning the average of the two middle values. The median is found using the selection algorithm for optimal time complexity. The code also includes tasks for calculating various statistical measures like mean, mode, and standard deviation. It also calculates moving (sliding window and cumulative) averages and different types of means such as arithmetic, geometric, harmonic, quadratic, and circular.


Python2: Simple[edit]
for i in xrange(1, 101):
    if i % 15 == 0:
        print "FizzBuzz"
    elif i % 3 == 0:
        print "Fizz"
    elif i % 5 == 0:
        print "Buzz"
    else:
        print i
Python3: Simple[edit]
for i in range(1, 101):
    if i % 15 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)
Python: Simple - no duplication[edit]
for n in range(1,101):
    response = ''

    if not n%3:
        response += 'Fizz'
    if not n%5:
        response += 'Buzz'

    print(response or n)

for i in range(1,101): print("Fizz"*(i%3==0) + "Buzz"*(i%5==0) or i)

for i in range(100):print(i%3//2*'Fizz'+i%5//4*'Buzz'or i+1)

for n in range(1, 100):
    fb = ''.join([ denom[1] if n % denom[0] == 0 else '' for denom in [(3,'fizz'),(5,'buzz')] ])
    print fb if fb else n

print (', '.join([(x%3<1)*'Fizz'+(x%5<1)*'Buzz' or str(x) for x in range(1,101)]))
Python: List Comprehension (Python 3)[edit]
[print("FizzBuzz") if i % 15 == 0 else print("Fizz") if i % 3 == 0 else print("Buzz") if i % 5 == 0 else print(i) for i in range(1,101)]
Python: Lazily[edit]

from itertools import cycle, izip, count, islice

fizzes = cycle([""] * 2 + ["Fizz"])
buzzes = cycle([""] * 4 + ["Buzz"])
both = (f + b for f, b in izip(fizzes, buzzes))

# if the string is "", yield the number
# otherwise yield the string
fizzbuzz = (word or n for word, n in izip(both, count(1)))

# print the first 100
for i in islice(fizzbuzz, 100):
    print i

Works with: Python version 3.7
'''Fizz buzz'''

from itertools import count, cycle, islice

# fizzBuzz :: () -> Generator [String]
def fizzBuzz():
    '''A non-finite stream of fizzbuzz terms.
    '''
    return map(
        lambda f, b, n: (f + b) or str(n),
        cycle([''] * 2 + ['Fizz']),
        cycle([''] * 4 + ['Buzz']),
        count(1)
    )

# ------------------------- TEST -------------------------
def main():
    '''Display of first 100 terms of the fizzbuzz series.
    '''
    print(
        '\n'.join(
            list(islice(
                fizzBuzz(),
                100
            ))
        )
    )

if __name__ == '__main__':
    main()
Python3.8: With walrus operator[edit]
print(*map(lambda n: 'Fizzbuzz '[(i):i+13] if (i := n**4%-15) > -14 else n, range(1,100)))
Python: Math tricks[edit]

def numsum(n):
	''' The recursive sum of all digits in a number
        unit a single character is obtained'''
	res = sum([int(i) for i in str(n)])
	if res < 10: return res
	else : return numsum(res)

for n in range(1,101):
	response = 'Fizz'*(numsum(n) in [3,6,9]) + \
                   'Buzz'*(str(n)[-1] in ['5','0'])\
	            or n
	print(response)
Python3: Super concise: 1 line[edit]
print(*((lambda x=x: ''.join(chr(c) for c in (102, 105)) + (2 * chr(122)) + ''.join(chr(c) for c in (98, 117)) + (2 * chr(122)) + '\n' if x % (30 >> 1) == 0 else ''.join(chr(c) for c in (102, 105)) + (2 * chr(122)) + '\n' if x % (6 >> 1) == 0 else ''.join(chr(c) for c in (98, 117)) + (2 * chr(122)) + '\n' if x % (10 >> 1) == 0 else str(x) + '\n')() for x in range(1, 101)))

print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'. This is a solution to the FizzBuzz problem, demonstrating basic programming comprehension. The solution can be implemented using string concatenation, list comprehensions, generator expressions, or Python 3 libraries. The code also utilizes the fact that numbers ending in 5 or 0 are divisible by 5, and numbers whose digits sum to 3, 6, or 9 are divisible by 3.


# Python 3.0+ and 2.5+
try:
    from functools import reduce
except:
    pass

def mandelbrot(a):
    return reduce(lambda z, _: z * z + a, range(50), 0)

def step(start, step, iterations):
    return (start + (i * step) for i in range(iterations))

rows = (("*" if abs(mandelbrot(complex(x, y))) < 2 else " "
        for x in step(-2.0, .0315, 80))
        for y in step(1, -.05, 41))

print("\n".join("".join(row) for row in rows))

import math

def mandelbrot(z , c , n=40):
    if abs(z) > 1000:
        return float("nan")
    elif n > 0:
        return mandelbrot(z ** 2 + c, c, n - 1)
    else:
        return z ** 2 + c

print("\n".join(["".join(["#" if not math.isnan(mandelbrot(0, x + 1j * y).real) else " "
                 for x in [a * 0.02 for a in range(-80, 30)]])
                 for y in [a * 0.05 for a in range(-20, 20)]])
     )

Library: matplotlib
Library: NumPy
from pylab import *
from numpy import NaN

def m(a):
	z = 0
	for n in range(1, 100):
		z = z**2 + a
		if abs(z) > 2:
			return n
	return NaN

X = arange(-2, .5, .002)
Y = arange(-1,  1, .002)
Z = zeros((len(Y), len(X)))

for iy, y in enumerate(Y):
	print (iy, "of", len(Y))
	for ix, x in enumerate(X):
		Z[iy,ix] = m(x + 1j * y)

imshow(Z, cmap = plt.cm.prism, interpolation = 'none', extent = (X.min(), X.max(), Y.min(), Y.max()))
xlabel("Re(c)")
ylabel("Im(c)")
savefig("mandelbrot_python.svg")
show()

import matplotlib.pyplot as plt
import numpy as np

npts = 300
max_iter = 100

X = np.linspace(-2, 1, 2 * npts)
Y = np.linspace(-1, 1, npts)

#broadcast X to a square array
C = X[:, None] + 1J * Y
#initial value is always zero
Z = np.zeros_like(C)

exit_times = max_iter * np.ones(C.shape, np.int32)
mask = exit_times > 0

for k in range(max_iter):
    Z[mask] = Z[mask] * Z[mask] + C[mask]
    mask, old_mask = abs(Z) < 2, mask
    #use XOR to detect the area which has changed
    exit_times[mask ^ old_mask] = k

plt.imshow(exit_times.T,
           cmap=plt.cm.prism,
           extent=(X.min(), X.max(), Y.min(), Y.max()))
plt.show()
Normal Map Effect, Mercator Projection and Deep Zoom Images[edit]

import numpy as np
import matplotlib.pyplot as plt

d, h = 800, 500  # pixel density (= image width) and image height
n, r = 200, 500  # number of iterations and escape radius (r > 2)

x = np.linspace(0, 2, num=d+1)
y = np.linspace(0, 2 * h / d, num=h+1)

A, B = np.meshgrid(x - 1, y - h / d)
C = 2.0 * (A + B * 1j) - 0.5

Z, dZ = np.zeros_like(C), np.zeros_like(C)
D, S, T = np.zeros(C.shape), np.zeros(C.shape), np.zeros(C.shape)

for k in range(n):
    M = abs(Z) < r
    S[M], T[M] = S[M] + np.exp(- abs(Z[M])), T[M] + 1
    Z[M], dZ[M] = Z[M] ** 2 + C[M], 2 * Z[M] * dZ[M] + 1

plt.imshow(S ** 0.1, cmap=plt.cm.twilight_shifted, origin="lower")
plt.savefig("Mandelbrot_set_1.png", dpi=200)

N = abs(Z) >= r  # normalized iteration count
T[N] = T[N] - np.log2(np.log(np.abs(Z[N])) / np.log(r))

plt.imshow(T ** 0.1, cmap=plt.cm.twilight_shifted, origin="lower")
plt.savefig("Mandelbrot_set_2.png", dpi=200)

N = abs(Z) > 2  # exterior distance estimation
D[N] = np.log(abs(Z[N])) * abs(Z[N]) / abs(dZ[N])

plt.imshow(D ** 0.1, cmap=plt.cm.twilight_shifted, origin="lower")
plt.savefig("Mandelbrot_set_3.png", dpi=200)

N, thickness = D > 0, 0.01  # boundary detection
D[N] = np.maximum(1 - D[N] / thickness, 0)

plt.imshow(D ** 2.0, cmap=plt.cm.binary, origin="lower")
plt.savefig("Mandelbrot_set_4.png", dpi=200)

import numpy as np
import matplotlib.pyplot as plt

d, h = 800, 500  # pixel density (= image width) and image height
n, r = 200, 500  # number of iterations and escape radius (r > 2)

direction, height = 45, 1.5  # direction and height of the incoming light
stripes, damping = 4.0, 2.0  # stripe density and damping parameter

x = np.linspace(0, 2, num=d+1)
y = np.linspace(0, 2 * h / d, num=h+1)

A, B = np.meshgrid(x - 1, y - h / d)
C = (2.0 + 1.0j) * (A + B * 1j) - 0.5

Z, dZ, ddZ = np.zeros_like(C), np.zeros_like(C), np.zeros_like(C)
D, S, T = np.zeros(C.shape), np.zeros(C.shape), np.zeros(C.shape)

for k in range(n):
    M = abs(Z) < r
    S[M], T[M] = S[M] + np.sin(stripes * np.angle(Z[M])), T[M] + 1
    Z[M], dZ[M], ddZ[M] = Z[M] ** 2 + C[M], 2 * Z[M] * dZ[M] + 1, 2 * (dZ[M] ** 2 + Z[M] * ddZ[M])

N = abs(Z) >= r  # basic normal map effect and stripe average coloring (potential function)
P, Q = S[N] / T[N], (S[N] + np.sin(stripes * np.angle(Z[N]))) / (T[N] + 1)
U, V = Z[N] / dZ[N], 1 + (np.log2(np.log(np.abs(Z[N])) / np.log(r)) * (P - Q) + Q) / damping
U, v = U / abs(U), np.exp(direction / 180 * np.pi * 1j)  # unit normal vectors and light
D[N] = np.maximum((U.real * v.real + U.imag * v.imag + V * height) / (1 + height), 0)

plt.imshow(D ** 1.0, cmap=plt.cm.bone, origin="lower")
plt.savefig("Mandelbrot_normal_map_1.png", dpi=200)

N = abs(Z) > 2  # advanced normal map effect using higher derivatives (distance estimation)
U = Z[N] * dZ[N] * ((1 + np.log(abs(Z[N]))) * np.conj(dZ[N] ** 2) - np.log(abs(Z[N])) * np.conj(Z[N] * ddZ[N]))
U, v = U / abs(U), np.exp(direction / 180 * np.pi * 1j)  # unit normal vectors and light
D[N] = np.maximum((U.real * v.real + U.imag * v.imag + height) / (1 + height), 0)

plt.imshow(D ** 1.0, cmap=plt.cm.afmhot, origin="lower")
plt.savefig("Mandelbrot_normal_map_2.png", dpi=200)

import numpy as np
import matplotlib.pyplot as plt

d, h = 200, 1200  # pixel density (= image width) and image height
n, r = 8000, 10000  # number of iterations and escape radius (r > 2)

a = -.743643887037158704752191506114774  # https://mathr.co.uk/web/m-location-analysis.html
b = 0.131825904205311970493132056385139  # try: a, b, n = -1.748764520194788535, 3e-13, 800

x = np.linspace(0, 2, num=d+1)
y = np.linspace(0, 2 * h / d, num=h+1)

A, B = np.meshgrid(x * np.pi, y * np.pi)
C = 8.0 * np.exp((A + B * 1j) * 1j) + (a + b * 1j)

Z, dZ = np.zeros_like(C), np.zeros_like(C)
D = np.zeros(C.shape)

for k in range(n):
    M = Z.real ** 2 + Z.imag ** 2 < r ** 2
    Z[M], dZ[M] = Z[M] ** 2 + C[M], 2 * Z[M] * dZ[M] + 1

N = abs(Z) > 2  # exterior distance estimation
D[N] = np.log(abs(Z[N])) * abs(Z[N]) / abs(dZ[N])

plt.imshow(D.T ** 0.05, cmap=plt.cm.nipy_spectral, origin="lower")
plt.savefig("Mercator_Mandelbrot_map.png", dpi=200)

X, Y = C.real, C.imag  # zoom images (adjust circle size 100 and zoom level 20 as needed)
R, c, z = 100 * (2 / d) * np.pi * np.exp(- B), min(d, h) + 1, max(0, h - d) // 20

fig, ax = plt.subplots(2, 2, figsize=(12, 12))
ax[0,0].scatter(X[1*z:1*z+c,0:d], Y[1*z:1*z+c,0:d], s=R[0:c,0:d]**2, c=D[1*z:1*z+c,0:d]**.5, cmap=plt.cm.nipy_spectral)
ax[0,1].scatter(X[2*z:2*z+c,0:d], Y[2*z:2*z+c,0:d], s=R[0:c,0:d]**2, c=D[2*z:2*z+c,0:d]**.4, cmap=plt.cm.nipy_spectral)
ax[1,0].scatter(X[3*z:3*z+c,0:d], Y[3*z:3*z+c,0:d], s=R[0:c,0:d]**2, c=D[3*z:3*z+c,0:d]**.3, cmap=plt.cm.nipy_spectral)
ax[1,1].scatter(X[4*z:4*z+c,0:d], Y[4*z:4*z+c,0:d], s=R[0:c,0:d]**2, c=D[4*z:4*z+c,0:d]**.2, cmap=plt.cm.nipy_spectral)
plt.savefig("Mercator_Mandelbrot_zoom.png", dpi=100)

import numpy as np
import matplotlib.pyplot as plt

import decimal as dc  # decimal floating point arithmetic with arbitrary precision
dc.getcontext().prec = 80  # set precision to 80 digits (about 256 bits)

d, h = 50, 1000  # pixel density (= image width) and image height
n, r = 80000, 100000  # number of iterations and escape radius (r > 2)

a = dc.Decimal("-1.256827152259138864846434197797294538253477389787308085590211144291")
b = dc.Decimal(".37933802890364143684096784819544060002129071484943239316486643285025")

S = np.zeros(n+1, dtype=np.complex128)
u, v = dc.Decimal(0), dc.Decimal(0)

for k in range(n+1):
    S[k] = float(u) + float(v) * 1j
    if u ** 2 + v ** 2 < r ** 2:
        u, v = u ** 2 - v ** 2 + a, 2 * u * v + b
    else:
        print("The reference sequence diverges within %s iterations." % k)
        break

x = np.linspace(0, 2, num=d+1)
y = np.linspace(0, 2 * h / d, num=h+1)

A, B = np.meshgrid(x * np.pi, y * np.pi)
C = 8.0 * np.exp((A + B * 1j) * 1j)

E, Z, dZ = np.zeros_like(C), np.zeros_like(C), np.zeros_like(C)
D, I, J = np.zeros(C.shape), np.zeros(C.shape, dtype=np.int64), np.zeros(C.shape, dtype=np.int64)

for k in range(n):
    Z2 = Z.real ** 2 + Z.imag ** 2
    M, R = Z2 < r ** 2, Z2 < E.real ** 2 + E.imag ** 2
    E[R], I[R] = Z[R], J[R]  # rebase when z is closer to zero
    E[M], I[M] = (2 * S[I[M]] + E[M]) * E[M] + C[M], I[M] + 1
    Z[M], dZ[M] = S[I[M]] + E[M], 2 * Z[M] * dZ[M] + 1

N = abs(Z) > 2  # exterior distance estimation
D[N] = np.log(abs(Z[N])) * abs(Z[N]) / abs(dZ[N])

plt.imshow(D.T ** 0.015, cmap=plt.cm.nipy_spectral, origin="lower")
plt.savefig("Mercator_Mandelbrot_deep_map.png", dpi=200)

Python - "One liner"[edit]
print(
'\n'.join(
    ''.join(
        ' *'[(z:=0, c:=x/50+y/50j, [z:=z*z+c for _ in range(99)], abs(z))[-1]<2]
        for x in range(-100,25)
    )
    for y in range(-50,50)
))
Python - "Functional"[edit]

from functools import reduce

def mandelbrot(x, y, c): return ' *'[abs(reduce(lambda z, _: z*z + c, range(99), 0)) < 2]

print('\n'.join(''.join(mandelbrot(x, y, x/50 + y/50j) for x in range(-100, 25)) for y in range(-50, 50)))

The code generates and visualizes the Mandelbrot set using various algorithms and functions. It employs different coloring algorithms for dynamical systems in the complex plane, including Normal Maps and Stripe Average Coloring. It also creates Mercator maps of the Mandelbrot set and zoom images with maximum magnification. The code uses perturbation theory for deep zoom images and rebasing to reduce glitches.


Works with: Python version 2.5
numbers = [1, 2, 3]
total = sum(numbers)

product = 1
for i in numbers:
    product *= i

Works with: Python version 2.5
from operator import mul, add
sum = reduce(add, numbers) # note: this version doesn't work with empty lists
sum = reduce(add, numbers, 0)
product = reduce(mul, numbers) # note: this version doesn't work with empty lists
product = reduce(mul, numbers, 1)
Library: NumPy
from numpy import r_
numbers = r_[1:4]
total = numbers.sum()
product = numbers.prod()

Works with: Python version 2.6, 3.x
import math
total = math.fsum(floats)

calculate the sum and product of an array of integers. For summing floats in Python 2.6+, math.fsum() is used to prevent precision loss.


import calendar
calendar.isleap(year)

def is_leap_year(year):
    return not year % (4 if year % 100 else 400)

import datetime

def is_leap_year(year):
    try:
        datetime.date(year, 2, 29)
    except ValueError:
        return False
    return True

"Determines if a given year is a leap year in the Gregorian calendar."


"""One-time pad using an XOR cipher. Requires Python >=3.6."""

import argparse
import itertools
import pathlib
import re
import secrets
import sys

# One-time pad file signature.
MAGIC = "#one-time pad"

def make_keys(n, size):
    """Generate ``n`` secure, random keys of ``size`` bytes."""
    # We're generating and storing keys in their hexadecimal form to make
    # one-time pad files a little more human readable and to ensure a key
    # can not start with a hyphen.
    return (secrets.token_hex(size) for _ in range(n))

def make_pad(name, pad_size, key_size):
    """Create a new one-time pad identified by the given name.

    Args:
        name (str): Unique one-time pad identifier.
        pad_size (int): The number of keys (or pages) in the pad.
        key_size (int): The number of bytes per key.
    Returns:
        The new one-time pad as a string.
    """
    pad = [
        MAGIC,
        f"#name={name}",
        f"#size={pad_size}",
        *make_keys(pad_size, key_size),
    ]

    return "\n".join(pad)

def xor(message, key):
    """Return ``message`` XOR-ed with ``key``.

    Args:
        message (bytes): Plaintext or cyphertext to be encrypted or decrypted.
        key (bytes): Encryption and decryption key.
    Returns:
        Plaintext or cyphertext as a byte string.
    """
    return bytes(mc ^ kc for mc, kc in zip(message, itertools.cycle(key)))

def use_key(pad):
    """Use the next available key from the given one-time pad.

    Args:
        pad (str): A one-time pad.
    Returns:
        (str, str) A two-tuple of updated pad and key.
    """
    match = re.search(r"^[a-f0-9]+$", pad, re.MULTILINE)
    if not match:
        error("pad is all used up")

    key = match.group()
    pos = match.start()

    return (f"{pad[:pos]}-{pad[pos:]}", key)

def log(msg):
    """Log a message."""
    sys.stderr.write(msg)
    sys.stderr.write("\n")

def error(msg):
    """Exit with an error message."""
    sys.stderr.write(msg)
    sys.stderr.write("\n")
    sys.exit(1)

def write_pad(path, pad_size, key_size):
    """Write a new one-time pad to the given path.

    Args:
        path (pathlib.Path): Path to write one-time pad to.
        length (int): Number of keys in the pad.
    """
    if path.exists():
        error(f"pad '{path}' already exists")

    with path.open("w") as fd:
        fd.write(make_pad(path.name, pad_size, key_size))

    log(f"New one-time pad written to {path}")

def main(pad, message, outfile):
    """Encrypt or decrypt ``message`` using the given pad.

    Args:
        pad (pathlib.Path): Path to one-time pad.
        message (bytes): Plaintext or ciphertext message to encrypt or decrypt.
        outfile: File-like object to write to.
    """
    if not pad.exists():
        error(f"no such pad '{pad}'")

    with pad.open("r") as fd:
        if fd.readline().strip() != MAGIC:
            error(f"file '{pad}' does not look like a one-time pad")

    # Rewrites the entire one-time pad every time
    with pad.open("r+") as fd:
        updated, key = use_key(fd.read())

        fd.seek(0)
        fd.write(updated)

    outfile.write(xor(message, bytes.fromhex(key)))

if __name__ == "__main__":
    # Command line interface
    parser = argparse.ArgumentParser(description="One-time pad.")

    parser.add_argument(
        "pad",
        help=(
            "Path to one-time pad. If neither --encrypt or --decrypt "
            "are given, will create a new pad."
        ),
    )

    parser.add_argument(
        "--length",
        type=int,
        default=10,
        help="Pad size. Ignored if --encrypt or --decrypt are given. Defaults to 10.",
    )

    parser.add_argument(
        "--key-size",
        type=int,
        default=64,
        help="Key size in bytes. Ignored if --encrypt or --decrypt are given. Defaults to 64.",
    )

    parser.add_argument(
        "-o",
        "--outfile",
        type=argparse.FileType("wb"),
        default=sys.stdout.buffer,
        help=(
            "Write encoded/decoded message to a file. Ignored if --encrypt or "
            "--decrypt is not given. Defaults to stdout."
        ),
    )

    group = parser.add_mutually_exclusive_group()

    group.add_argument(
        "--encrypt",
        metavar="FILE",
        type=argparse.FileType("rb"),
        help="Encrypt FILE using the next available key from pad.",
    )
    group.add_argument(
        "--decrypt",
        metavar="FILE",
        type=argparse.FileType("rb"),
        help="Decrypt FILE using the next available key from pad.",
    )

    args = parser.parse_args()

    if args.encrypt:
        message = args.encrypt.read()
    elif args.decrypt:
        message = args.decrypt.read()
    else:
        message = None

    # Sometimes necessary if message came from stdin
    if isinstance(message, str):
        message = message.encode()

    pad = pathlib.Path(args.pad).with_suffix(".1tp")

    if message:
        main(pad, message, args.outfile)
    else:
        write_pad(pad, args.length, args.key_size)

The code implements a One-time pad for encrypting and decrypting messages using only letters. It generates a One-time pad data based on user-specified filename and length, using true random numbers. The encryption/decryption operation is similar to Rot-13 and reuses much of the Vigenère cipher. The code also optionally manages One-time pads, including listing, marking as used, and deleting. It supports the management of pad-files with a ".1tp" extension, and handles metadata and used status. The code also provides a command-line interface for creating a new one-time pad, distributing it, encrypting a message, and decrypting a message using the shared one-time pad.


Works with: Python version 3.2

import math

rotate_amounts = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
                  5,  9, 14, 20, 5,  9, 14, 20, 5,  9, 14, 20, 5,  9, 14, 20,
                  4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
                  6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]

constants = [int(abs(math.sin(i+1)) * 2**32) & 0xFFFFFFFF for i in range(64)]

init_values = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]

functions = 16*[lambda b, c, d: (b & c) | (~b & d)] + \
            16*[lambda b, c, d: (d & b) | (~d & c)] + \
            16*[lambda b, c, d: b ^ c ^ d] + \
            16*[lambda b, c, d: c ^ (b | ~d)]

index_functions = 16*[lambda i: i] + \
                  16*[lambda i: (5*i + 1)%16] + \
                  16*[lambda i: (3*i + 5)%16] + \
                  16*[lambda i: (7*i)%16]

def left_rotate(x, amount):
    x &= 0xFFFFFFFF
    return ((x<<amount) | (x>>(32-amount))) & 0xFFFFFFFF

def md5(message):

    message = bytearray(message) #copy our input into a mutable buffer
    orig_len_in_bits = (8 * len(message)) & 0xffffffffffffffff
    message.append(0x80)
    while len(message)%64 != 56:
        message.append(0)
    message += orig_len_in_bits.to_bytes(8, byteorder='little')

    hash_pieces = init_values[:]

    for chunk_ofst in range(0, len(message), 64):
        a, b, c, d = hash_pieces
        chunk = message[chunk_ofst:chunk_ofst+64]
        for i in range(64):
            f = functions[i](b, c, d)
            g = index_functions[i](i)
            to_rotate = a + f + constants[i] + int.from_bytes(chunk[4*g:4*g+4], byteorder='little')
            new_b = (b + left_rotate(to_rotate, rotate_amounts[i])) & 0xFFFFFFFF
            a, b, c, d = d, new_b, b, c
        for i, val in enumerate([a, b, c, d]):
            hash_pieces[i] += val
            hash_pieces[i] &= 0xFFFFFFFF

    return sum(x<<(32*i) for i, x in enumerate(hash_pieces))

def md5_to_hex(digest):
    raw = digest.to_bytes(16, byteorder='little')
    return '{:032x}'.format(int.from_bytes(raw, byteorder='big'))

if __name__=='__main__':
    demo = [b"", b"a", b"abc", b"message digest", b"abcdefghijklmnopqrstuvwxyz",
            b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
            b"12345678901234567890123456789012345678901234567890123456789012345678901234567890"]
    for message in demo:
        print(md5_to_hex(md5(message)),' <= "',message.decode('ascii'),'"', sep='')

The code works with whole bytes, arbitrary message length is not supported.
Instead of doing an if-else chain in the inner loop, we build a list of functions to use for each iteration. An if-else chain would probably be faster, but this shows off the language features better.
Python integers don't ever overflow (they are implemented internally as bignums), so the code actually has to emulate 32-bit overflow by masking manually where it matters. On the other hand, this allows us to return the digest as a regular 128-bit number instead of a bytes object.
The code makes heavy use of int.from_bytes() and int.to_bytes() to convert between bytes and integers. These methods were introduced in Python 3.2. In earlier versions, you needed to use more cumbersome ways to convert between the two types.
The multiple assignment feature allows us to easily decompose the four items in hash_pieces into individual variables, and to shuffle around the four helper variables at the end of every iteration without introducing a temporary variable.

implement the MD5 Message Digest Algorithm without using built-in or external hashing libraries. The implementation focuses on producing a correct message digest for an input string, and does not necessarily mimic all calling modes. It provides practical illustrations of bit manipulation, unsigned integers, and working with little-endian data. The code also includes handling of boundary conditions. The implementation is developed from the specification, reference implementation, or pseudo-code, or it could be a translation from another language. The implementation should not use built-in MD5 functions or library routines written in other languages.


Procedural[edit]
from itertools import permutations

def solve():
    c, p, f, s = "\\,Police,Fire,Sanitation".split(',')
    print(f"{c:>3}  {p:^6} {f:^4} {s:^10}")
    c = 1
    for p, f, s in permutations(range(1, 8), r=3):
        if p + s + f == 12 and p % 2 == 0:
            print(f"{c:>3}: {p:^6} {f:^4} {s:^10}")
            c += 1

if __name__ == '__main__':
    solve()

all possible combinations of department numbers for the police, sanitation, and fire departments where each department has a unique number between 1 and 7, the total sum of the numbers is 12, and the police department's number is even. The combinations are generated using a constraint solver.


Works with: Python version 2.3, 2.4, and 2.5

>>> src = "hello"
>>> a = src
>>> b = src[:]
>>> import copy
>>> c = copy.copy(src)
>>> d = copy.deepcopy(src)
>>> src is a is b is c is d
True

>>> a = 'hello'
>>> b = ''.join(a)
>>> a == b
True
>>> b is a  ### Might be True ... depends on "interning" implementation details!
False

"Implements a function to copy a string, considering the distinction between copying the contents of a string and making an additional reference to an existing string. It handles the immutability of strings and the potential object interning of Python. It also includes precautions for using the 'is' operator for object identity comparison."


Works with: Python version 3.0.Works with: Python version 2.6
def F(n): return 1 if n == 0 else n - M(F(n-1))
def M(n): return 0 if n == 0 else n - F(M(n-1))

print ([ F(n) for n in range(20) ])
print ([ M(n) for n in range(20) ])

implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. The functions use each other in their definitions and computations. The Female sequence starts with 1 and the Male sequence starts with 0. For any number n greater than 0, the Female sequence is computed as n minus the Male sequence at the index of the previous Female sequence, and the Male sequence is computed as n minus the Female sequence at the index of the previous Male sequence. The functions are defined in such a way that they can be used in languages that do not require pre-declaration of functions.


>>> import random
>>> random.choice(['foo', 'bar', 'baz'])
'baz'

demonstrate how to select a random element from a list.


#Python 2.X
import urllib
print urllib.unquote("http%3A%2F%2Ffoo%20bar%2F")
#Python 3.5+
from urllib.parse import unquote
print(unquote('http%3A%2F%2Ffoo%20bar%2F'))

provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like "http%3A%2F%2Ffoo%20bar%2F", "google.com/search?q=%60Abdu%27l-Bah%C3%A1", and "%25%32%35".


Python: Iterative[edit]
def binary_search(l, value):
    low = 0
    high = len(l)-1
    while low <= high:
        mid = (low+high)//2
        if l[mid] > value: high = mid-1
        elif l[mid] < value: low = mid+1
        else: return mid
    return -1

# findIndexBinary :: (a -> Ordering) -> [a] -> Maybe Int
def findIndexBinary(p):
    def isFound(bounds):
        (lo, hi) = bounds
        return lo > hi or 0 == hi

    def half(xs):
        def choice(lh):
            (lo, hi) = lh
            mid = (lo + hi) // 2
            cmpr = p(xs[mid])
            return (lo, mid - 1) if cmpr < 0 else (
                (1 + mid, hi) if cmpr > 0 else (
                    mid, 0
                )
            )
        return lambda bounds: choice(bounds)

    def go(xs):
        (lo, hi) = until(isFound)(
            half(xs)
        )((0, len(xs) - 1)) if xs else None
        return None if 0 != hi else lo

    return lambda xs: go(xs)

# COMPARISON CONSTRUCTORS ---------------------------------

# compare :: a -> a -> Ordering
def compare(a):
    '''Simple comparison of x and y -> LT|EQ|GT'''
    return lambda b: -1 if a < b else (1 if a > b else 0)

# byKV :: (a -> b) -> a -> a -> Ordering
def byKV(f):
    '''Property accessor function -> target value -> x -> LT|EQ|GT'''
    def go(v, x):
        fx = f(x)
        return -1 if v < fx else 1 if v > fx else 0
    return lambda v: lambda x: go(v, x)

# TESTS ---------------------------------------------------
def main():

    # BINARY SEARCH FOR WORD IN AZ-SORTED LIST

    mb1 = findIndexBinary(compare('iota'))(
        # Sorted AZ
        ['alpha', 'beta', 'delta', 'epsilon', 'eta', 'gamma', 'iota',
         'kappa', 'lambda', 'mu', 'theta', 'zeta']
    )

    print (
        'Not found' if None is mb1 else (
            'Word found at index ' + str(mb1)
        )
    )

    # BINARY SEARCH FOR WORD OF GIVEN LENGTH (IN WORD-LENGTH SORTED LIST)

    mb2 = findIndexBinary(byKV(len)(7))(
        # Sorted by rising length
        ['mu', 'eta', 'beta', 'iota', 'zeta', 'alpha', 'delta', 'gamma',
         'kappa', 'theta', 'lambda', 'epsilon']
    )

    print (
        'Not found' if None is mb2 else (
            'Word of given length found at index ' + str(mb2)
        )
    )

# GENERIC -------------------------------------------------

# until :: (a -> Bool) -> (a -> a) -> a -> a
def until(p):
    def go(f, x):
        v = x
        while not p(v):
            v = f(v)
        return v
    return lambda f: lambda x: go(f, x)

if __name__ == '__main__':
    main()

The code implements a binary search algorithm that searches for a specific number within a sorted integer array. The search can be either recursive or iterative. The code also handles multiple values equal to the given value, and indicates whether the element was found or not. It also provides the index of the found element. The code also includes versions that return the leftmost and rightmost insertion points for the given element. It also handles potential overflow bugs. The code can be generalized to use a custom comparator function for more complex searches.


import sys
program_name = sys.argv[0]
arguments = sys.argv[1:]
count = len(arguments)

The code retrieves and processes command-line arguments given to the program, including the program name. It uses the sys.argv list to access these arguments. The code also handles scenarios where the module is run directly by Python, ensuring all arguments are accessible. It provides the ability to modify the command-line arguments within the Python program, without affecting the arguments seen by other processes. Additionally, it utilizes the optparse module for advanced option parsing capabilities.