WeixiangYan/CodeTransOcean huggingface dataset:
Task: Dragon curve







Python: l = 3
ints = 13

def setup():
  size(700, 600)
  background(0, 0, 255)
  translate(150, 100)
  stroke(255)
  turn_left(l, ints)
  turn_right(l, ints)

def turn_right(l, ints):
    if ints == 0:
        line(0, 0, 0, -l)
        translate(0, -l)
    else:
        turn_left(l, ints - 1)
        rotate(radians(90))
        turn_right(l, ints - 1)
  
def turn_left(l, ints):
    if ints == 0:
        line(0, 0, 0, -l)
        translate(0, -l)
    else:
        turn_left(l, ints - 1)
        rotate(radians(-90))
        turn_right(l, ints - 1)


VB: option explicit


const pi180= 0.01745329251994329576923690768489 
const pi=3.1415926535897932384626433832795 
class turtle
   
   dim fso
   dim fn
   dim svg
   
   dim iang  
   dim ori   
   dim incr
   dim pdown
   dim clr
   dim x
   dim y

   public property let orient(n):ori = n*pi180 :end property
   public property let iangle(n):iang= n*pi180 :end property
   public sub pd() : pdown=true: end sub 
   public sub pu()  :pdown=FALSE :end sub 
   
   public sub rt(i)  
     ori=ori - i*iang:
     
   end sub 
   public sub lt(i):  
     ori=(ori + i*iang) 
     
   end sub
   
   public sub bw(l)
      x= x+ cos(ori+pi)*l*incr
      y= y+ sin(ori+pi)*l*incr
     
   end sub 
   
   public sub fw(l)
      dim x1,y1 
      x1=x + cos(ori)*l*incr
      y1=y + sin(ori)*l*incr
      if pdown then line x,y,x1,y1
      x=x1:y=y1
   end sub
   
   Private Sub Class_Initialize()  
      setlocale "us"   
      initsvg
      x=400:y=400:incr=100
      ori=90*pi180
      iang=90*pi180
      clr=0
      pdown=true
   end sub
   
   Private Sub Class_Terminate()   
      disply
   end sub
   
   private sub line (x,y,x1,y1)
      svg.WriteLine "<line x1=""" & x & """ y1= """& y & """ x2=""" & x1& """ y2=""" & y1 & """/>"
   end sub 

   private sub disply()
       dim shell
       svg.WriteLine "</svg></body></html>"
       svg.close
       Set shell = CreateObject("Shell.Application") 
       shell.ShellExecute fn,1,False
   end sub 

   private sub initsvg()
     dim scriptpath
     Set fso = CreateObject ("Scripting.Filesystemobject")
     ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\"))
     fn=Scriptpath & "SIERP.HTML"
     Set svg = fso.CreateTextFile(fn,True)
     if SVG IS nothing then wscript.echo "Can
     svg.WriteLine "<!DOCTYPE html>" &vbcrlf & "<html>" &vbcrlf & "<head>"
     svg.writeline "<style>" & vbcrlf & "line {stroke:rgb(255,0,0);stroke-width:.5}" &vbcrlf &"</style>"
     svg.writeline "</head>"&vbcrlf & "<body>"
     svg.WriteLine "<svg xmlns=""http://www.w3.org/2000/svg"" width=""800"" height=""800"" viewBox=""0 0 800 800"">" 
   end sub 
end class

sub dragon(st,le,dir)
if st=0 then x.fw le: exit sub
  x.rt dir
  dragon st-1, le/1.41421 ,1
  x.rt dir*2
  dragon st-1, le/1.41421 ,-1
  x.rt dir
end sub

 
dim x
set x=new turtle
x.iangle=45
x.orient=45
x.incr=1
x.x=200:x.y=200
dragon 12,300,1
set x=nothing
Task: Read a file line by line







Python: for line in lines open('input.txt'):
    print line


VB: $Include "Rapidq.inc"
dim file as qfilestream

if file.open("c:\A Test.txt", fmOpenRead) then
    while not File.eof
        print File.readline
    wend
else
    print "Cannot read file"
end if

input "Press enter to exit: ";a$
Task: Doubly-linked list_Element insertion







Python: def insert(anchor, new):
    new.next = anchor.next
    new.prev = anchor
    anchor.next.prev = new
    anchor.next = new


VB: Public Sub Insert(ByVal a As Node(Of T), ByVal b As Node(Of T), ByVal c As T)
    Dim node As New Node(Of T)(value)
    a.Next = node
    node.Previous = a
    b.Previous = node
    node.Next = b
End Sub
Task: Quickselect algorithm







Python: import random

def partition(vector, left, right, pivotIndex):
    pivotValue = vector[pivotIndex]
    vector[pivotIndex], vector[right] = vector[right], vector[pivotIndex]  
    storeIndex = left
    for i in range(left, right):
        if vector[i] < pivotValue:
            vector[storeIndex], vector[i] = vector[i], vector[storeIndex]
            storeIndex += 1
    vector[right], vector[storeIndex] = vector[storeIndex], vector[right]  
    return storeIndex

def _select(vector, left, right, k):
    "Returns the k-th smallest, (k >= 0), element of vector within vector[left:right+1] inclusive."
    while True:
        pivotIndex = random.randint(left, right)     
        pivotNewIndex = partition(vector, left, right, pivotIndex)
        pivotDist = pivotNewIndex - left
        if pivotDist == k:
            return vector[pivotNewIndex]
        elif k < pivotDist:
            right = pivotNewIndex - 1
        else:
            k -= pivotDist + 1
            left = pivotNewIndex + 1

def select(vector, k, left=None, right=None):
    
    if left is None:
        left = 0
    lv1 = len(vector) - 1
    if right is None:
        right = lv1
    assert vector and k >= 0, "Either null vector or k < 0 "
    assert 0 <= left <= lv1, "left is out of range"
    assert left <= right <= lv1, "right is out of range"
    return _select(vector, left, right, k)

if __name__ == '__main__':
    v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]
    print([select(v, i) for i in range(10)])


VB: Dim s As Variant
Private Function quick_select(ByRef s As Variant, k As Integer) As Integer
    Dim left As Integer, right As Integer, pos As Integer
    Dim pivotValue As Integer, tmp As Integer
    left = 1: right = UBound(s)
    Do While left < right
        pivotValue = s(k)
        tmp = s(k)
        s(k) = s(right)
        s(right) = tmp
        pos = left
        For i = left To right
            If s(i) < pivotValue Then
                tmp = s(i)
                s(i) = s(pos)
                s(pos) = tmp
                pos = pos + 1
            End If
        Next i
        tmp = s(right)
        s(right) = s(pos)
        s(pos) = tmp
        If pos = k Then
            Exit Do
        End If
        If pos < k Then
            left = pos + 1
        Else
            right = pos - 1
        End If
    Loop
    quick_select = s(k)
End Function
Public Sub main()
    Dim r As Integer, i As Integer
    s = [{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}]
    For i = 1 To 10
        r = quick_select(s, i) 
        Debug.Print IIf(i < 10, r & ", ", "" & r);
    Next i
End Sub
Task: Non-decimal radices_Convert







Python: i = int('1a',16)  


VB: Private Function to_base(ByVal number As Long, base As Integer) As String
    Dim digits As String, result As String
    Dim i As Integer, digit As Integer
    digits = "0123456789abcdefghijklmnopqrstuvwxyz"
    Do While number > 0
        digit = number Mod base
        result = Mid(digits, digit + 1, 1) & result
        number = number \ base
    Loop
    to_base = result
End Function
Private Function from_base(number As String, base As Integer) As Long
    Dim digits As String, result As Long
    Dim i As Integer
    digits = "0123456789abcdefghijklmnopqrstuvwxyz"
    result = Val(InStr(1, digits, Mid(number, 1, 1), vbTextCompare) - 1)
    For i = 2 To Len(number)
        result = result * base + Val(InStr(1, digits, Mid(number, i, 1), vbTextCompare) - 1)
    Next i
    from_base = result
End Function
Public Sub Non_decimal_radices_Convert()
    Debug.Print "26 decimal in base 16 is: "; to_base(26, 16); ". Conversely, hexadecimal 1a in decimal is: "; from_base("1a", 16)
End Sub
Task: Walk a directory_Recursively







Python: from pathlib import Path

for path in Path('.').rglob('*.*'):
    print(path)


VB: Sub printFiles(parentDir As FolderItem, pattern As String)
  For i As Integer = 1 To parentDir.Count
    If parentDir.Item(i).Directory Then
      printFiles(parentDir.Item(i), pattern)
    Else
      Dim rg as New RegEx
      Dim myMatch as RegExMatch
      rg.SearchPattern = pattern
      myMatch = rg.search(parentDir.Item(i).Name)
      If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)
    End If
  Next
End Sub
Task: CRC-32







Python: >>> s = 'The quick brown fox jumps over the lazy dog'
>>> import zlib
>>> hex(zlib.crc32(s))
'0x414fa339'

>>> import binascii
>>> hex(binascii.crc32(s))
'0x414fa339'


VB: dim crctbl(255)
const crcc =&hEDB88320

sub gencrctable
for i= 0 to 255
   k=i
   for j=1 to 8
    if k and 1 then 
      k=(k and &h7fffffff)\2 or (&h40000000 and ((k and &h80000000)<>0)) 
      k=k xor crcc
    else 
      k=(k and &h7fffffff)\2 or (&h40000000 and ((k and &h80000000)<>0))
   end if
   next 
   crctbl(i)=k
 next
end sub
 
 function crc32 (buf) 
  dim r,r1,i 
  r=&hffffffff 
  for i=1 to len(buf) 
      r1=(r and &h7fffffff)\&h100 or (&h800000 and (r and &h80000000)<>0)
    r=r1 xor crctbl((asc(mid(buf,i,1))xor r) and 255) 
  next 
  crc32=r xor &hffffffff
end function

  

gencrctable
wscript.stdout.writeline hex(crc32("The quick brown fox jumps over the lazy dog"))
Task: CSV to HTML translation







Python: csvtxt = 

from cgi import escape

def _row2tr(row, attr=None):
    cols = escape(row).split(',')
    return ('<TR>'
            + ''.join('<TD>%s</TD>' % data for data in cols)
            + '</TR>')

def csv2html(txt):
    htmltxt = '<TABLE summary="csv2html program output">\n'
    for rownum, row in enumerate(txt.split('\n')):
        htmlrow = _row2tr(row)
        htmlrow = '  <TBODY>%s</TBODY>\n' % htmlrow
        htmltxt += htmlrow
    htmltxt += '</TABLE>\n'
    return htmltxt

htmltxt = csv2html(csvtxt)
print(htmltxt)


VB: Public Sub CSV_TO_HTML()
    input_ = "Character,Speech\n" & _
        "The multitude,The messiah! Show us the messiah!\n" & _
        "Brians mother,<angry>Now you listen here! He
            "he
        "The multitude,Who are you?\n" & _
        "Brians mother,I
        "The multitude,Behold his mother! Behold his mother!"
     
    Debug.Print "<table>" & vbCrLf & "<tr><td>"
    For i = 1 To Len(input_)
        Select Case Mid(input_, i, 1)
            Case "\"
                If Mid(input_, i + 1, 1) = "n" Then
                    Debug.Print "</td></tr>" & vbCrLf & "<tr><td>";
                    i = i + 1
                Else
                    Debug.Print Mid(input_, i, 1);
                End If
            Case ",": Debug.Print "</td><td>";
            Case "<": Debug.Print "&lt;";
            Case ">": Debug.Print "&gt;";
            Case "&": Debug.Print "&amp;";
            Case Else: Debug.Print Mid(input_, i, 1);
        End Select
    Next i
    Debug.Print "</td></tr>" & vbCrLf & "</table>"
End Sub
Task: Classes







Python: class MyClass:
    name2 = 2 

    def __init__(self):
        
        self.name1 = 0 
  
    def someMethod(self):
        
        self.name1 = 1
        MyClass.name2 = 3
  
  
myclass = MyClass() 

class MyOtherClass:
    count = 0  
    def __init__(self, name, gender="Male", age=None):
        
        MyOtherClass.count += 1
        self.name = name
        self.gender = gender
        if age is not None:
            self.age = age
    def __del__(self):
        MyOtherClass.count -= 1

person1 = MyOtherClass("John")
print person1.name, person1.gender  
print person1.age                   
person2 = MyOtherClass("Jane", "Female", 23)
print person2.name, person2.gender, person2.age  


VB: Class NumberContainer
  Private TheNumber As Integer
  Sub Constructor(InitialNumber As Integer)
    TheNumber = InitialNumber
  End Sub

  Function Number() As Integer
    Return TheNumber
  End Function

  Sub Number(Assigns NewNumber As Integer)
    TheNumber = NewNumber
  End Sub
End Class
Task: Kaprekar numbers







Python: >>> def k(n):
	n2 = str(n**2)
	for i in range(len(n2)):
		a, b = int(n2[:i] or 0), int(n2[i:])
		if b and a + b == n:
			return n
			

		
>>> [x for x in range(1,10000) if k(x)]
[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]
>>> len([x for x in range(1,1000000) if k(x)])
54
>>>


VB: Module Module1

    ReadOnly max As ULong = 1000000

    Function Kaprekar(n As ULong) As Boolean
        If n = 1 Then Return True

        Dim sq = n * n
        Dim sq_str = Str(sq)
        Dim l = Len(sq_str)

        For x = l - 1 To 1 Step -1
            If sq_str(x) = "0" Then
                l = l - 1
            Else
                Exit For
            End If
        Next

        For x = 1 To l - 1
            Dim p2 = Val(Mid(sq_str, x + 1))
            If p2 > n Then
                Continue For
            End If
            Dim p1 = Val(Left(sq_str, x))
            If p1 > n Then Return False
            If (p1 + p2) = n Then Return True
        Next

        Return False
    End Function

    Sub Main()
        Dim count = 0

        Console.WriteLine("Kaprekar numbers below 10000")

        For n = 1 To max - 1
            If Kaprekar(n) Then
                count = count + 1
                If n < 10000 Then
                    Console.WriteLine("{0,2} {1,4}", count, n)
                End If
            End If
        Next

        Console.WriteLine()
        Console.WriteLine("{0} numbers below {1} are kaprekar numbers", count, max)
    End Sub

End Module
Task: LZW compression







Python: def compress(uncompressed):
    

    
    dict_size = 256
    dictionary = dict((chr(i), i) for i in range(dict_size))
    

    w = ""
    result = []
    for c in uncompressed:
        wc = w + c
        if wc in dictionary:
            w = wc
        else:
            result.append(dictionary[w])
            
            dictionary[wc] = dict_size
            dict_size += 1
            w = c

    
    if w:
        result.append(dictionary[w])
    return result


def decompress(compressed):
    
    from io import StringIO

    
    dict_size = 256
    dictionary = dict((i, chr(i)) for i in range(dict_size))
    

    
    
    result = StringIO()
    w = chr(compressed.pop(0))
    result.write(w)
    for k in compressed:
        if k in dictionary:
            entry = dictionary[k]
        elif k == dict_size:
            entry = w + w[0]
        else:
            raise ValueError('Bad compressed k: %s' % k)
        result.write(entry)

        
        dictionary[dict_size] = w + entry[0]
        dict_size += 1

        w = entry
    return result.getvalue()



compressed = compress('TOBEORNOTTOBEORTOBEORNOT')
print (compressed)
decompressed = decompress(compressed)
print (decompressed)


VB: Option Explicit
Const numchars=127  

Function LZWCompress(si)
  Dim oDict,  intMaxCode, i,z,ii,ss,strCurrent,strNext,j
  Set oDict = CreateObject("Scripting.Dictionary")
  ReDim a(Len(si))
  
  intMaxCode = numchars
  For i = 0 To numchars
    oDict.Add Chr(i), i
  Next
  
  strCurrent = Left(si,1)
  j=0
  For ii=2 To Len(si)
    strNext = Mid(si,ii,1)
    ss=strCurrent & strNext
    If oDict.Exists(ss) Then
      strCurrent = ss
    Else
      a(j)=oDict.Item(strCurrent) :j=j+1
      intMaxCode = intMaxCode + 1
      oDict.Add ss, intMaxCode
      strCurrent = strNext
    End If
  Next
  a(j)=oDict.Item(strCurrent) 
  ReDim preserve a(j)
  LZWCompress=a
  Set oDict = Nothing
End Function

Function lzwUncompress(sc)
  Dim intNext, intCurrent, intMaxCode, i,ss,istr,s,j
  s=""     
  reDim dict(1000)
  intMaxCode = numchars
  For i = 0 To numchars : dict(i)= Chr(i) :  Next
    intCurrent=sc(0)
    
    For j=1 To UBound(sc)
      ss=dict(intCurrent)
      s= s & ss
      intMaxCode = intMaxCode + 1
      intnext=sc(j)
      If intNext<intMaxCode Then
        dict(intMaxCode)=ss & Left(dict(intNext), 1)
      Else
        dict(intMaxCode)=ss & Left(ss, 1) 
      End If
      intCurrent = intNext
    Next
    s= s & dict(intCurrent)
    lzwUncompress=s
End function

Sub printvec(a)
  Dim s,i,x
  s="("
  For i=0 To UBound (a)
   s=s & x & a(i)
   x=", "
  Next 
  WScript.echo s &")"
End sub

Dim a,b
b="TOBEORNOTTOBEORTOBEORNOT"
WScript.Echo b
a=LZWCompress (b)
printvec(a)
WScript.echo lzwUncompress (a )
wscript.quit 1
Task: Hofstadter Figure-Figure sequences







Python: def ffr(n):
    if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1")
    try:
        return ffr.r[n]
    except IndexError:
        r, s = ffr.r, ffs.s
        ffr_n_1 = ffr(n-1)
        lastr = r[-1]
        
        s += list(range(s[-1] + 1, lastr))
        if s[-1] < lastr: s += [lastr + 1]
        
        len_s = len(s)
        ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]
        ans = ffr_n_1 + ffs_n_1
        r.append(ans)
        return ans
ffr.r = [None, 1]

def ffs(n):
    if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1")
    try:
        return ffs.s[n]
    except IndexError:
        r, s = ffr.r, ffs.s
        for i in range(len(r), n+2):
            ffr(i)
            if len(s) > n:
                return s[n]
        raise Exception("Whoops!")
ffs.s = [None, 2]

if __name__ == '__main__':
    first10 = [ffr(i) for i in range(1,11)]
    assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], "ffr() value error(s)"
    print("ffr(n) for n = [1..10] is", first10)
    
    bin = [None] + [0]*1000
    for i in range(40, 0, -1):
        bin[ffr(i)] += 1
    for i in range(960, 0, -1):
        bin[ffs(i)] += 1
    if all(b == 1 for b in bin[1:1000]):
        print("All Integers 1..1000 found OK")
    else:
        print("All Integers 1..1000 NOT found only once: ERROR")


VB: Private Function ffr(n As Long) As Long
    Dim R As New Collection
    Dim S As New Collection
    R.Add 1
    S.Add 2
    
    For i = 2 To n
        R.Add R(i - 1) + S(i - 1)
        For j = S(S.Count) + 1 To R(i) - 1
            S.Add j
        Next j
        For j = R(i) + 1 To R(i) + S(i - 1)
            S.Add j
        Next j
    Next i
    ffr = R(n)
    Set R = Nothing
    Set S = Nothing
End Function
Private Function ffs(n As Long) As Long
    Dim R As New Collection
    Dim S As New Collection
    R.Add 1
    S.Add 2
    
    For i = 2 To n
        R.Add R(i - 1) + S(i - 1)
        For j = S(S.Count) + 1 To R(i) - 1
            S.Add j
        Next j
        For j = R(i) + 1 To R(i) + S(i - 1)
            S.Add j
        Next j
        If S.Count >= n Then Exit For
    Next i
    ffs = S(n)
    Set R = Nothing
    Set S = Nothing
End Function
Public Sub main()
    Dim i As Long
    Debug.Print "The first ten values of R are:"
    For i = 1 To 10
        Debug.Print ffr(i);
    Next i
    Debug.Print
    Dim x As New Collection
    For i = 1 To 1000
        x.Add i, CStr(i)
    Next i
    For i = 1 To 40
        x.Remove CStr(ffr(i))
    Next i
    For i = 1 To 960
        x.Remove CStr(ffs(i))
    Next i
    Debug.Print "The first 40 values of ffr plus the first 960 values of ffs "
    Debug.Print "include all the integers from 1 to 1000 exactly once is "; Format(x.Count = 0)
End Sub
Task: Magic squares of odd order







Python: >>> def magic(n):
    for row in range(1, n + 1):
        print(' '.join('%*i' % (len(str(n**2)), cell) for cell in
                       (n * ((row + col - 1 + n // 2) % n) +
                       ((row + 2 * col - 2) % n) + 1
                       for col in range(1, n + 1))))
    print('\nAll sum to magic number %i' % ((n * n + 1) * n // 2))

    
>>> for n in (5, 3, 7):
	print('\nOrder %i\n=======' % n)
	magic(n)

	

Order 5
=======
17 24  1  8 15
23  5  7 14 16
 4  6 13 20 22
10 12 19 21  3
11 18 25  2  9

All sum to magic number 65

Order 3
=======
8 1 6
3 5 7
4 9 2

All sum to magic number 15

Order 7
=======
30 39 48  1 10 19 28
38 47  7  9 18 27 29
46  6  8 17 26 35 37
 5 14 16 25 34 36 45
13 15 24 33 42 44  4
21 23 32 41 43  3 12
22 31 40 49  2 11 20

All sum to magic number 175
>>>


VB: Sub magicsquare()
    
    Const n = 9
    Dim i As Integer, j As Integer, v As Integer
    Debug.Print "The square order is: " & n
    For i = 1 To n
        For j = 1 To n
            Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1
        Next j
    Next i
    Debug.Print "The magic number of"; n; "x"; n; "square is:"; n * (n * n + 1) \ 2
End Sub
Task: Benford's law







Python: from __future__ import division
from itertools import islice, count
from collections import Counter
from math import log10
from random import randint

expected = [log10(1+1/d) for d in range(1,10)]

def fib():
    a,b = 1,1
    while True:
        yield a
        a,b = b,a+b


def power_of_threes():
    return (3**k for k in count(0))

def heads(s):
    for a in s: yield int(str(a)[0])

def show_dist(title, s):
    c = Counter(s)
    size = sum(c.values())
    res = [c[d]/size for d in range(1,10)]

    print("\n%s Benfords deviation" % title)
    for r, e in zip(res, expected):
        print("%5.1f%% %5.1f%%  %5.1f%%" % (r*100., e*100., abs(r - e)*100.))

def rand1000():
    while True: yield randint(1,9999)

if __name__ == '__main__':
    show_dist("fibbed", islice(heads(fib()), 1000))
    show_dist("threes", islice(heads(power_of_threes()), 1000))

    
    show_dist("random", islice(heads(rand1000()), 10000))


VB: Sub BenfordLaw()

Dim BenResult(1 To 9) As Long

BENref = "30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%"

For Each c In Selection.Cells
  If InStr(1, "-0123456789", Left(c, 1)) > 0 Then
    For i = 1 To 9
      If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For
    Next
  End If
Next
Total= Application.Sum(BenResult)
biggest= Len(CStr(BenResult(1)))

txt = "#   |   Values    |     Real     |  Expected   " & vbCrLf
For i = 1 To 9
  If BenResult(i) > 0 Then
    txt = txt & "#" & i & " | " & vbTab
    txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, " ") & Format(BenResult(i), "0") & " | " & vbTab
    txt = txt & String((Len(CStr(Format(BenResult(1) / Total, "##0.0%"))) - Len(CStr(Format(BenResult(i) / Total, "##0.0%")))) * 2, " ") & Format(BenResult(i) / Total, "##0.0%") & " | " & vbTab
    txt = txt & Format(Split(BENref, "|")(i - 1), "     ##0.0%") & vbCrLf
  End If
Next

MsgBox txt, vbOKOnly, "Finish"

End Sub

}
Task: Anonymous recursion







Python: >>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))
>>> [ Y(fib)(i) for i in range(-2, 10) ]
[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]


VB: Sub Main()
Debug.Print F(-10)
Debug.Print F(10)
End Sub

Private Function F(N As Long) As Variant
    If N < 0 Then
        F = "Error. Negative argument"
    ElseIf N <= 1 Then
        F = N
    Else
        F = F(N - 1) + F(N - 2)
    End If
End Function
Task: Substring_Top and tail







Python: print "knight"[1:]     
print "socks"[:-1]     
print "brooms"[1:-1]   


VB: string = "Small Basic"
TextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) 
TextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) 
TextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2))
Task: Longest string challenge







Python: import fileinput






def longer(a, b):
    try:
        b[len(a)-1]
        return False
    except:
        return True

longest, lines = '', ''
for x in fileinput.input():
    if longer(x, longest):
        lines, longest = x, x
    elif not longer(longest, x):
        lines += x

print(lines, end='')


VB: 

Set objfso = CreateObject("Scripting.FileSystemObject")
Set objfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_
	"\input.txt",1)

list = ""
previous_line = ""
l = Len(previous_line)

Do Until objfile.AtEndOfStream
	current_line = objfile.ReadLine
	If Mid(current_line,l+1,1) <> "" Then
		list = current_line & vbCrLf
		previous_line = current_line
		l = Len(previous_line)
	ElseIf Mid(current_line,l,1) <> ""  And Mid(current_line,(l+1),1) = "" Then
		list = list & current_line & vbCrLf
	End If
Loop

WScript.Echo list

objfile.Close
Set objfso = Nothing
Task: Create a file







Python: import os
for directory in ['/', './']:
  open(directory + 'output.txt', 'w').close()  
  os.mkdir(directory + 'docs')                 


VB: Public Sub create_file()
    Dim FileNumber As Integer
    FileNumber = FreeFile
    MkDir "docs"
    Open "docs\output.txt" For Output As #FreeFile
    Close #FreeFile
    MkDir "C:\docs"
    Open "C:\docs\output.txt" For Output As #FreeFile
    Close #FreeFile
End Sub