WeixiangYan/CodeTransOcean huggingface dataset:
Task: Move-to-front algorithm







Python: from __future__ import print_function
from string import ascii_lowercase

SYMBOLTABLE = list(ascii_lowercase)

def move2front_encode(strng, symboltable):
    sequence, pad = [], symboltable[::]
    for char in strng:
        indx = pad.index(char)
        sequence.append(indx)
        pad = [pad.pop(indx)] + pad
    return sequence

def move2front_decode(sequence, symboltable):
    chars, pad = [], symboltable[::]
    for indx in sequence:
        char = pad[indx]
        chars.append(char)
        pad = [pad.pop(indx)] + pad
    return ''.join(chars)

if __name__ == '__main__':
    for s in ['broood', 'bananaaa', 'hiphophiphop']:
        encode = move2front_encode(s, SYMBOLTABLE)
        print('%14r encodes to %r' % (s, encode), end=', ')
        decode = move2front_decode(encode, SYMBOLTABLE)
        print('which decodes back to %r' % decode)
        assert s == decode, 'Whoops!'


VB: Function mtf_encode(s)
	
	Set symbol_table = CreateObject("System.Collections.ArrayList")
	For j = 97 To 122 
		symbol_table.Add Chr(j)
	Next
	output = ""
	For i = 1 To Len(s)
		char = Mid(s,i,1)
		If i = Len(s) Then
			output = output & symbol_table.IndexOf(char,0)
			symbol_table.RemoveAt(symbol_table.LastIndexOf(char))
			symbol_table.Insert 0,char
		Else
			output = output & symbol_table.IndexOf(char,0) & " "
			symbol_table.RemoveAt(symbol_table.LastIndexOf(char))
			symbol_table.Insert 0,char
		End If
	Next
	mtf_encode = output
End Function

Function mtf_decode(s)
	
	code = Split(s," ")
	
	Set symbol_table = CreateObject("System.Collections.ArrayList")
	For j = 97 To 122 
		symbol_table.Add Chr(j)
	Next
	output = ""
	For i = 0 To UBound(code)
		char = symbol_table(code(i))
		output = output & char
		If code(i) <> 0 Then
			symbol_table.RemoveAt(symbol_table.LastIndexOf(char))
			symbol_table.Insert 0,char
		End If
	Next
	mtf_decode = output	
End Function


wordlist = Array("broood","bananaaa","hiphophiphop")
For Each word In wordlist
	WScript.StdOut.Write word & " encodes as " & mtf_encode(word) & " and decodes as " &_
		mtf_decode(mtf_encode(word)) & "."
	WScript.StdOut.WriteBlankLines(1)
Next
Task: Execute a system command







Python: import os
exit_code = os.system('ls')       
output    = os.popen('ls').read() 


VB: Set objShell = CreateObject("WScript.Shell")
objShell.Run "%comspec% /K dir",3,True
Task: XML validation







Python: 
from __future__ import print_function
import lxml
from lxml import etree

if __name__=="__main__":

	parser = etree.XMLParser(dtd_validation=True)
	schema_root = etree.XML()
	schema = etree.XMLSchema(schema_root)

	
	parser = etree.XMLParser(schema = schema)
	try:
		root = etree.fromstring("<a>5</a>", parser)
		print ("Finished validating good xml")
	except lxml.etree.XMLSyntaxError as err:
		print (err)

	
	parser = etree.XMLParser(schema = schema)
	try:
		root = etree.fromstring("<a>5<b>foobar</b></a>", parser)
	except lxml.etree.XMLSyntaxError as err:
		print (err)


VB: Option explicit

Function fileexists(fn) 
  fileexists= CreateObject("Scripting.FileSystemObject").FileExists(fn)
End Function

Function xmlvalid(strfilename)
  Dim xmldoc,xmldoc2,objSchemas 
  Set xmlDoc = CreateObject("Msxml2.DOMDocument.6.0")
  
  If fileexists(Replace(strfilename,".xml",".dtd")) Then
    xmlDoc.setProperty "ProhibitDTD", False
    xmlDoc.setProperty "ResolveExternals", True 
    xmlDoc.validateOnParse = True
    xmlDoc.async = False
    xmlDoc.load(strFileName)
  ElseIf fileexists(Replace(strfilename,".xml",".xsd")) Then
    xmlDoc.setProperty "ProhibitDTD", True
    xmlDoc.setProperty "ResolveExternals", True 
    xmlDoc.validateOnParse = True
    xmlDoc.async = False
    xmlDoc.load(strFileName)
    
    
    Set xmlDoc2 = CreateObject("Msxml2.DOMDocument.6.0")
    xmlDoc2.validateOnParse = True
    xmlDoc2.async = False
    xmlDoc2.load(Replace (strfilename,".xml",".xsd"))
    
    
    Set objSchemas = CreateObject("MSXML2.XMLSchemaCache.6.0")
    objSchemas.Add "", xmlDoc2
  Else 
    Set xmlvalid= Nothing:Exit Function
  End If
  
  Set xmlvalid=xmldoc.parseError 
End Function



Sub displayerror (parserr) 
  Dim strresult
  If parserr is Nothing Then 
    strresult= "could not find dtd or xsd for " & strFileName
  Else   
    With parserr
     Select Case .errorcode
      Case 0 
        strResult = "Valid: " & strFileName & vbCr
      Case Else
        strResult = vbCrLf & "ERROR! Failed to validate " & _
        strFileName & vbCrLf &.reason & vbCr & _
        "Error code: " & .errorCode & ", Line: " & _
        .line & ", Character: " & _
        .linepos & ", Source: """ & _
        .srcText &  """ - " & vbCrLf 
 
      End Select
    End With
  End If
  WScript.Echo strresult
End Sub


Dim strfilename






strfilename="shiporder.xml"
displayerror xmlvalid (strfilename)
Task: Longest increasing subsequence







Python: def longest_increasing_subsequence(X):
    
    N = len(X)
    P = [0] * N
    M = [0] * (N+1)
    L = 0
    for i in range(N):
       lo = 1
       hi = L
       while lo <= hi:
           mid = (lo+hi)//2
           if (X[M[mid]] < X[i]):
               lo = mid+1
           else:
               hi = mid-1
    
       newL = lo
       P[i] = M[newL-1]
       M[newL] = i
    
       if (newL > L):
           L = newL
    
    S = []
    k = M[L]
    for i in range(L-1, -1, -1):
        S.append(X[k])
        k = P[k]
    return S[::-1]

if __name__ == '__main__':
    for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:
        print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))


VB: Function LIS(arr)
	n = UBound(arr)
	Dim p()
	ReDim p(n)
	Dim m()
	ReDim m(n)
	l = 0
	For i = 0 To n
		lo = 1
		hi = l
		Do While lo <= hi
			middle = Int((lo+hi)/2)
			If arr(m(middle)) < arr(i) Then
				lo = middle + 1
			Else
				hi = middle - 1
			End If
		Loop
		newl = lo
		p(i) = m(newl-1)
		m(newl) = i
		If newL > l Then
			l = newl
		End If
	Next
	Dim s()
	ReDim s(l)
	k = m(l)
	For i = l-1 To 0 Step - 1
		s(i) = arr(k)
		k = p(k)
	Next
	LIS = Join(s,",")
End Function

WScript.StdOut.WriteLine LIS(Array(3,2,6,4,5,1))
WScript.StdOut.WriteLine LIS(Array(0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15))
Task: GUI component interaction







Python: import random, tkMessageBox
from Tkinter import *
window = Tk()
window.geometry("300x50+100+100")
options = { "padx":5, "pady":5}
s=StringVar()
s.set(1)
def increase():
    s.set(int(s.get())+1)
def rand():
    if tkMessageBox.askyesno("Confirmation", "Reset to random value ?"):
        s.set(random.randrange(0,5000))
def update(e):
    if not e.char.isdigit():
        tkMessageBox.showerror('Error', 'Invalid input !') 
        return "break"
e = Entry(text=s)
e.grid(column=0, row=0, **options)
e.bind('<Key>', update)
b1 = Button(text="Increase", command=increase, **options )
b1.grid(column=1, row=0, **options)
b2 = Button(text="Random", command=rand, **options)
b2.grid(column=2, row=0, **options)
mainloop()


VB: VERSION 5.00
Begin VB.Form Form1 
   Caption         =   "Form1"
   ClientHeight    =   2265
   ClientLeft      =   60
   ClientTop       =   600
   ClientWidth     =   2175
   LinkTopic       =   "Form1"
   ScaleHeight     =   2265
   ScaleWidth      =   2175
   StartUpPosition =   3  
   Begin VB.CommandButton cmdRnd 
      Caption         =   "Random"
      Height          =   495
      Left            =   120
      TabIndex        =   2
      Top             =   1680
      Width           =   1215
   End
   Begin VB.CommandButton cmdInc 
      Caption         =   "Increment"
      Height          =   495
      Left            =   120
      TabIndex        =   1
      Top             =   1080
      Width           =   1215
   End
   Begin VB.TextBox txtValue 
      Height          =   495
      Left            =   120
      TabIndex        =   0
      Text            =   "0"
      Top             =   240
      Width           =   1215
   End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False

Private Sub Form_Load()
    Randomize Timer
End Sub

Private Sub cmdRnd_Click()
    If MsgBox("Random?", vbYesNo) Then txtValue.Text = Int(Rnd * 11)
End Sub

Private Sub cmdInc_Click()
    If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1
End Sub

Private Sub txtValue_KeyPress(KeyAscii As Integer)
    Select Case KeyAscii
        Case 8, 43, 45, 48 To 57
            
        Case Else
            KeyAscii = 0
    End Select
End Sub
Task: One of n lines in a file







Python: from random import randrange
try:
    range = xrange
except: pass

def one_of_n(lines): 
    choice = None
    for i, line in enumerate(lines):
        if randrange(i+1) == 0:
            choice = line
    return choice
            
def one_of_n_test(n=10, trials=1000000):
    bins = [0] * n
    if n:
        for i in range(trials):
            bins[one_of_n(range(n))] += 1
    return bins

print(one_of_n_test())


VB: Dim chosen(10)

For j = 1 To 1000000
	c = one_of_n(10)
	chosen(c) = chosen(c) + 1
Next

For k = 1 To 10
	WScript.StdOut.WriteLine k & ". " & chosen(k)
Next 

Function one_of_n(n)
	Randomize
	For i = 1 To n
		If Rnd(1) < 1/i Then
			one_of_n = i
		End If
	Next
End Function
Task: Self-describing numbers







Python: >>> def isSelfDescribing(n):
	s = str(n)
	return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))

>>> [x for x in range(4000000) if isSelfDescribing(x)]
[1210, 2020, 21200, 3211000]
>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]
[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]


VB: Function IsSelfDescribing(n)
	IsSelfDescribing = False
	Set digit = CreateObject("Scripting.Dictionary")
	For i = 1 To Len(n)
		k = Mid(n,i,1)
		If digit.Exists(k) Then
			digit.Item(k) = digit.Item(k) + 1
		Else
			digit.Add k,1
		End If	
	Next
	c = 0
	For j = 0 To Len(n)-1
		l = Mid(n,j+1,1)
		If digit.Exists(CStr(j)) Then
			If digit.Item(CStr(j)) = CInt(l) Then
				c = c + 1
			End If
		ElseIf l = 0 Then
			c = c + 1
		Else
			Exit For
		End If
	Next
	If c = Len(n) Then
		IsSelfDescribing = True
	End If
End Function


start_time = Now
s = ""
For m = 1 To 100000000
	If 	IsSelfDescribing(m) Then
		WScript.StdOut.WriteLine m
	End If
Next
end_time = Now
WScript.StdOut.WriteLine "Elapse Time: " & DateDiff("s",start_time,end_time) & " seconds"
Task: Addition chains







Python: def prepend(n, seq):
    return [n] + seq

def check_seq(pos, seq, n, min_len):
    if pos > min_len or seq[0] > n:
        return min_len, 0
    if seq[0] == n:
        return pos, 1
    if pos < min_len:
        return try_perm(0, pos, seq, n, min_len)
    return min_len, 0

def try_perm(i, pos, seq, n, min_len):
    if i > pos:
        return min_len, 0

    res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len)
    res2 = try_perm(i + 1, pos, seq, n, res1[0])

    if res2[0] < res1[0]:
        return res2
    if res2[0] == res1[0]:
        return res2[0], res1[1] + res2[1]
    raise Exception("try_perm exception")

def init_try_perm(x):
    return try_perm(0, 0, [1], x, 12)

def find_brauer(num):
    res = init_try_perm(num)
    print
    print "N = ", num
    print "Minimum length of chains: L(n) = ", res[0]
    print "Number of minimum length Brauer chains: ", res[1]


nums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379]
for i in nums:
    find_brauer(i)


VB: Module Module1

    Function Prepend(n As Integer, seq As List(Of Integer)) As List(Of Integer)
        Dim result As New List(Of Integer) From {
            n
        }
        result.AddRange(seq)
        Return result
    End Function

    Function CheckSeq(pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)
        If pos > min_len OrElse seq(0) > n Then
            Return Tuple.Create(min_len, 0)
        End If
        If seq(0) = n Then
            Return Tuple.Create(pos, 1)
        End If
        If pos < min_len Then
            Return TryPerm(0, pos, seq, n, min_len)
        End If
        Return Tuple.Create(min_len, 0)
    End Function

    Function TryPerm(i As Integer, pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer)
        If i > pos Then
            Return Tuple.Create(min_len, 0)
        End If

        Dim res1 = CheckSeq(pos + 1, Prepend(seq(0) + seq(i), seq), n, min_len)
        Dim res2 = TryPerm(i + 1, pos, seq, n, res1.Item1)

        If res2.Item1 < res1.Item1 Then
            Return res2
        End If
        If res2.Item1 = res1.Item1 Then
            Return Tuple.Create(res2.Item1, res1.Item2 + res2.Item2)
        End If

        Throw New Exception("TryPerm exception")
    End Function

    Function InitTryPerm(x As Integer) As Tuple(Of Integer, Integer)
        Return TryPerm(0, 0, New List(Of Integer) From {1}, x, 12)
    End Function

    Sub FindBrauer(num As Integer)
        Dim res = InitTryPerm(num)
        Console.WriteLine("N = {0}", num)
        Console.WriteLine("Minimum length of chains: L(n) = {0}", res.Item1)
        Console.WriteLine("Number of minimum length Brauer chains: {0}", res.Item2)
        Console.WriteLine()
    End Sub

    Sub Main()
        Dim nums() = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379}
        Array.ForEach(nums, Sub(n) FindBrauer(n))
    End Sub

End Module
Task: Repeat







Python: 
def repeat(f,n):
  for i in range(n):
    f();

def procedure():
  print("Example");

repeat(procedure,3); 


VB: Private Sub Repeat(rid As String, n As Integer)
    For i = 1 To n
        Application.Run rid
    Next i
End Sub
 
Private Sub Hello()
    Debug.Print "Hello"
End Sub
 
Public Sub main()
    Repeat "Hello", 5
End Sub
Task: Sparkline in unicode







Python: 


bar = '▁▂▃▄▅▆▇█'
barcount = len(bar)

def sparkline(numbers):
    mn, mx = min(numbers), max(numbers)
    extent = mx - mn
    sparkline = ''.join(bar[min([barcount - 1,
                                 int((n - mn) / extent * barcount)])]
                        for n in numbers)
    return mn, mx, sparkline

if __name__ == '__main__':
    import re
    
    for line in ("0 0 1 1; 0 1 19 20; 0 999 4000 4999 7000 7999;"
                 "1 2 3 4 5 6 7 8 7 6 5 4 3 2 1;"
                 "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 ").split(';'):
        print("\nNumbers:", line)
        numbers = [float(n) for n in re.split(r'[\s,]+', line.strip())]
        mn, mx, sp = sparkline(numbers)
        print('  min: %5f; max: %5f' % (mn, mx))
        print("  " + sp)


VB: 

sub ensure_cscript()
if instrrev(ucase(WScript.FullName),"WSCRIPT.EXE")then
   createobject("wscript.shell").run "CSCRIPT //nologo """ &_
     WScript.ScriptFullName &"""" ,,0
   wscript.quit
 end if
end sub 

class bargraph
  private bar,mn,mx,nn,cnt

  Private sub class_initialize()
     bar=chrw(&h2581)&chrw(&h2582)&chrw(&h2583)&chrw(&h2584)&chrw(&h2585)&_
     chrw(&h2586)&chrw(&h2587)&chrw(&h2588)
     nn=8
  end sub


  public function bg (s)
    a=split(replace(replace(s,","," "),"  "," ")," ")

    mn=999999:mx=-999999:cnt=ubound(a)+1
    for i=0 to ubound(a)
       a(i)=cdbl(trim(a(i)))
       if a(i)>mx then mx=a(i) 
       if a(i)<mn then mn=a(i) 
    next
   
    ss="Data:    "
    for i=0 to ubound(a) :ss=ss & right ("     "& a(i),6) :next
    
    ss=ss+vbcrlf + "sparkline: "  
    
    for i=0 to ubound(a)
       x=scale(a(i))
       
       ss=ss & string(6,mid(bar,x,1))
    next
    bg=ss &vbcrlf & "min: "&mn & "  max: "& mx & _
      " cnt: "& ubound(a)+1 &vbcrlf
  end function   

  private function scale(x)
    if x=<mn then 
      scale=1
    elseif x>=mx then
      scale=nn
    else
      scale=int(nn* (x-mn)/(mx-mn)+1)
    end if  
  end function    

end class

ensure_cscript

set b=new bargraph
wscript.stdout.writeblanklines 2
wscript.echo b.bg("1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1")
wscript.echo b.bg("1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5")
wscript.echo b.bg("0, 1, 19, 20")
wscript.echo b.bg("0, 999, 4000, 4999, 7000, 7999")
set b=nothing

wscript.echo "If bars don
"font to DejaVu Sans Mono or any other that has the bargrph characters" & _
vbcrlf

wscript.stdout.write "Press any key.." : wscript.stdin.read 1
Task: Modular inverse







Python: >>> def extended_gcd(aa, bb):
    lastremainder, remainder = abs(aa), abs(bb)
    x, lastx, y, lasty = 0, 1, 1, 0
    while remainder:
        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)
        x, lastx = lastx - quotient*x, x
        y, lasty = lasty - quotient*y, y
    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)

>>> def modinv(a, m):
	g, x, y = extended_gcd(a, m)
	if g != 1:
		raise ValueError
	return x % m

>>> modinv(42, 2017)
1969
>>>


VB: Private Function mul_inv(a As Long, n As Long) As Variant
    If n < 0 Then n = -n
    If a < 0 Then a = n - ((-a) Mod n)
    Dim t As Long: t = 0
    Dim nt As Long: nt = 1
    Dim r As Long: r = n
    Dim nr As Long: nr = a
    Dim q As Long
    Do While nr <> 0
        q = r \ nr
        tmp = t
        t = nt
        nt = tmp - q * nt
        tmp = r
        r = nr
        nr = tmp - q * nr
    Loop
    If r > 1 Then
        mul_inv = "a is not invertible"
    Else
        If t < 0 Then t = t + n
        mul_inv = t
    End If
End Function
Public Sub mi()
    Debug.Print mul_inv(42, 2017)
    Debug.Print mul_inv(40, 1)
    Debug.Print mul_inv(52, -217) 
    Debug.Print mul_inv(-486, 217)
    Debug.Print mul_inv(40, 2018)
End Sub
Task: Hello world_Web server







Python: from wsgiref.simple_server import make_server

def app(environ, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    yield b"<h1>Goodbye, World!</h1>"

server = make_server('127.0.0.1', 8080, app)
server.serve_forever()


VB: Class HTTPSock
Inherits TCPSocket
  Event Sub DataAvailable()
    Dim headers As New InternetHeaders
    headers.AppendHeader("Content-Length", Str(LenB("Goodbye, World!")))
    headers.AppendHeader("Content-Type", "text/plain")
    headers.AppendHeader("Content-Encoding", "identity")
    headers.AppendHeader("Connection", "close")
    Dim data As String = "HTTP/1.1 200 OK" + EndOfLine.Windows + headers.Source + EndOfLine.Windows + EndOfLine.Windows + "Goodbye, World!"
    Me.Write(data)
    Me.Close
  End Sub
End Class

Class HTTPServ
Inherits ServerSocket
  Event Sub AddSocket() As TCPSocket
    Return New HTTPSock
  End Sub
End Class

Class App
Inherits Application
  Event Sub Run(Args() As String)
    Dim sock As New HTTPServ
    sock.Port = 8080
    sock.Listen()
    While True
      App.DoEvents
    Wend
  End Sub
End Class
Task: Sorting algorithms_Pancake sort







Python: tutor = False

def pancakesort(data):
    if len(data) <= 1:
        return data
    if tutor: print()
    for size in range(len(data), 1, -1):
        maxindex = max(range(size), key=data.__getitem__)
        if maxindex+1 != size:
            
            if maxindex != 0:
                
                if tutor: print('With: %r doflip  %i'
                                % ( ' '.join(str(x) for x in data), maxindex+1 ))
                data[:maxindex+1] = reversed(data[:maxindex+1])
            
            if tutor: print('With: %r  doflip %i'
                                % ( ' '.join(str(x) for x in data), size ))
            data[:size] = reversed(data[:size])
    if tutor: print()


VB: 


Public Sub printarray(A)
  For i = LBound(A) To UBound(A)
    Debug.Print A(i),
  Next
  Debug.Print
End Sub

Public Sub Flip(ByRef A, p1, p2, trace)

 If trace Then Debug.Print "we
 Cut = Int((p2 - p1 + 1) / 2)
 For i = 0 To Cut - 1
   
   temp = A(i)
   A(i) = A(p2 - i)
   A(p2 - i) = temp
 Next
End Sub

Public Sub pancakesort(ByRef A(), Optional trace As Boolean = False)


lb = LBound(A)
ub = UBound(A)
Length = ub - lb + 1
If Length <= 1 Then 
  Exit Sub
End If

For i = ub To lb + 1 Step -1
  
  P = lb
  Maximum = A(P)
  For j = lb + 1 To i
    If A(j) > Maximum Then
      P = j
      Maximum = A(j)
    End If
  Next j
  
  If P < i Then
    
    If P > 1 Then
      Flip A, lb, P, trace
      If trace Then printarray A
    End If
    
    Flip A, lb, i, trace
    If trace Then printarray A
  End If
Next i
End Sub


Public Sub TestPancake(Optional trace As Boolean = False)
Dim A()
A = Array(5, 7, 8, 3, 1, 10, 9, 23, 50, 0)
Debug.Print "Initial array:"
printarray A
pancakesort A, trace
Debug.Print "Final array:"
printarray A
End Sub
Task: Pythagorean quadruples







Python: def quad(top=2200):
    r = [False] * top
    ab = [False] * (top * 2)**2
    for a in range(1, top):
        for b in range(a, top):
            ab[a * a + b * b] = True
    s = 3
    for c in range(1, top):
        s1, s, s2 = s, s + 2, s + 2
        for d in range(c + 1, top):
            if ab[s1]:
                r[d] = True
            s1 += s2
            s2 += 2
    return [i for i, val in enumerate(r) if not val and i]
    
if __name__ == '__main__':
    n = 2200
    print(f"Those values of d in 1..{n} that can't be represented: {quad(n)}")


VB: Const n = 2200
Public Sub pq()
    Dim s As Long, s1 As Long, s2 As Long, x As Long, x2 As Long, y As Long: s = 3
    Dim l(n) As Boolean, l_add(9680000) As Boolean 
    For x = 1 To n
        x2 = x * x
        For y = x To n
            l_add(x2 + y * y) = True
        Next y
    Next x
    For x = 1 To n
        s1 = s
        s = s + 2
        s2 = s
        For y = x + 1 To n
            If l_add(s1) Then l(y) = True
            s1 = s1 + s2
            s2 = s2 + 2
        Next
    Next
    For x = 1 To n
        If Not l(x) Then Debug.Print x;
    Next
    Debug.Print
End Sub
Task: Long stairs







Python: 

from numpy import mean
from random import sample

def gen_long_stairs(start_step, start_length, climber_steps, add_steps):
    secs, behind, total = 0, start_step, start_length
    while True:
        behind += climber_steps
        behind += sum([behind > n for n in sample(range(total), add_steps)])
        total += add_steps
        secs += 1
        yield (secs, behind, total)
        

ls = gen_long_stairs(1, 100, 1, 5)

print("Seconds  Behind  Ahead\n----------------------")
while True:
    secs, pos, len = next(ls)
    if 600 <= secs < 610:
        print(secs, "     ", pos, "   ", len - pos)
    elif secs == 610:
        break

print("\nTen thousand trials to top:")
times, heights = [], []
for trial in range(10_000):
    trialstairs = gen_long_stairs(1, 100, 1, 5)
    while True:
        sec, step, height = next(trialstairs)
        if step >= height:
            times.append(sec)
            heights.append(height)
            break

print("Mean time:", mean(times), "secs. Mean height:", mean(heights))


VB: Option Explicit
Randomize Timer

Function pad(s,n) 
  If n<0 Then pad= right(space(-n) & s ,-n) Else  pad= left(s& space(n),n) End If 
End Function

Sub print(s)
  On Error Resume Next
  WScript.stdout.WriteLine (s)  
  If  err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit
End Sub

Function Rounds(maxsecs,wiz,a)
  Dim mystep,maxstep,toend,j,i,x,d 
  If IsArray(a) Then d=True: print "seconds behind pending"   
  maxstep=100
  For j=1 To maxsecs
    For i=1 To wiz
      If Int(Rnd*maxstep)<=mystep Then mystep=mystep+1
      maxstep=maxstep+1  
    Next 
    mystep=mystep+1 
    If mystep=maxstep Then Rounds=Array(j,maxstep) :Exit Function
    If d Then
      If j>=a(0) And j<=a(1) Then print pad(j,-7) & pad (mystep,-7) & pad (maxstep-mystep,-8)
    End If     
  Next 
  Rounds=Array(maxsecs,maxstep)
End Function


Dim n,r,a,sumt,sums,ntests,t,maxsecs
ntests=10000
maxsecs=7000
t=timer
a=Array(600,609)
For n=1 To ntests
  r=Rounds(maxsecs,5,a)
  If r(0)<>maxsecs Then 
    sumt=sumt+r(0)
    sums=sums+r(1)
  End if  
  a=""
Next  

print vbcrlf & "Done " & ntests & " tests in " & Timer-t & " seconds" 
print "escaped in " & sumt/ntests  & " seconds with " & sums/ntests & " stairs"