WeixiangYan/CodeTransOcean huggingface dataset:
Task: External sort







Python: 



import io

def sort_large_file(n: int, source: open, sink: open, file_opener = open)->None:

    

    
    mergers = []
    while True:
        text = list(source.read(n))
        if not len(text):
            break;
        text.sort()
        merge_me = file_opener()
        merge_me.write(''.join(text))
        mergers.append(merge_me)
        merge_me.seek(0)

    
    stack_tops = [f.read(1) for f in mergers]
    while stack_tops:
        c = min(stack_tops)
        sink.write(c)
        i = stack_tops.index(c)
        t = mergers[i].read(1)
        if t:
            stack_tops[i] = t
        else:
            del stack_tops[i]
            mergers[i].close()
            del mergers[i]  

def main():
    

    
    input_file_too_large_for_memory = io.StringIO('678925341')

    
    t = list(input_file_too_large_for_memory.read())
    t.sort()
    expect = ''.join(t)
    print('expect', expect)

    
    for memory_size in range(1,12):
        input_file_too_large_for_memory.seek(0)
        output_file_too_large_for_memory = io.StringIO()
        sort_large_file(memory_size, input_file_too_large_for_memory, output_file_too_large_for_memory, io.StringIO)
        output_file_too_large_for_memory.seek(0)
        assert(output_file_too_large_for_memory.read() == expect)
        print('memory size {} passed'.format(memory_size))

if __name__ == '__main__':
   example = main
   example()
Task: Penrose tiling







Python: def penrose(depth):
    print(	<g id="A{d+1}" transform="translate(100, 0) scale(0.6180339887498949)">
		<use href="
		<use href="
	</g>
	<g id="B{d+1}">
		<use href="
		<use href="
	</g>	<g id="G">
		<use href="
		<use href="
	</g>
  </defs>
  <g transform="scale(2, 2)">
	<use href="
	<use href="
	<use href="
	<use href="
	<use href="
  </g>
</svg>''')

penrose(6)
Task: Print itself







Python: import sys
with open(sys.argv[0],'r') as input:
    for row in input:
        print(row, end='')
Task: Count the coins_0-1







Python: from itertools import product, compress

fact = lambda n: n and n*fact(n - 1) or 1
combo_count = lambda total, coins, perm:\
                    sum(perm and fact(len(x)) or 1
                        for x in (list(compress(coins, c))
                                  for c in product(*([(0, 1)]*len(coins))))
                        if sum(x) == total)

cases = [(6,  [1, 2, 3, 4, 5]),
         (6,  [1, 1, 2, 3, 3, 4, 5]),
         (40, [1, 2, 3, 4, 5, 5, 5, 5, 15, 15, 10, 10, 10, 10, 25, 100])]

for perm in [False, True]:
    print(f'Order matters: {perm}')
    for s, c in cases:
        print(f'{combo_count(s, c, perm):7d} ways for {s:2d} total from coins {c}')
    print()
Task: Bifid cipher







Python: 
import math
import pprint
import string

from itertools import chain
from itertools import zip_longest

from typing import Dict
from typing import Iterable
from typing import Iterator
from typing import Tuple
from typing import TypeVar


T = TypeVar("T")


def group(it: Iterable[T], n: int) -> Iterator[Tuple[T, ...]]:
    
    return zip_longest(*[iter(it)] * n)


Square = Tuple[Tuple[str, ...], ...]


def polybius_square(alphabet: str) -> Square:
    
    return tuple(group(alphabet, math.ceil(math.sqrt(len(alphabet)))))


def polybius_map(square: Square) -> Dict[str, Tuple[int, int]]:
    
    return {
        square[i][j]: (i + 1, j + 1)
        for i in range(len(square))
        for j in range(len(square))
    }


def encrypt(message: str, square: Square) -> str:
    
    _map = polybius_map(square)
    return "".join(
        square[x - 1][y - 1]
        for x, y in group(
            chain.from_iterable(zip(*(_map[c] for c in message if c in _map))),
            2,
        )
    )


def decrypt(message: str, square: Square) -> str:
    
    _map = polybius_map(square)
    return "".join(
        square[x - 1][y - 1]
        for x, y in zip(
            *group(
                chain.from_iterable((_map[c] for c in message if c in _map)),
                len(message),
            )
        )
    )


def normalize(message: str) -> str:
    
    return message.upper().replace("J", "I")


TYPICAL_POLYBIUS_SQUARE = polybius_square(
    alphabet="".join(c for c in string.ascii_uppercase if c != "J")
)


EXAMPLE_POLYBIUS_SQUARE = polybius_square(
    alphabet="BGWKZQPNDSIOAXEFCLUMTHYVR",
)


def main() -> None:
    test_cases = [
        ("ATTACKATDAWN", TYPICAL_POLYBIUS_SQUARE),  
        ("FLEEATONCE", EXAMPLE_POLYBIUS_SQUARE),  
        ("FLEEATONCE", TYPICAL_POLYBIUS_SQUARE),  
        (
            normalize("The invasion will start on the first of January"),
            polybius_square(alphabet="PLAYFIREXMBCDGHKNOQSTUVWZ"),
        ),
        (
            "The invasion will start on the first of January".upper(),
            polybius_square(alphabet=string.ascii_uppercase + string.digits),
        ),
    ]

    for message, square in test_cases:
        pprint.pprint(square)
        print("Message  :", message)
        print("Encrypted:", encrypt(message, square))
        print("Decrypted:", decrypt(encrypt(message, square), square))
        print("")


if __name__ == "__main__":
    main()
Task: Marching squares







Python: from numpy import array, round
from skimage import measure

example = array([
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 1, 1, 0],
    [0, 0, 1, 1, 0],
    [0, 0, 0, 1, 0],
    [0, 0, 0, 0, 0]
])


contours = round(measure.find_contours(example, 0.1))[0]
print('[', ', '.join([str((p[1], 5 - p[0])) for p in contours]), ']')
Task: Babylonian spiral







Python: 

from itertools import accumulate
from math import isqrt, atan2, tau
from matplotlib.pyplot import axis, plot, show


square_cache = []

def babylonian_spiral(nsteps):
    
    if len(square_cache) <= nsteps:
        square_cache.extend([x * x for x in range(len(square_cache), nsteps)])
    xydeltas = [(0, 0), (0, 1)]
    δsquared = 1
    for _ in range(nsteps - 2):
        x, y = xydeltas[-1]
        θ = atan2(y, x)
        candidates = []
        while not candidates:
            δsquared += 1
            for i, a in enumerate(square_cache):
                if a > δsquared // 2:
                    break
                for j in range(isqrt(δsquared) + 1, 0, -1):
                    b = square_cache[j]
                    if a + b < δsquared:
                        break
                    if a + b == δsquared:
                        candidates.extend([(i, j), (-i, j), (i, -j), (-i, -j), (j, i), (-j, i),
                           (j, -i), (-j, -i)])

        p = min(candidates, key=lambda d: (θ - atan2(d[1], d[0])) % tau)
        xydeltas.append(p)

    return list(accumulate(xydeltas, lambda a, b: (a[0] + b[0], a[1] + b[1])))


points10000 = babylonian_spiral(10000)
print("The first 40 Babylonian spiral points are:")
for i, p in enumerate(points10000[:40]):
     print(str(p).ljust(10), end = '\n' if (i + 1) % 10 == 0 else '')


plot(*zip(*points10000), color="navy", linewidth=0.2)
axis('scaled')
show()
Task: Discrete Fourier transform







Python: 
import cmath


def dft( x ):
    
    N                           = len( x )
    result                      = []
    for k in range( N ):
        r                       = 0
        for n in range( N ):
            t                   = -2j * cmath.pi * k * n / N
            r                  += x[n] * cmath.exp( t )
        result.append( r )
    return result


def idft( y ):
    
    N                           = len( y )
    result                      = []
    for n in range( N ):
        r                       = 0
        for k in range( N ):
            t                   = 2j * cmath.pi * k * n / N
            r                  += y[k] * cmath.exp( t )
        r                      /= N+0j
        result.append( r )
    return result


if __name__ == "__main__":
    x                           = [ 2, 3, 5, 7, 11 ]
    print( "vals:   " + ' '.join( f"{f:11.2f}" for f in x ))
    y                           = dft( x )
    print( "DFT:    " + ' '.join( f"{f:11.2f}" for f in y ))
    z                           = idft( y )
    print( "inverse:" + ' '.join( f"{f:11.2f}" for f in z ))
    print( " - real:" + ' '.join( f"{f.real:11.2f}" for f in z ))

    N                           = 8
    print( f"Complex signals, 1-4 cycles in {N} samples; energy into successive DFT bins" )
    for rot in (0, 1, 2, 3, -4, -3, -2, -1):    
        if rot > N/2:
            print( "Signal change frequency exceeds sample rate and will result in artifacts")
        sig                     = [
            
            cmath.rect(
                1, cmath.pi*2*rot/N*i
            )
            for i in range( N )
        ]
        print( f"{rot:2} cycle" + ' '.join( f"{f:11.2f}" for f in sig ))
        dft_sig                 = dft( sig )
        print( f"  DFT:  " + ' '.join( f"{f:11.2f}" for f in dft_sig ))
        print( f"   ABS: " + ' '.join( f"{abs(f):11.2f}" for f in dft_sig ))
Task: Rosetta Code_Rank languages by number of users







Python: 

import requests


URL = "http://rosettacode.org/mw/api.php"


PARAMS = {
    "action": "query",
    "format": "json",
    "formatversion": 2,
    "generator": "categorymembers",
    "gcmtitle": "Category:Language users",
    "gcmlimit": 500,
    "prop": "categoryinfo",
}


def fetch_data():
    counts = {}
    continue_ = {"continue": ""}

    
    
    while continue_:
        resp = requests.get(URL, params={**PARAMS, **continue_})
        resp.raise_for_status()

        data = resp.json()

        
        counts.update(
            {
                p["title"]: p.get("categoryinfo", {}).get("size", 0)
                for p in data["query"]["pages"]
            }
        )

        continue_ = data.get("continue", {})

    return counts


if __name__ == "__main__":
    
    counts = fetch_data()

    
    at_least_100 = [(lang, count) for lang, count in counts.items() if count >= 100]

    
    top_languages = sorted(at_least_100, key=lambda x: x[1], reverse=True)

    
    for i, lang in enumerate(top_languages):
        print(f"{i+1:<5}{lang[0][9:][:-5]:<20}{lang[1]}")
Task: HTTPS_Client-authenticated







Python: import httplib

connection = httplib.HTTPSConnection('www.example.com',cert_file='myCert.PEM')
connection.request('GET','/index.html')
response = connection.getresponse()
data = response.read()
Task: SQL-based authentication







Python: import mysql.connector 
import hashlib
 
import sys	 
import random	 
 
DB_HOST = "localhost"	 
DB_USER = "devel" 
DB_PASS = "devel"	 
DB_NAME = "test"	 
 
def connect_db():	 
    	 
    try:	 
        return mysql.connector.connect(host=DB_HOST, user=DB_USER, passwd=DB_PASS, db=DB_NAME)	 
    except:	 
        return False	 
 
def create_user(username, passwd):	 
    	 
    db = connect_db()	 
    if not db:	 
        print "Can't connect MySQL!"
        return None
 
    cursor = db.cursor()	 
 
    salt = randomValue(16)	 	 
    passwd_md5 = hashlib.md5(salt+passwd).hexdigest()	 
 
    
    try:	 
        cursor.execute("INSERT INTO users (`username`, `pass_salt`, `pass_md5`) VALUES (%s, %s, %s)", (username, salt, passwd_md5)) 
        cursor.execute("SELECT userid FROM users WHERE username=%s", (username,) ) 
        id = cursor.fetchone()
        db.commit()
        cursor.close()
        db.close()
        return id[0]	 
    except:	 
        print 'Username was already taken. Please select another'	 
        return None
 
def authenticate_user(username, passwd):	 
    db = connect_db()	 
    if not db:	 
        print "Can't connect MySQL!"
        return False
 
    cursor = db.cursor()	 
 
    cursor.execute("SELECT pass_salt, pass_md5 FROM users WHERE username=%s", (username,))

    row = cursor.fetchone()
    cursor.close()
    db.close()
    if row is None:     
        return False
    salt = row[0]
    correct_md5 = row[1]
    tried_md5 = hashlib.md5(salt+passwd).hexdigest()
    return correct_md5 == tried_md5
 
def randomValue(length):	 
    	 
    salt_chars = 'abcdefghijklmnopqrstuvwxyz0123456789'

    return ''.join(random.choice(salt_chars) for x in range(length))
 
if __name__ == '__main__':	 
    user = randomValue(10)
    passwd = randomValue(16)	 
 
    new_user_id = create_user(user, passwd)
    if new_user_id is None:
        print 'Failed to create user %s' % user
        sys.exit(1)
    auth = authenticate_user(user, passwd)	 
    if auth:	 
        print 'User %s authenticated successfully' % user	 
    else:	 
        print 'User %s failed' % user
Task: Bitmap_PPM conversion through a pipe







Python: 

from PIL import Image

im = Image.open("boxes_1.ppm")
im.save("boxes_1.jpg")
Task: Tarjan







Python: from collections import defaultdict

def from_edges(edges):
    

    class Node:
        def __init__(self):
            
            
            
            
            self.root = None
            self.succ = []

    nodes = defaultdict(Node)
    for v,w in edges:
        nodes[v].succ.append(nodes[w])

    for i,v in nodes.items(): 
        v.id = i

    return nodes.values()

def trajan(V):
    def strongconnect(v, S):
        v.root = pos = len(S)
        S.append(v)

        for w in v.succ:
            if w.root is None:  
                yield from strongconnect(w, S)

            if w.root >= 0:  
                v.root = min(v.root, w.root)

        if v.root == pos:  
            res, S[pos:] = S[pos:], []
            for w in res:
                w.root = -1
            yield [r.id for r in res]

    for v in V:
        if v.root is None:
            yield from strongconnect(v, [])


tables = [  
            [(1,2), (3,1), (3,6), (6,7), (7,6), (2,3), (4,2),
             (4,3), (4,5), (5,6), (5,4), (8,5), (8,7), (8,6)],

            
            [('A', 'B'), ('B', 'C'), ('C', 'A'), ('A', 'Other')]]

for table in (tables):
    for g in trajan(from_edges(table)):
        print(g)
    print()
Task: Powerful numbers







Python: from primesieve import primes 
import math

def primepowers(k, upper_bound):
    ub = int(math.pow(upper_bound, 1/k) + .5)
    res = [(1,)]

    for p in primes(ub):
        a = [p**k]
        u = upper_bound // a[-1]
        while u >= p:
            a.append(a[-1]*p)
            u //= p
        res.append(tuple(a))

    return res

def kpowerful(k, upper_bound, count_only=True):
    ps = primepowers(k, upper_bound)

    def accu(i, ub):
        c = 0 if count_only else [] 
        for p in ps[i]:
            u = ub//p
            if not u: break

            c += 1 if count_only else [p]

            for j in range(i + 1, len(ps)):
                if u < ps[j][0]:
                    break
                c += accu(j, u) if count_only else [p*x for x in accu(j, u)]
        return c

    res = accu(0, upper_bound)
    return res if count_only else sorted(res)

for k in range(2, 11):
    res = kpowerful(k, 10**k, count_only=False)
    print(f'{len(res)} {k}-powerfuls up to 10^{k}:',
        ' '.join(str(x) for x in res[:5]),
        '...',
        ' '.join(str(x) for x in res[-5:])
        )

for k in range(2, 11):
    res = [kpowerful(k, 10**n) for n in range(k+10)]
    print(f'{k}-powerful up to 10^{k+10}:',
        ' '.join(str(x) for x in res))
Task: Distribution of 0 digits in factorial series







Python: def facpropzeros(N, verbose = True):
    proportions = [0.0] * N
    fac, psum = 1, 0.0
    for i in range(N):
        fac *= i + 1
        d = list(str(fac))
        psum += sum(map(lambda x: x == '0', d)) / len(d)
        proportions[i] = psum / (i + 1)

    if verbose:
        print("The mean proportion of 0 in factorials from 1 to {} is {}.".format(N, psum / N))

    return proportions


for n in [100, 1000, 10000]:
    facpropzeros(n)

props = facpropzeros(47500, False)
n = (next(i for i in reversed(range(len(props))) if props[i] > 0.16))

print("The mean proportion dips permanently below 0.16 at {}.".format(n + 2))
Task: Execute CopyPasta Language







Python: import sys


def fatal_error(errtext):
	print("%" + errtext)
	print("usage: " + sys.argv[0] + " [filename.cp]")
	sys.exit(1)


fname = None
source = None
try:
	fname = sys.argv[1]
	source = open(fname).read()
except:
	fatal_error("error while trying to read from specified file")


lines = source.split("\n")


clipboard = ""


loc = 0
while(loc < len(lines)):
	
	command = lines[loc].strip()

	try:
		if(command == "Copy"):
			clipboard += lines[loc + 1]
		elif(command == "CopyFile"):
			if(lines[loc + 1] == "TheF*ckingCode"):
				clipboard += source
			else:
				filetext = open(lines[loc+1]).read()
				clipboard += filetext
		elif(command == "Duplicate"):
			clipboard += clipboard * ((int(lines[loc + 1])) - 1)
		elif(command == "Pasta!"):
			print(clipboard)
			sys.exit(0)
		else:
			fatal_error("unknown command '" + command + "' encountered on line " + str(loc + 1))
	except Exception as e:
		fatal_error("error while executing command '" + command + "' on line " + str(loc + 1) + ": " + e)

	
	loc += 2
Task: Suffixation of decimal numbers







Python: import math
import os


def suffize(num, digits=None, base=10):
    suffixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'X', 'W', 'V', 'U', 'googol']

    exponent_distance = 10 if base == 2 else 3
    num = num.strip().replace(',', '')
    num_sign = num[0] if num[0] in '+-' else ''

    num = abs(float(num))

    if base == 10 and num >= 1e100:
        suffix_index = 13
        num /= 1e100
    elif num > 1:
        magnitude = math.floor(math.log(num, base))
        suffix_index = min(math.floor(magnitude / exponent_distance), 12)
        num /= base ** (exponent_distance * suffix_index)
    else:
        suffix_index = 0

    if digits is not None:
        num_str = f'{num:.{digits}f}'
    else:
        num_str = f'{num:.3f}'.strip('0').strip('.')

    return num_sign + num_str + suffixes[suffix_index] + ('i' if base == 2 else '')


tests = [('87,654,321',),
         ('-998,877,665,544,332,211,000', 3),
         ('+112,233', 0),
         ('16,777,216', 1),
         ('456,789,100,000,000', 2),
         ('456,789,100,000,000', 2, 10),
         ('456,789,100,000,000', 5, 2),
         ('456,789,100,000.000e+00', 0, 10),
         ('+16777216', None, 2),
         ('1.2e101',)]

for test in tests:
    print(' '.join(str(i) for i in test) + ' : ' + suffize(*test))
Task: Pentomino tiling







Python: from itertools import product

minos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)),
        ((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)),
        ((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)),
        ((131843, 7, 6), (1798, 6, 7), (775, 6, 7), (1795, 6, 7), (1543, 6, 7), (197377, 7, 6), (197378, 7, 6), (66307, 7, 6)),
        ((132865, 6, 6), (131846, 6, 6), (198146, 6, 6), (132611, 6, 6), (393986, 6, 6), (263938, 6, 6), (67330, 6, 6), (132868, 6, 6)),
        ((1039, 5, 7), (33751554, 7, 5), (16843521, 7, 5), (16974081, 7, 5), (33686274, 7, 5), (3842, 5, 7), (3844, 5, 7), (527, 5, 7)),
        ((1804, 5, 7), (33751297, 7, 5), (33686273, 7, 5), (16974338, 7, 5), (16843522, 7, 5), (782, 5, 7), (3079, 5, 7), (3587, 5, 7)),
        ((263683, 6, 6), (198148, 6, 6), (66310, 6, 6), (393985, 6, 6)),
        ((67329, 6, 6), (131591, 6, 6), (459266, 6, 6), (263940, 6, 6)),
        ((459780, 6, 6), (459009, 6, 6), (263175, 6, 6), (65799, 6, 6)),
        ((4311810305, 8, 4), (31, 4, 8)),
        ((132866, 6, 6),))

boxchar_double_width = ' ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋'
boxchar_single_width = [c + ' ─━'[i%3] for i, c in enumerate(boxchar_double_width)]


patterns = boxchar_single_width

tiles = []
for row in reversed(minos):
    tiles.append([])
    for n, x, y in row:
        for shift in (b*8 + a for a, b in product(range(x), range(y))):
            tiles[-1].append(n << shift)

def img(seq):
    b = [[0]*10 for _ in range(10)]

    for i, s in enumerate(seq):
        for j, k in product(range(8), range(8)):
            if s & (1<<(j*8 + k)):
                b[j + 1][k + 1] = i + 1

    idices = [[0]*9 for _ in range(9)]
    for i, j in product(range(9), range(9)):
        n = (b[i+1][j+1], b[i][j+1], b[i][j], b[i+1][j], b[i+1][j+1])
        idices[i][j] = sum((a != b)*(1 + (not a or not b))*3**i for i, (a,b) in enumerate(zip(n, n[1:])))

    return '\n'.join(''.join(patterns[i] for i in row) for row in idices)

def tile(board=0, seq=tuple(), tiles=tiles):
    if not tiles:
        yield img(seq)
        return

    for c in tiles[0]:
        b = board | c

        tnext = [] 
        for t in tiles[1:]:
            tnext.append(tuple(n for n in t if not n&b))
            if not tnext[-1]: break 
        else:
            yield from tile(b, seq + (c,), tnext)

for x in tile():
    print(x)
Task: Divide a rectangle into a number of unequal triangles







Python: import random
from typing import List, Union, Tuple



Num = Union[int, float]
Point = Tuple[Num, Num]



def rect_into_tri(
        top_right: Tuple[Num, Num] = (2, 1), 
        triangles: int             = 5,      
        _rand_tol: Num             = 1e6,    
        ) -> List[Tuple[Point, Point, Point]]:
    

    width, height = top_right
    assert triangles > 2 and triangles % 2 == 1, "Needs Odd number greater than 2"
    

    _rand_tol = int(_rand_tol)

    
    insert_top = triangles // 2
    p = q = None
    while not p or not different_distances(p, q, height):
        p = [0] + rand_points(insert_top,     width, int(_rand_tol)) + [width]  
        q = [0] + rand_points(insert_top - 1, width, int(_rand_tol)) + [width]  

    
    top_tri = [((t0, height), (t1, height), (b0, 0))
               for t0, t1, b0 in zip(p, p[1:], q)]
    bottom_tri = [((b0, 0), (b1, 0), (t1, height))
                  for b0, b1, t1 in zip(q, q[1:], p[1:])]

    return top_tri + bottom_tri

def rect_into_top_tri(
        top_right: Tuple[Num, Num] = (2, 1),
        triangles: int             = 4,
        _rand_tol: Num             = 1e6,
        ) -> List[Tuple[Point, Point, Point]]:
    

    width, height = top_right
    assert int(triangles)==triangles and triangles > 2, "Needs int > 2"
    

    _rand_tol = int(_rand_tol)

    
    insert_top = triangles - 2
    top = [0] + rand_points(insert_top, width, int(_rand_tol)) + [width]  

    
    top_tri = [((0, 0), (t0, height), (t1, height))
               for t0, t1 in zip(top, top[1:])]
    bottom_tri = [((0, 0), (width, height), (width, 0))]

    return top_tri + bottom_tri


def rand_points(n: int, width: Num=1, _rand_tol: int=1_000_000) -> List[float]:
    "return n sorted, random points where 0 < point < width"
    return sorted(p * width / _rand_tol
                  for p in random.sample(range(1, _rand_tol), n))

def different_distances(p: List[Num], q: List[Num], height: Num) -> bool:
    "Are all point-to-next-point distances in p and q; and height all different?"
    diffs =  [p1 - p0 for p0, p1 in zip(p, p[1:])]
    diffs += [q1 - q0 for q0, q1 in zip(q, q[1:])]
    diffs += [height]
    return len(diffs) == len(set(diffs))



if __name__ == "__main__":
    from pprint import pprint as pp

    print("\nrect_into_tri 
    pp(rect_into_tri((2, 1), 5, 10))
    print("\nrect_into_tri 
    pp(rect_into_tri((2, 1), 5, 10))
    print("\nrect_into_top_tri 
    pp(rect_into_top_tri((2, 1), 4, 10))
    print("\nrect_into_top_tri 
    pp(rect_into_top_tri((2, 1), 4, 10))