WeixiangYan/CodeTransOcean huggingface dataset:
Task: Bioinformatics_base count







Python: from collections import Counter

def basecount(dna):
    return sorted(Counter(dna).items())

def seq_split(dna, n=50):
    return [dna[i: i+n] for i in range(0, len(dna), n)]

def seq_pp(dna, n=50):
    for i, part in enumerate(seq_split(dna, n)):
        print(f"{i*n:>5}: {part}")
    print("\n  BASECOUNT:")
    tot = 0
    for base, count in basecount(dna):
        print(f"    {base:>3}: {count}")
        tot += count
    base, count = 'TOT', tot
    print(f"    {base:>3}= {count}")
    
if __name__ == '__main__':
    print("SEQUENCE:")
    sequence = 
    seq_pp(sequence)


VB: b=_  
"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" &_
"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" &_
"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" &_
"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" &_
"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" &_
"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" &_
"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" &_
"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" &_
"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" &_
"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"

s="SEQUENCE:"
acnt=0:ccnt=0:gcnt=0:tcnt=0
 
for i=0 to len(b)-1
  if (i mod 30)=0 then s = s & vbcrlf & right("   "& i+1,3)&": " 
  if (i mod 5)=0 then s=s& " "
  m=mid(b,i+1,1)  
  s=s & m
  select case m
  case "A":acnt=acnt+1
  case "C":ccnt=ccnt+1
  case "G":gcnt=gcnt+1
  case "T":tcnt=tcnt+1
  case else
     wscript.echo "error at ",i+1, m 
  end select
next  
wscript.echo s & vbcrlf
wscript.echo "Count: A="&acnt & " C=" & ccnt & " G=" & gcnt & " T=" & tcnt
Task: Factorions







Python: fact = [1] 
for n in range(1, 12):
    fact.append(fact[n-1] * n)

for b in range(9, 12+1):
    print(f"The factorions for base {b} are:")
    for i in range(1, 1500000):
        fact_sum = 0
        j = i
        while j > 0:
            d = j % b
            fact_sum += fact[d]
            j = j//b
        if fact_sum == i:
            print(i, end=" ")
    print("\n")


VB: 
    Dim fact()
	nn1=9 : nn2=12
	lim=1499999
    ReDim fact(nn2)
	fact(0)=1
	For i=1 To nn2
		fact(i)=fact(i-1)*i
	Next
	For base=nn1 To nn2
		list=""
		For i=1 To lim
			s=0
			t=i
			Do While t<>0
				d=t Mod base
				s=s+fact(d)
				t=t\base
			Loop
			If s=i Then list=list &" "& i
		Next
		Wscript.Echo "the factorions for base "& right(" "& base,2) &" are: "& list
	Next
Task: Spiral matrix







Python: def spiral(n):
    dx,dy = 1,0            
    x,y = 0,0              
    myarray = [[None]* n for j in range(n)]
    for i in xrange(n**2):
        myarray[x][y] = i
        nx,ny = x+dx, y+dy
        if 0<=nx<n and 0<=ny<n and myarray[nx][ny] == None:
            x,y = nx,ny
        else:
            dx,dy = -dy,dx
            x,y = x+dx, y+dy
    return myarray

def printspiral(myarray):
    n = range(len(myarray))
    for y in n:
        for x in n:
            print "%2i" % myarray[x][y],
        print

printspiral(spiral(5))


VB: Function build_spiral(n)
	botcol = 0 : topcol = n - 1
	botrow = 0 : toprow = n - 1
	
	Dim matrix()
	ReDim matrix(topcol,toprow)
	dir = 0 : col = 0 : row = 0
	
	For i = 0 To n*n-1
		matrix(col,row) = i
		Select Case dir
			Case 0
				If col < topcol Then
					col = col + 1
				Else
					dir = 1 : row = row + 1 : botrow = botrow + 1
				End If
			Case 1
				If row < toprow Then
					row = row + 1
				Else
					dir = 2 : col = col - 1 : topcol = topcol - 1	
				End If
			Case 2
				If col > botcol Then
					col = col - 1
				Else
					dir = 3 : row = row - 1 : toprow = toprow - 1
				End If
			Case 3
				If row > botrow Then
					row = row - 1
				Else
					dir = 0 : col = col + 1 : botcol = botcol + 1
				End If
		End Select
	Next
	
	For y = 0 To n-1
		For x = 0 To n-1
			WScript.StdOut.Write matrix(x,y) & vbTab
		Next
		WScript.StdOut.WriteLine
	Next
End Function

build_spiral(CInt(WScript.Arguments(0)))
Task: Optional parameters







Python: >>> def printtable(data):
    for row in data:
        print ' '.join('%-5s' % ('"%s"' % cell) for cell in row)

        
>>> import operator
>>> def sorttable(table, ordering=None, column=0, reverse=False):
    return sorted(table, cmp=ordering, key=operator.itemgetter(column), reverse=reverse)

>>> data = [["a", "b", "c"], ["", "q", "z"], ["zap", "zip", "Zot"]]
>>> printtable(data)
"a"   "b"   "c"  
""    "q"   "z"  
"zap" "zip" "Zot"
>>> printtable( sorttable(data) )
""    "q"   "z"  
"a"   "b"   "c"  
"zap" "zip" "Zot"
>>> printtable( sorttable(data, column=2) )
"zap" "zip" "Zot"
"a"   "b"   "c"  
""    "q"   "z"  
>>> printtable( sorttable(data, column=1) )
"a"   "b"   "c"  
""    "q"   "z"  
"zap" "zip" "Zot"
>>> printtable( sorttable(data, column=1, reverse=True) )
"zap" "zip" "Zot"
""    "q"   "z"  
"a"   "b"   "c"  
>>> printtable( sorttable(data, ordering=lambda a,b: cmp(len(b),len(a))) )
"zap" "zip" "Zot"
"a"   "b"   "c"  
""    "q"   "z"  
>>>


VB: Private Sub optional_parameters(theRange As String, _
        Optional ordering As Integer = 0, _
        Optional column As Integer = 1, _
        Optional reverse As Integer = 1)
    ActiveSheet.Sort.SortFields.Clear
    ActiveSheet.Sort.SortFields.Add _
        Key:=Range(theRange).Columns(column), _
        SortOn:=SortOnValues, _
        Order:=reverse, _
        DataOption:=ordering 
    With ActiveSheet.Sort
        .SetRange Range(theRange)
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub
Public Sub main()
    
    
    
    
    
    
    
    
    
    optional_parameters theRange:="A1:C4", ordering:=1, column:=2, reverse:=1
End Sub
Task: Call a foreign-language function







Python: import ctypes
libc = ctypes.CDLL("/lib/libc.so.6")
libc.strcmp("abc", "def")     
libc.strcmp("hello", "hello") 


VB:   Declare Function CreateFileW Lib "Kernel32" (FileName As WString, DesiredAccess As Integer, ShareMode As Integer, SecurityAttributes As Integer, _
        CreateDisposition As Integer, Flags As Integer, Template As Integer) As Integer
  Declare Function WriteFile Lib "Kernel32" (fHandle As Integer, writeData As Ptr, numOfBytes As Integer, ByRef numOfBytesWritten As Integer, _
        overlapped As Ptr) As Boolean
  Declare Function GetLastError Lib "Kernel32" () As Integer
  Declare Function CloseHandle Lib "kernel32" (hObject As Integer) As Boolean
  
  Const FILE_SHARE_READ = &h00000001
  Const FILE_SHARE_WRITE = &h00000002
  Const OPEN_EXISTING = 3
  
  Dim fHandle As Integer = CreateFileW("C:\foo.txt", 0,  FILE_SHARE_READ Or FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0)
  If fHandle > 0 Then
    Dim mb As MemoryBlock = "Hello, World!"
    Dim bytesWritten As Integer
    If Not WriteFile(fHandle, mb, mb.Size, bytesWritten, Nil) Then
      MsgBox("Error Number: " + Str(GetLastError))
    End If
    Call CloseHandle(fHandle)
  Else
    MsgBox("Error Number: " + Str(GetLastError))
  End If
Task: Command-line arguments







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


VB: Function Run(args() as String) As Integer
  For each arg As String In args
    Stdout.WriteLine(arg)
  Next
End Function
Task: Word wheel







Python: import urllib.request
from collections import Counter


GRID = 


def getwords(url='http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'):
    "Return lowercased words of 3 to 9 characters"
    words = urllib.request.urlopen(url).read().decode().strip().lower().split()
    return (w for w in words if 2 < len(w) < 10)

def solve(grid, dictionary):
    gridcount = Counter(grid)
    mid = grid[4]
    return [word for word in dictionary
            if mid in word and not (Counter(word) - gridcount)]


if __name__ == '__main__':
    chars = ''.join(GRID.strip().lower().split())
    found = solve(chars, dictionary=getwords())
    print('\n'.join(found))


VB: Const wheel="ndeokgelw"

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 

Dim oDic
Set oDic = WScript.CreateObject("scripting.dictionary")
Dim cnt(127)
Dim fso
Set fso = WScript.CreateObject("Scripting.Filesystemobject")
Set ff=fso.OpenTextFile("unixdict.txt")
i=0
print "reading words of 3 or more letters"
While Not ff.AtEndOfStream
  x=LCase(ff.ReadLine) 
  If Len(x)>=3 Then 
    If  Not odic.exists(x) Then oDic.Add x,0
  End If  
Wend  
print "remaining words: "& oDic.Count & vbcrlf
ff.Close
Set ff=Nothing
Set fso=Nothing

Set re=New RegExp
print "removing words with chars not in the wheel" 
re.pattern="[^"& wheel &"]"
For Each w In oDic.Keys
  If  re.test(w) Then oDic.remove(w) 
Next
print "remaining words: "& oDic.Count & vbcrlf

print "ensuring the mandatory letter "& Mid(wheel,5,1) & " is present"
re.Pattern=Mid(wheel,5,1)
For Each w In oDic.Keys
  If  Not re.test(w) Then oDic.remove(w) 
Next
print "remaining words: "& oDic.Count & vbcrlf

print "checking number of chars"

Dim nDic
Set nDic = WScript.CreateObject("scripting.dictionary")
For i=1 To Len(wheel)
  x=Mid(wheel,i,1)
  If nDic.Exists(x) Then
    a=nDic(x)
    nDic(x)=Array(a(0)+1,0)
  Else
    nDic.add x,Array(1,0)
  End If  
Next

For Each w In oDic.Keys
  For Each c In nDic.Keys
    ndic(c)=Array(nDic(c)(0),0)
  Next
  For ii = 1 To len(w)
    c=Mid(w,ii,1) 
    a=nDic(c)
    If (a(0)=a(1)) Then  
      oDic.Remove(w):Exit For
    End If
    nDic(c)=Array(a(0),a(1)+1)
  Next
Next

print "Remaining words "& oDic.count
For Each w In oDic.Keys 
  print w  
Next
Task: Array concatenation







Python: arr1 = [1, 2, 3]
arr2 = [4, 5, 6]
arr3 = [7, 8, 9]
arr4 = arr1 + arr2
assert arr4 == [1, 2, 3, 4, 5, 6]
arr4.extend(arr3)
assert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]


VB: DEFINT A(1 to 4) = {1, 2, 3, 4}
DEFINT B(1 to 4) = {10, 20, 30, 40}


Redim A(1 to 8) as integer
MEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)
Task: User input_Text







Python:    string = raw_input("Input a string: ")


VB: Public Sub text()
    Debug.Print InputBox("Input a string")
    Debug.Print InputBox("Input the integer 75000", "Input an integer", 75000, Context = "Long")
End Sub
Task: Musical scale







Python: >>> import winsound
>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:
	winsound.Beep(int(note+.5), 500)	
>>>


VB: Option Explicit

Declare Function Beep Lib "kernel32" (ByVal Freq As Long, ByVal Dur As Long) As Long

Sub Musical_Scale()
Dim Fqs, i As Integer
   Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528)
   For i = LBound(Fqs) To UBound(Fqs)
      Beep Fqs(i), 500
   Next
End Sub
Task: Knapsack problem_0-1







Python: from itertools import combinations

def anycomb(items):
    ' return combinations of any length from the items '
    return ( comb
             for r in range(1, len(items)+1)
             for comb in combinations(items, r)
             )

def totalvalue(comb):
    ' Totalise a particular combination of items'
    totwt = totval = 0
    for item, wt, val in comb:
        totwt  += wt
        totval += val
    return (totval, -totwt) if totwt <= 400 else (0, 0)

items = (
    ("map", 9, 150), ("compass", 13, 35), ("water", 153, 200), ("sandwich", 50, 160),
    ("glucose", 15, 60), ("tin", 68, 45), ("banana", 27, 60), ("apple", 39, 40),
    ("cheese", 23, 30), ("beer", 52, 10), ("suntan cream", 11, 70), ("camera", 32, 30),
    ("t-shirt", 24, 15), ("trousers", 48, 10), ("umbrella", 73, 40),
    ("waterproof trousers", 42, 70), ("waterproof overclothes", 43, 75),
    ("note-case", 22, 80), ("sunglasses", 7, 20), ("towel", 18, 12),
    ("socks", 4, 50), ("book", 30, 10),
    )
bagged = max( anycomb(items), key=totalvalue) 
print("Bagged the following items\n  " +
      '\n  '.join(sorted(item for item,_,_ in bagged)))
val, wt = totalvalue(bagged)
print("for a total value of %i and a total weight of %i" % (val, -wt))


VB: 
Option Explicit
Const maxWeight = 400
Dim DataList As Variant
Dim xList(64, 3) As Variant
Dim nItems As Integer
Dim s As String, xss As String
Dim xwei As Integer, xval As Integer, nn As Integer

Sub Main()
    Dim i As Integer, j As Integer
    DataList = Array("map", 9, 150, "compass", 13, 35, "water", 153, 200, "sandwich", 50, 160, _
           "glucose", 15, 60, "tin", 68, 45, "banana", 27, 60, "apple", 39, 40, _
           "cheese", 23, 30, "beer", 52, 10, "suntan cream", 11, 70, "camera", 32, 30, _
           "T-shirt", 24, 15, "trousers", 48, 10, "umbrella", 73, 40, "book", 30, 10, _
           "waterproof trousers", 42, 70, "waterproof overclothes", 43, 75, _
           "note-case", 22, 80, "sunglasses", 7, 20, "towel", 18, 12, "socks", 4, 50)
    nItems = (UBound(DataList) + 1) / 3
    j = 0
    For i = 1 To nItems
        xList(i, 1) = DataList(j)
        xList(i, 2) = DataList(j + 1)
        xList(i, 3) = DataList(j + 2)
        j = j + 3
    Next i
    s = ""
    For i = 1 To nItems
        s = s & Chr(i)
    Next
    nn = 0
    Call ChoiceBin(1, "")
    For i = 1 To Len(xss)
        j = Asc(Mid(xss, i, 1))
        Debug.Print xList(j, 1)
    Next i
    Debug.Print "count=" & Len(xss), "weight=" & xwei, "value=" & xval
End Sub 

Private Sub ChoiceBin(n As String, ss As String)
    Dim r As String
    Dim i As Integer, j As Integer, iwei As Integer, ival As Integer
    Dim ipct As Integer
    If n = Len(s) + 1 Then
        iwei = 0: ival = 0
        For i = 1 To Len(ss)
            j = Asc(Mid(ss, i, 1))
            iwei = iwei + xList(j, 2)
            ival = ival + xList(j, 3)
        Next
        If iwei <= maxWeight And ival > xval Then
            xss = ss: xwei = iwei: xval = ival
        End If
    Else
        r = Mid(s, n, 1)
        Call ChoiceBin(n + 1, ss & r)
        Call ChoiceBin(n + 1, ss)
    End If
End Sub
Task: Cartesian product of two or more lists







Python: import itertools

def cp(lsts):
    return list(itertools.product(*lsts))

if __name__ == '__main__':
    from pprint import pprint as pp
    
    for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],
                  ((1776, 1789),  (7, 12), (4, 14, 23), (0, 1)),
                  ((1, 2, 3), (30,), (500, 100)),
                  ((1, 2, 3), (), (500, 100))]:
        print(lists, '=>')
        pp(cp(lists), indent=2)


VB: Imports System.Runtime.CompilerServices

Module Module1

    <Extension()>
    Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T))
        Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)}
        Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item}))
    End Function

    Sub Main()
        Dim empty(-1) As Integer
        Dim list1 = {1, 2}
        Dim list2 = {3, 4}
        Dim list3 = {1776, 1789}
        Dim list4 = {7, 12}
        Dim list5 = {4, 14, 23}
        Dim list6 = {0, 1}
        Dim list7 = {1, 2, 3}
        Dim list8 = {30}
        Dim list9 = {500, 100}

        For Each sequnceList As Integer()() In {
            ({list1, list2}),
            ({list2, list1}),
            ({list1, empty}),
            ({empty, list1}),
            ({list3, list4, list5, list6}),
            ({list7, list8, list9}),
            ({list7, empty, list9})
        }
            Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $"({String.Join(", ", tuple)})")
            Console.WriteLine($"{{{String.Join(", ", cart)}}}")
        Next
    End Sub

End Module
Task: Proper divisors







Python: >>> def proper_divs2(n):
...     return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x}
... 
>>> [proper_divs2(n) for n in range(1, 11)]
[set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}]
>>> 
>>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1])
>>> n
15120
>>> length
79
>>>


VB: dim _proper_divisors(100)

sub proper_divisors(n)
	dim i
	dim _proper_divisors_count = 0
	if n <> 1 then
		for i = 1 to (n \ 2)
			if n %% i = 0 then
				_proper_divisors_count = _proper_divisors_count + 1
				_proper_divisors(_proper_divisors_count) = i 
			end if
		next
	end if
	return _proper_divisors_count
end sub

sub show_proper_divisors(n, tabbed)
	dim cnt = proper_divisors(n)
	print str$(n) + ":"; tab(4);"(" + str$(cnt) + " items) ";
	dim j 
	for j = 1 to cnt
		if tabbed then
			print str$(_proper_divisors(j)),
		else 
			print str$(_proper_divisors(j));
		end if
		if (j < cnt) then print ",";
	next
	print
end sub

dim i
for i = 1 to 10
    show_proper_divisors(i, false)
next

dim c 
dim maxindex = 0
dim maxlength = 0
for t = 1 to 20000
	c = proper_divisors(t)
	if c > maxlength then
		maxindex = t
		maxlength = c
	end if
next

print "A maximum at ";
show_proper_divisors(maxindex, false)
Task: XML_Output







Python: >>> from xml.etree import ElementTree as ET
>>> from itertools import izip
>>> def characterstoxml(names, remarks):
	root = ET.Element("CharacterRemarks")
	for name, remark in izip(names, remarks):
		c = ET.SubElement(root, "Character", {'name': name})
		c.text = remark
	return ET.tostring(root)

>>> print characterstoxml(
	names = ["April", "Tam O'Shanter", "Emily"],
	remarks = [ "Bubbly: I'm > Tam and <= Emily",
		    'Burns: "When chapman billies leave the street ..."',
		    'Short & shrift' ] ).replace('><','>\n<')


VB: Module XMLOutput
    Sub Main()
        Dim charRemarks As New Dictionary(Of String, String)
        charRemarks.Add("April", "Bubbly: I
        charRemarks.Add("Tam O
        charRemarks.Add("Emily", "Short & shrift")

        Dim xml = <CharacterRemarks>
                      <%= From cr In charRemarks Select <Character name=<%= cr.Key %>><%= cr.Value %></Character> %>
                  </CharacterRemarks>

        Console.WriteLine(xml)
    End Sub
End Module
Task: Plot coordinate pairs







Python: >>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]

>>> import pylab
>>> pylab.plot(x, y, 'bo')
>>> pylab.savefig('qsort-range-10-9.png')


VB: Private Sub plot_coordinate_pairs(x As Variant, y As Variant)
    Dim chrt As Chart
    Set chrt = ActiveSheet.Shapes.AddChart.Chart
    With chrt
        .ChartType = xlLine
        .HasLegend = False
        .HasTitle = True
        .ChartTitle.Text = "Time"
        .SeriesCollection.NewSeries
        .SeriesCollection.Item(1).XValues = x
        .SeriesCollection.Item(1).Values = y
        .Axes(xlValue, xlPrimary).HasTitle = True
        .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "microseconds"
    End With
End Sub
Public Sub main()
    x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}]
    y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}]
    plot_coordinate_pairs x, y
End Sub
Task: Regular expressions







Python: import re

string = "This is a string"

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

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


VB: text = "I need more coffee!!!"
Set regex = New RegExp
regex.Global = True
regex.Pattern = "\s"
If regex.Test(text) Then
	WScript.StdOut.Write regex.Replace(text,vbCrLf)
Else
	WScript.StdOut.Write "No matching pattern"
End If
Task: Hash from two arrays







Python: keys = ['a', 'b', 'c']
values = [1, 2, 3]
hash = {key: value for key, value in zip(keys, values)}


VB: Set dict = CreateObject("Scripting.Dictionary")
os = Array("Windows", "Linux", "MacOS")
owner = Array("Microsoft", "Linus Torvalds", "Apple")
For n = 0 To 2
    dict.Add os(n), owner(n)
Next
MsgBox dict.Item("Linux")
MsgBox dict.Item("MacOS")
MsgBox dict.Item("Windows")
Task: Colour pinstripe_Display







Python: from turtle import *

colors = ["black", "red", "green", "blue", "magenta", "cyan", "yellow", "white"]



screen = getscreen()

left_edge = -screen.window_width()//2

right_edge = screen.window_width()//2

quarter_height = screen.window_height()//4

half_height = quarter_height * 2

speed("fastest")

for quarter in range(4):
    pensize(quarter+1)
    colornum = 0

    min_y = half_height - ((quarter + 1) * quarter_height)
    max_y = half_height - ((quarter) * quarter_height)
    
    for x in range(left_edge,right_edge,quarter+1):
        penup()
        pencolor(colors[colornum])
        colornum = (colornum + 1) % len(colors)
        setposition(x,min_y)
        pendown()
        setposition(x,max_y)
         
notused = input("Hit enter to continue: ")


VB: Public Class Main
    Inherits System.Windows.Forms.Form
    Public Sub New()
        Me.FormBorderStyle = FormBorderStyle.None
        Me.WindowState = FormWindowState.Maximized
    End Sub
    Private Sub Main_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim Index As Integer
        Dim Colors() As Color = {Color.Black, Color.Red, Color.Green, Color.Magenta, Color.Cyan, Color.Yellow, Color.White}
        Dim Height = (Me.ClientSize.Height / 4) + 1
        For y = 1 To 4
            Dim Top = Me.ClientSize.Height / 4 * (y - 1)
            For x = 0 To Me.ClientSize.Width Step y
                If Index = 6 Then Index = 0 Else Index += 1
                Me.Controls.Add(New Panel With {.Top = Top, .Height = Height, .Left = x, .Width = y, .BackColor = Colors(Index)})
            Next
        Next
    End Sub
End Class
Task: Sorting algorithms_Cocktail sort with shifting bounds







Python: 
            
def cocktailshiftingbounds(A):
    beginIdx = 0
    endIdx = len(A) - 1
    
    while beginIdx <= endIdx:
        newBeginIdx = endIdx
        newEndIdx = beginIdx
        for ii in range(beginIdx,endIdx):
            if A[ii] > A[ii + 1]:
                A[ii+1], A[ii] = A[ii], A[ii+1]
                newEndIdx = ii
                
        endIdx = newEndIdx
    
        for ii in range(endIdx,beginIdx-1,-1):
            if A[ii] > A[ii + 1]:
                A[ii+1], A[ii] = A[ii], A[ii+1]
                newBeginIdx = ii
        
        beginIdx = newBeginIdx + 1
            
test1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]
cocktailshiftingbounds(test1)
print(test1)
 
test2=list('big fjords vex quick waltz nymph')
cocktailshiftingbounds(test2)
print(''.join(test2))


VB: 

Function cocktailShakerSort(ByVal A As Variant) As Variant
    beginIdx = LBound(A)
    endIdx = UBound(A) - 1
    Do While beginIdx <= endIdx
        newBeginIdx = endIdx
        newEndIdx = beginIdx
        For ii = beginIdx To endIdx
            If A(ii) > A(ii + 1) Then
                tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp
                newEndIdx = ii
            End If
        Next ii
        endIdx = newEndIdx - 1
        For ii = endIdx To beginIdx Step -1
            If A(ii) > A(ii + 1) Then
                tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp
                newBeginIdx = ii
            End If
        Next ii
        beginIdx = newBeginIdx + 1
    Loop
    cocktailShakerSort = A
End Function 

Public Sub main()
    Dim B(20) As Variant
    For i = LBound(B) To UBound(B)
        B(i) = Int(Rnd() * 100)
    Next i
    Debug.Print Join(B, ", ")
    Debug.Print Join(cocktailShakerSort(B), ", ")
End Sub
Task: Gray code







Python: >>> def int2bin(n):
	'From positive integer to list of binary bits, msb at index 0'
	if n:
		bits = []
		while n:
			n,remainder = divmod(n, 2)
			bits.insert(0, remainder)
		return bits
	else: return [0]

	
>>> def bin2int(bits):
	'From binary bits, msb at index 0 to integer'
	i = 0
	for bit in bits:
		i = i * 2 + bit
	return i


VB: Function Encoder(ByVal n)
    Encoder = n Xor (n \ 2)
End Function

Function Decoder(ByVal n)
    Dim g : g = 0
    Do While n > 0
       g = g Xor n
       n = n \ 2
    Loop
    Decoder = g
End Function


Function Dec2bin(ByVal n, ByVal length)
    Dim i, strbin : strbin = ""
    For i = 1 to 5
        strbin = (n Mod 2) & strbin
        n = n \ 2
    Next
    Dec2Bin = strbin
End Function

WScript.StdOut.WriteLine("Binary -> Gray Code -> Binary")
For i = 0 to 31
    encoded = Encoder(i)
    decoded = Decoder(encoded)
    WScript.StdOut.WriteLine(Dec2Bin(i, 5) & " -> " & Dec2Bin(encoded, 5) & " -> " & Dec2Bin(decoded, 5))
Next