Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Can you help me rewrite this code in Python instead of VB, keeping it the same logically? | Dim total As Variant, prim As Variant, maxPeri As Variant
Private Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)
Dim p As Variant
p = CDec(s0) + CDec(s1) + CDec(s2)
If p <= maxPeri Then
prim = prim + 1
total = total + maxPeri \ p
newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2
newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2
newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2
End If
End Sub
Public Sub Program_PythagoreanTriples()
maxPeri = CDec(100)
Do While maxPeri <= 10000000#
prim = CDec(0)
total = CDec(0)
newTri 3, 4, 5
Debug.Print "Up to "; maxPeri; ": "; total; " triples, "; prim; " primitives."
maxPeri = maxPeri * 10
Loop
End Sub
| from fractions import gcd
def pt1(maxperimeter=100):
trips = []
for a in range(1, maxperimeter):
aa = a*a
for b in range(a, maxperimeter-a+1):
bb = b*b
for c in range(b, maxperimeter-b-a+1):
cc = c*c
if a+b+c > maxperimeter or cc > aa + bb: break
if aa + bb == cc:
trips.append((a,b,c, gcd(a, b) == 1))
return trips
def pytrip(trip=(3,4,5),perim=100, prim=1):
a0, b0, c0 = a, b, c = sorted(trip)
t, firstprim = set(), prim>0
while a + b + c <= perim:
t.add((a, b, c, firstprim>0))
a, b, c, firstprim = a+a0, b+b0, c+c0, False
t2 = set()
for a, b, c, firstprim in t:
a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7
if a5 - b5 + c7 <= perim:
t2 |= pytrip(( a - b2 + c2, a2 - b + c2, a2 - b2 + c3), perim, firstprim)
if a5 + b5 + c7 <= perim:
t2 |= pytrip(( a + b2 + c2, a2 + b + c2, a2 + b2 + c3), perim, firstprim)
if -a5 + b5 + c7 <= perim:
t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)
return t | t2
def pt2(maxperimeter=100):
trips = pytrip((3,4,5), maxperimeter, 1)
return trips
def printit(maxperimeter=100, pt=pt1):
trips = pt(maxperimeter)
print(" Up to a perimeter of %i there are %i triples, of which %i are primitive"
% (maxperimeter,
len(trips),
len([prim for a,b,c,prim in trips if prim])))
for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):
print(algo.__doc__)
for maxperimeter in range(mn, mx+1, mn):
printit(maxperimeter, algo)
|
Convert this VB snippet to Python and keep its semantics consistent. | Dim total As Variant, prim As Variant, maxPeri As Variant
Private Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)
Dim p As Variant
p = CDec(s0) + CDec(s1) + CDec(s2)
If p <= maxPeri Then
prim = prim + 1
total = total + maxPeri \ p
newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2
newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2
newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2
End If
End Sub
Public Sub Program_PythagoreanTriples()
maxPeri = CDec(100)
Do While maxPeri <= 10000000#
prim = CDec(0)
total = CDec(0)
newTri 3, 4, 5
Debug.Print "Up to "; maxPeri; ": "; total; " triples, "; prim; " primitives."
maxPeri = maxPeri * 10
Loop
End Sub
| from fractions import gcd
def pt1(maxperimeter=100):
trips = []
for a in range(1, maxperimeter):
aa = a*a
for b in range(a, maxperimeter-a+1):
bb = b*b
for c in range(b, maxperimeter-b-a+1):
cc = c*c
if a+b+c > maxperimeter or cc > aa + bb: break
if aa + bb == cc:
trips.append((a,b,c, gcd(a, b) == 1))
return trips
def pytrip(trip=(3,4,5),perim=100, prim=1):
a0, b0, c0 = a, b, c = sorted(trip)
t, firstprim = set(), prim>0
while a + b + c <= perim:
t.add((a, b, c, firstprim>0))
a, b, c, firstprim = a+a0, b+b0, c+c0, False
t2 = set()
for a, b, c, firstprim in t:
a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7
if a5 - b5 + c7 <= perim:
t2 |= pytrip(( a - b2 + c2, a2 - b + c2, a2 - b2 + c3), perim, firstprim)
if a5 + b5 + c7 <= perim:
t2 |= pytrip(( a + b2 + c2, a2 + b + c2, a2 + b2 + c3), perim, firstprim)
if -a5 + b5 + c7 <= perim:
t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)
return t | t2
def pt2(maxperimeter=100):
trips = pytrip((3,4,5), maxperimeter, 1)
return trips
def printit(maxperimeter=100, pt=pt1):
trips = pt(maxperimeter)
print(" Up to a perimeter of %i there are %i triples, of which %i are primitive"
% (maxperimeter,
len(trips),
len([prim for a,b,c,prim in trips if prim])))
for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):
print(algo.__doc__)
for maxperimeter in range(mn, mx+1, mn):
printit(maxperimeter, algo)
|
Convert this VB block to Python, preserving its control flow and logic. | Dim total As Variant, prim As Variant, maxPeri As Variant
Private Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)
Dim p As Variant
p = CDec(s0) + CDec(s1) + CDec(s2)
If p <= maxPeri Then
prim = prim + 1
total = total + maxPeri \ p
newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2
newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2
newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2
End If
End Sub
Public Sub Program_PythagoreanTriples()
maxPeri = CDec(100)
Do While maxPeri <= 10000000#
prim = CDec(0)
total = CDec(0)
newTri 3, 4, 5
Debug.Print "Up to "; maxPeri; ": "; total; " triples, "; prim; " primitives."
maxPeri = maxPeri * 10
Loop
End Sub
| from fractions import gcd
def pt1(maxperimeter=100):
trips = []
for a in range(1, maxperimeter):
aa = a*a
for b in range(a, maxperimeter-a+1):
bb = b*b
for c in range(b, maxperimeter-b-a+1):
cc = c*c
if a+b+c > maxperimeter or cc > aa + bb: break
if aa + bb == cc:
trips.append((a,b,c, gcd(a, b) == 1))
return trips
def pytrip(trip=(3,4,5),perim=100, prim=1):
a0, b0, c0 = a, b, c = sorted(trip)
t, firstprim = set(), prim>0
while a + b + c <= perim:
t.add((a, b, c, firstprim>0))
a, b, c, firstprim = a+a0, b+b0, c+c0, False
t2 = set()
for a, b, c, firstprim in t:
a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7
if a5 - b5 + c7 <= perim:
t2 |= pytrip(( a - b2 + c2, a2 - b + c2, a2 - b2 + c3), perim, firstprim)
if a5 + b5 + c7 <= perim:
t2 |= pytrip(( a + b2 + c2, a2 + b + c2, a2 + b2 + c3), perim, firstprim)
if -a5 + b5 + c7 <= perim:
t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)
return t | t2
def pt2(maxperimeter=100):
trips = pytrip((3,4,5), maxperimeter, 1)
return trips
def printit(maxperimeter=100, pt=pt1):
trips = pt(maxperimeter)
print(" Up to a perimeter of %i there are %i triples, of which %i are primitive"
% (maxperimeter,
len(trips),
len([prim for a,b,c,prim in trips if prim])))
for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):
print(algo.__doc__)
for maxperimeter in range(mn, mx+1, mn):
printit(maxperimeter, algo)
|
Produce a language-to-language conversion: from VB to Python, same semantics. | Option Explicit
Sub Main()
Dim myArr() As Variant, i As Long
myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, "Alpha", 1, 235, 4, 1.25, 1.25, "Beta", 1.23456789101112E+16, "Delta", "Alpha", "Charlie", 1, 2, "Foxtrot", "Foxtrot", "Alpha", 235))
For i = LBound(myArr) To UBound(myArr)
Debug.Print myArr(i)
Next
End Sub
Private Function Remove_Duplicate(Arr As Variant) As Variant()
Dim myColl As New Collection, Temp() As Variant, i As Long, cpt As Long
ReDim Temp(UBound(Arr))
For i = LBound(Arr) To UBound(Arr)
On Error Resume Next
myColl.Add CStr(Arr(i)), CStr(Arr(i))
If Err.Number > 0 Then
On Error GoTo 0
Else
Temp(cpt) = Arr(i)
cpt = cpt + 1
End If
Next i
ReDim Preserve Temp(cpt - 1)
Remove_Duplicate = Temp
End Function
| items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']
unique = list(set(items))
|
Generate an equivalent Python version of this VB code. | function looksay( n )
dim i
dim accum
dim res
dim c
res = vbnullstring
do
if n = vbnullstring then exit do
accum = 0
c = left( n,1 )
do while left( n, 1 ) = c
accum = accum + 1
n = mid(n,2)
loop
if accum > 0 then
res = res & accum & c
end if
loop
looksay = res
end function
| def lookandsay(number):
result = ""
repeat = number[0]
number = number[1:]+" "
times = 1
for actual in number:
if actual != repeat:
result += str(times)+repeat
times = 1
repeat = actual
else:
times += 1
return result
num = "1"
for i in range(10):
print num
num = lookandsay(num)
|
Maintain the same structure and functionality when rewriting this code in Python. |
Private myStack()
Private myStackHeight As Integer
Public Function Push(aValue)
myStackHeight = myStackHeight + 1
ReDim Preserve myStack(myStackHeight)
myStack(myStackHeight) = aValue
End Function
Public Function Pop()
If myStackHeight > 0 Then
Pop = myStack(myStackHeight)
myStackHeight = myStackHeight - 1
Else
MsgBox "Pop: stack is empty!"
End If
End Function
Public Function IsEmpty() As Boolean
IsEmpty = (myStackHeight = 0)
End Function
Property Get Size() As Integer
Size = myStackHeight
End Property
| from collections import deque
stack = deque()
stack.append(value)
value = stack.pop()
not stack
|
Write the same algorithm in Python as shown in this VB implementation. | Private Function totient(ByVal n As Long) As Long
Dim tot As Long: tot = n
Dim i As Long: i = 2
Do While i * i <= n
If n Mod i = 0 Then
Do While True
n = n \ i
If n Mod i <> 0 Then Exit Do
Loop
tot = tot - tot \ i
End If
i = i + IIf(i = 2, 1, 2)
Loop
If n > 1 Then
tot = tot - tot \ n
End If
totient = tot
End Function
Public Sub main()
Debug.Print " n phi prime"
Debug.Print " --------------"
Dim count As Long
Dim tot As Integer, n As Long
For n = 1 To 25
tot = totient(n)
prime = (n - 1 = tot)
count = count - prime
Debug.Print Format(n, "@@"); Format(tot, "@@@@@"); Format(prime, "@@@@@@@@")
Next n
Debug.Print
Debug.Print "Number of primes up to 25 = "; Format(count, "@@@@")
For n = 26 To 100000
count = count - (totient(n) = n - 1)
Select Case n
Case 100, 1000, 10000, 100000
Debug.Print "Number of primes up to"; n; String$(6 - Len(CStr(n)), " "); "="; Format(count, "@@@@@")
Case Else
End Select
Next n
End Sub
| from math import gcd
def φ(n):
return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)
if __name__ == '__main__':
def is_prime(n):
return φ(n) == n - 1
for n in range(1, 26):
print(f" φ({n}) == {φ(n)}{', is prime' if is_prime(n) else ''}")
count = 0
for n in range(1, 10_000 + 1):
count += is_prime(n)
if n in {100, 1000, 10_000}:
print(f"Primes up to {n}: {count}")
|
Convert this VB snippet to Python and keep its semantics consistent. | Sub C_S_If()
Dim A$, B$
A = "Hello"
B = "World"
If A = B Then Debug.Print A & " = " & B
If A = B Then
Debug.Print A & " = " & B
Else
Debug.Print A & " and " & B & " are differents."
End If
If A = B Then
Debug.Print A & " = " & B
Else: Debug.Print A & " and " & B & " are differents."
End If
If A = B Then Debug.Print A & " = " & B _
Else Debug.Print A & " and " & B & " are differents."
If A = B Then Debug.Print A & " = " & B Else Debug.Print A & " and " & B & " are differents."
If A = B Then Debug.Print A & " = " & B Else: Debug.Print A & " and " & B & " are differents."
End Sub
| if x == 0:
foo()
elif x == 1:
bar()
elif x == 2:
baz()
else:
qux()
match x:
0 => foo()
1 => bar()
2 => baz()
_ => qux()
(a) ? b : c
|
Change the following VB code into Python without altering its purpose. | Sub C_S_If()
Dim A$, B$
A = "Hello"
B = "World"
If A = B Then Debug.Print A & " = " & B
If A = B Then
Debug.Print A & " = " & B
Else
Debug.Print A & " and " & B & " are differents."
End If
If A = B Then
Debug.Print A & " = " & B
Else: Debug.Print A & " and " & B & " are differents."
End If
If A = B Then Debug.Print A & " = " & B _
Else Debug.Print A & " and " & B & " are differents."
If A = B Then Debug.Print A & " = " & B Else Debug.Print A & " and " & B & " are differents."
If A = B Then Debug.Print A & " = " & B Else: Debug.Print A & " and " & B & " are differents."
End Sub
| if x == 0:
foo()
elif x == 1:
bar()
elif x == 2:
baz()
else:
qux()
match x:
0 => foo()
1 => bar()
2 => baz()
_ => qux()
(a) ? b : c
|
Ensure the translated Python code behaves exactly like the original VB snippet. | Option Base 1
Public prime As Variant
Public nf As New Collection
Public df As New Collection
Const halt = 20
Private Sub init()
prime = [{2,3,5,7,11,13,17,19,23,29,31}]
End Sub
Private Function factor(f As Long) As Variant
Dim result(10) As Integer
Dim i As Integer: i = 1
Do While f > 1
Do While f Mod prime(i) = 0
f = f \ prime(i)
result(i) = result(i) + 1
Loop
i = i + 1
Loop
factor = result
End Function
Private Function decrement(ByVal a As Variant, b As Variant) As Variant
For i = LBound(a) To UBound(a)
a(i) = a(i) - b(i)
Next i
decrement = a
End Function
Private Function increment(ByVal a As Variant, b As Variant) As Variant
For i = LBound(a) To UBound(a)
a(i) = a(i) + b(i)
Next i
increment = a
End Function
Private Function test(a As Variant, b As Variant)
flag = True
For i = LBound(a) To UBound(a)
If a(i) < b(i) Then
flag = False
Exit For
End If
Next i
test = flag
End Function
Private Function unfactor(x As Variant) As Long
result = 1
For i = LBound(x) To UBound(x)
result = result * prime(i) ^ x(i)
Next i
unfactor = result
End Function
Private Sub compile(program As String)
program = Replace(program, " ", "")
programlist = Split(program, ",")
For Each instruction In programlist
parts = Split(instruction, "/")
nf.Add factor(Val(parts(0)))
df.Add factor(Val(parts(1)))
Next instruction
End Sub
Private Function run(x As Long) As Variant
n = factor(x)
counter = 0
Do While True
For i = 1 To df.Count
If test(n, df(i)) Then
n = increment(decrement(n, df(i)), nf(i))
Exit For
End If
Next i
Debug.Print unfactor(n);
counter = counter + 1
If num = 31 Or counter >= halt Then Exit Do
Loop
Debug.Print
run = n
End Function
Private Function steps(x As Variant) As Variant
For i = 1 To df.Count
If test(x, df(i)) Then
x = increment(decrement(x, df(i)), nf(i))
Exit For
End If
Next i
steps = x
End Function
Private Function is_power_of_2(x As Variant) As Boolean
flag = True
For i = LBound(x) + 1 To UBound(x)
If x(i) > 0 Then
flag = False
Exit For
End If
Next i
is_power_of_2 = flag
End Function
Private Function filter_primes(x As Long, max As Integer) As Long
n = factor(x)
i = 0: iterations = 0
Do While i < max
If is_power_of_2(steps(n)) Then
Debug.Print n(1);
i = i + 1
End If
iterations = iterations + 1
Loop
Debug.Print
filter_primes = iterations
End Function
Public Sub main()
init
compile ("17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1")
Debug.Print "First 20 results:"
output = run(2)
Debug.Print "First 30 primes:"
Debug.Print "after"; filter_primes(2, 30); "iterations."
End Sub
| from fractions import Fraction
def fractran(n, fstring='17 / 91, 78 / 85, 19 / 51, 23 / 38, 29 / 33,'
'77 / 29, 95 / 23, 77 / 19, 1 / 17, 11 / 13,'
'13 / 11, 15 / 14, 15 / 2, 55 / 1'):
flist = [Fraction(f) for f in fstring.replace(' ', '').split(',')]
n = Fraction(n)
while True:
yield n.numerator
for f in flist:
if (n * f).denominator == 1:
break
else:
break
n *= f
if __name__ == '__main__':
n, m = 2, 15
print('First %i members of fractran(%i):\n ' % (m, n) +
', '.join(str(f) for f,i in zip(fractran(n), range(m))))
|
Port the provided VB code into Python while preserving the original functionality. | type TSettings extends QObject
FullName as string
FavouriteFruit as string
NeedSpelling as integer
SeedsRemoved as integer
OtherFamily as QStringlist
Constructor
FullName = ""
FavouriteFruit = ""
NeedSpelling = 0
SeedsRemoved = 0
OtherFamily.clear
end constructor
end type
Dim Settings as TSettings
dim ConfigList as QStringList
dim x as integer
dim StrLine as string
dim StrPara as string
dim StrData as string
function Trim$(Expr as string) as string
Result = Rtrim$(Ltrim$(Expr))
end function
Sub ConfigOption(PData as string)
dim x as integer
for x = 1 to tally(PData, ",") +1
Settings.OtherFamily.AddItems Trim$(field$(PData, "," ,x))
next
end sub
Function ConfigBoolean(PData as string) as integer
PData = Trim$(PData)
Result = iif(lcase$(PData)="true" or PData="1" or PData="", 1, 0)
end function
sub ReadSettings
ConfigList.LoadFromFile("Rosetta.cfg")
ConfigList.text = REPLACESUBSTR$(ConfigList.text,"="," ")
for x = 0 to ConfigList.ItemCount -1
StrLine = Trim$(ConfigList.item(x))
StrPara = Trim$(field$(StrLine," ",1))
StrData = Trim$(lTrim$(StrLine - StrPara))
Select case UCase$(StrPara)
case "FULLNAME" : Settings.FullName = StrData
case "FAVOURITEFRUIT" : Settings.FavouriteFruit = StrData
case "NEEDSPEELING" : Settings.NeedSpelling = ConfigBoolean(StrData)
case "SEEDSREMOVED" : Settings.SeedsRemoved = ConfigBoolean(StrData)
case "OTHERFAMILY" : Call ConfigOption(StrData)
end select
next
end sub
Call ReadSettings
| def readconf(fn):
ret = {}
with file(fn) as fp:
for line in fp:
line = line.strip()
if not line or line.startswith('
boolval = True
if line.startswith(';'):
line = line.lstrip(';')
if len(line.split()) != 1: continue
boolval = False
bits = line.split(None, 1)
if len(bits) == 1:
k = bits[0]
v = boolval
else:
k, v = bits
ret[k.lower()] = v
return ret
if __name__ == '__main__':
import sys
conf = readconf(sys.argv[1])
for k, v in sorted(conf.items()):
print k, '=', v
|
Can you help me rewrite this code in Python instead of VB, keeping it the same logically? | Imports System
Module Sorting_Using_a_Custom_Comparator
Function CustomComparator(ByVal x As String, ByVal y As String) As Integer
Dim result As Integer
result = y.Length - x.Length
If result = 0 Then
result = String.Compare(x, y, True)
End If
Return result
End Function
Sub Main()
Dim strings As String() = {"test", "Zoom", "strings", "a"}
Array.Sort(strings, New Comparison(Of String)(AddressOf CustomComparator))
End Sub
End Module
| strings = "here are Some sample strings to be sorted".split()
def mykey(x):
return -len(x), x.upper()
print sorted(strings, key=mykey)
|
Preserve the algorithm and functionality while converting the code from VB to Python. | VERSION 5.00
Begin VB.Form Form1
Begin VB.Timer Timer1
Interval = 250
End
Begin VB.Label Label1
AutoSize = -1
Caption = "Hello World! "
End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Private goRight As Boolean
Private Sub Label1_Click()
goRight = Not goRight
End Sub
Private Sub Timer1_Timer()
If goRight Then
x = Mid(Label1.Caption, 2) & Left(Label1.Caption, 1)
Else
x = Right(Label1.Caption, 1) & Left(Label1.Caption, Len(Label1.Caption) - 1)
End If
Label1.Caption = x
End Sub
| txt = "Hello, world! "
left = True
def draw():
global txt
background(128)
text(txt, 10, height / 2)
if frameCount % 10 == 0:
if (left):
txt = rotate(txt, 1)
else:
txt = rotate(txt, -1)
println(txt)
def mouseReleased():
global left
left = not left
def rotate(text, startIdx):
rotated = text[startIdx:] + text[:startIdx]
return rotated
|
Preserve the algorithm and functionality while converting the code from VB to Python. | Module ListComp
Sub Main()
Dim ts = From a In Enumerable.Range(1, 20) _
From b In Enumerable.Range(a, 21 - a) _
From c In Enumerable.Range(b, 21 - b) _
Where a * a + b * b = c * c _
Select New With { a, b, c }
For Each t In ts
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c)
Next
End Sub
End Module
| [(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]
|
Please provide an equivalent version of this VB code in Python. | Function Selection_Sort(s)
arr = Split(s,",")
For i = 0 To UBound(arr)
For j = i To UBound(arr)
temp = arr(i)
If arr(j) < arr(i) Then
arr(i) = arr(j)
arr(j) = temp
End If
Next
Next
Selection_Sort = (Join(arr,","))
End Function
WScript.StdOut.Write "Pre-Sort" & vbTab & "Sorted"
WScript.StdOut.WriteLine
WScript.StdOut.Write "3,2,5,4,1" & vbTab & Selection_Sort("3,2,5,4,1")
WScript.StdOut.WriteLine
WScript.StdOut.Write "c,e,b,a,d" & vbTab & Selection_Sort("c,e,b,a,d")
| def selection_sort(lst):
for i, e in enumerate(lst):
mn = min(range(i,len(lst)), key=lst.__getitem__)
lst[i], lst[mn] = lst[mn], e
return lst
|
Rewrite this program in Python while keeping its functionality equivalent to the VB version. | Function Selection_Sort(s)
arr = Split(s,",")
For i = 0 To UBound(arr)
For j = i To UBound(arr)
temp = arr(i)
If arr(j) < arr(i) Then
arr(i) = arr(j)
arr(j) = temp
End If
Next
Next
Selection_Sort = (Join(arr,","))
End Function
WScript.StdOut.Write "Pre-Sort" & vbTab & "Sorted"
WScript.StdOut.WriteLine
WScript.StdOut.Write "3,2,5,4,1" & vbTab & Selection_Sort("3,2,5,4,1")
WScript.StdOut.WriteLine
WScript.StdOut.Write "c,e,b,a,d" & vbTab & Selection_Sort("c,e,b,a,d")
| def selection_sort(lst):
for i, e in enumerate(lst):
mn = min(range(i,len(lst)), key=lst.__getitem__)
lst[i], lst[mn] = lst[mn], e
return lst
|
Convert the following code from VB to Python, ensuring the logic remains intact. | Option Explicit
Sub Main()
Dim arr, i
arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next
Debug.Print Join(arr, ", ")
End Sub
Private Function Fibonacci(N) As Variant
If N <= 1 Then
Fibonacci = N
Else
Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)
End If
End Function
| def square(n):
return n * n
numbers = [1, 3, 5, 7]
squares1 = [square(n) for n in numbers]
squares2a = map(square, numbers)
squares2b = map(lambda x: x*x, numbers)
squares3 = [n * n for n in numbers]
isquares1 = (n * n for n in numbers)
import itertools
isquares2 = itertools.imap(square, numbers)
|
Port the following code from VB to Python with equivalent syntax and logic. | Option Explicit
Sub Main()
Dim arr, i
arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next
Debug.Print Join(arr, ", ")
End Sub
Private Function Fibonacci(N) As Variant
If N <= 1 Then
Fibonacci = N
Else
Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)
End If
End Function
| def square(n):
return n * n
numbers = [1, 3, 5, 7]
squares1 = [square(n) for n in numbers]
squares2a = map(square, numbers)
squares2b = map(lambda x: x*x, numbers)
squares3 = [n * n for n in numbers]
isquares1 = (n * n for n in numbers)
import itertools
isquares2 = itertools.imap(square, numbers)
|
Change the programming language of this snippet from VB to Python without modifying what it does. | Public Sub case_sensitivity()
Dim DOG As String
DOG = "Benjamin"
DOG = "Samba"
DOG = "Bernie"
Debug.Print "There is just one dog named " & DOG
End Sub
| >>> dog = 'Benjamin'; Dog = 'Samba'; DOG = 'Bernie'
>>> print ('The three dogs are named ',dog,', ',Dog,', and ',DOG)
The three dogs are named Benjamin , Samba , and Bernie
>>>
|
Please provide an equivalent version of this VB code in Python. | Option Explicit
Const strName As String = "MyFileText.txt"
Const Text As String = "(Over)write a file so that it contains a string. " & vbCrLf & _
"The reverse of Read entire file—for when you want to update or " & vbCrLf & _
"create a file which you would read in its entirety all at once."
Sub Main()
Dim Nb As Integer
Nb = FreeFile
Open "C:\Users\" & Environ("username") & "\Desktop\" & strName For Output As #Nb
Print #1, Text
Close #Nb
End Sub
| with open(filename, 'w') as f:
f.write(data)
|
Can you help me rewrite this code in Python instead of VB, keeping it the same logically? | Public OutConsole As Scripting.TextStream
For i = 0 To 4
For j = 0 To i
OutConsole.Write "*"
Next j
OutConsole.WriteLine
Next i
| for i in 1..5:
for j in 1..i:
stdout.write("*")
echo("")
|
Change the following VB code into Python without altering its purpose. | Public OutConsole As Scripting.TextStream
For i = 0 To 4
For j = 0 To i
OutConsole.Write "*"
Next j
OutConsole.WriteLine
Next i
| for i in 1..5:
for j in 1..i:
stdout.write("*")
echo("")
|
Maintain the same structure and functionality when rewriting this code in Python. | 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 sier(lev,lgth)
dim i
if lev=1 then
for i=1 to 3
x.fw lgth
x.lt 2
next
else
sier lev-1,lgth\2
x.fw lgth\2
sier lev-1,lgth\2
x.bw lgth\2
x.lt 1
x.fw lgth\2
x.rt 1
sier lev-1,lgth\2
x.lt 1
x.bw lgth\2
x.rt 1
end if
end sub
dim x
set x=new turtle
x.iangle=60
x.orient=0
x.incr=10
x.x=100:x.y=100
sier 7,64
set x=nothing
|
import turtle as t
def sier(n,length):
if n == 0:
return
for i in range(3):
sier(n - 1, length / 2)
t.fd(length)
t.rt(120)
|
Keep all operations the same but rewrite the snippet in Python. | 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 sier(lev,lgth)
dim i
if lev=1 then
for i=1 to 3
x.fw lgth
x.lt 2
next
else
sier lev-1,lgth\2
x.fw lgth\2
sier lev-1,lgth\2
x.bw lgth\2
x.lt 1
x.fw lgth\2
x.rt 1
sier lev-1,lgth\2
x.lt 1
x.bw lgth\2
x.rt 1
end if
end sub
dim x
set x=new turtle
x.iangle=60
x.orient=0
x.incr=10
x.x=100:x.y=100
sier 7,64
set x=nothing
|
import turtle as t
def sier(n,length):
if n == 0:
return
for i in range(3):
sier(n - 1, length / 2)
t.fd(length)
t.rt(120)
|
Maintain the same structure and functionality when rewriting this code in Python. |
Function noncontsubseq(l)
Dim i, j, g, n, r, s, w, m
Dim a, b, c
n = Ubound(l)
For s = 0 To n-2
For g = s+1 To n-1
a = "["
For i = s To g-1
a = a & l(i) & ", "
Next
For w = 1 To n-g
r = n+1-g-w
For i = 1 To 2^r-1 Step 2
b = a
For j = 0 To r-1
If i And 2^j Then b=b & l(g+w+j) & ", "
Next
c = (Left(b, Len(b)-1))
WScript.Echo Left(c, Len(c)-1) & "]"
m = m+1
Next
Next
Next
Next
noncontsubseq = m
End Function
list = Array("1", "2", "3", "4")
WScript.Echo "List: [" & Join(list, ", ") & "]"
nn = noncontsubseq(list)
WScript.Echo nn & " non-continuous subsequences"
| def ncsub(seq, s=0):
if seq:
x = seq[:1]
xs = seq[1:]
p2 = s % 2
p1 = not p2
return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + p2)
else:
return [[]] if s >= 3 else []
|
Port the provided VB code into Python while preserving the original functionality. | Function IsPrime(x As Long) As Boolean
Dim i As Long
If x Mod 2 = 0 Then
Exit Function
Else
For i = 3 To Int(Sqr(x)) Step 2
If x Mod i = 0 Then Exit Function
Next i
End If
IsPrime = True
End Function
Function TwinPrimePairs(max As Long) As Long
Dim p1 As Boolean, p2 As Boolean, count As Long, i As Long
p2 = True
For i = 5 To max Step 2
p1 = p2
p2 = IsPrime(i)
If p1 And p2 Then count = count + 1
Next i
TwinPrimePairs = count
End Function
Sub Test(x As Long)
Debug.Print "Twin prime pairs below" + Str(x) + ":" + Str(TwinPrimePairs(x))
End Sub
Sub Main()
Test 10
Test 100
Test 1000
Test 10000
Test 100000
Test 1000000
Test 10000000
End Sub
| primes = [2, 3, 5, 7, 11, 13, 17, 19]
def count_twin_primes(limit: int) -> int:
global primes
if limit > primes[-1]:
ram_limit = primes[-1] + 90000000 - len(primes)
reasonable_limit = min(limit, primes[-1] ** 2, ram_limit) - 1
while reasonable_limit < limit:
ram_limit = primes[-1] + 90000000 - len(primes)
if ram_limit > primes[-1]:
reasonable_limit = min(limit, primes[-1] ** 2, ram_limit)
else:
reasonable_limit = min(limit, primes[-1] ** 2)
sieve = list({x for prime in primes for x in
range(primes[-1] + prime - (primes[-1] % prime), reasonable_limit, prime)})
primes += [x - 1 for i, x in enumerate(sieve) if i and x - 1 != sieve[i - 1] and x - 1 < limit]
count = len([(x, y) for (x, y) in zip(primes, primes[1:]) if x + 2 == y])
return count
def test(limit: int):
count = count_twin_primes(limit)
print(f"Number of twin prime pairs less than {limit} is {count}\n")
test(10)
test(100)
test(1000)
test(10000)
test(100000)
test(1000000)
test(10000000)
test(100000000)
|
Generate a Python translation of this VB snippet without changing its computational steps. | Public Sub roots_of_unity()
For n = 2 To 9
Debug.Print n; "th roots of 1:"
For r00t = 0 To n - 1
Debug.Print " Root "; r00t & ": "; WorksheetFunction.Complex(Cos(2 * WorksheetFunction.Pi() * r00t / n), _
Sin(2 * WorksheetFunction.Pi() * r00t / n))
Next r00t
Debug.Print
Next n
End Sub
| import cmath
class Complex(complex):
def __repr__(self):
rp = '%7.5f' % self.real if not self.pureImag() else ''
ip = '%7.5fj' % self.imag if not self.pureReal() else ''
conj = '' if (
self.pureImag() or self.pureReal() or self.imag < 0.0
) else '+'
return '0.0' if (
self.pureImag() and self.pureReal()
) else rp + conj + ip
def pureImag(self):
return abs(self.real) < 0.000005
def pureReal(self):
return abs(self.imag) < 0.000005
def croots(n):
if n <= 0:
return None
return (Complex(cmath.rect(1, 2 * k * cmath.pi / n)) for k in range(n))
for nr in range(2, 11):
print(nr, list(croots(nr)))
|
Write the same algorithm in Python as shown in this VB implementation. | Imports System
Imports System.Console
Imports BI = System.Numerics.BigInteger
Module Module1
Dim a As Decimal, mx As Decimal = 1E28D, hm As Decimal = 1E14D
Structure bd
Public hi, lo As Decimal
End Structure
Function toStr(ByVal a As bd, ByVal Optional comma As Boolean = False) As String
Dim r As String = If(a.hi = 0, String.Format("{0:0}", a.lo),
String.Format("{0:0}{1:" & New String("0"c, 28) & "}", a.hi, a.lo))
If Not comma Then Return r
Dim rc As String = ""
For i As Integer = r.Length - 3 To 0 Step -3
rc = "," & r.Substring(i, 3) & rc : Next
toStr = r.Substring(0, r.Length Mod 3) & rc
toStr = toStr.Substring(If(toStr.Chars(0) = "," , 1, 0))
End Function
Function Pow_dec(ByVal bas As Decimal, ByVal exp As UInteger) As Decimal
If exp = 0 Then Pow_dec = 1D else Pow_dec = Pow_dec(bas, exp >> 1) : _
Pow_dec *= Pow_dec : If (exp And 1) <> 0 Then Pow_dec *= bas
End Function
Sub Main(ByVal args As String())
For p As UInteger = 64 To 95 - 1 Step 30
Dim y As bd, x As bd : a = Pow_dec(2D, p)
WriteLine("The square of (2^{0}): {1,38:n0}", p, a)
x.hi = Math.Floor(a / hm) : x.lo = a Mod hm
Dim BS As BI = BI.Pow(CType(a, BI), 2)
y.lo = x.lo * x.lo : y.hi = x.hi * x.hi
a = x.hi * x.lo * 2D
y.hi += Math.Floor(a / hm) : y.lo += (a Mod hm) * hm
While y.lo > mx : y.lo -= mx : y.hi += 1 : End While
WriteLine(" is {0,75} (which {1} match the BigInteger computation)" & vbLf,
toStr(y, True), If(BS.ToString() = toStr(y), "does", "fails to"))
Next
End Sub
End Module
|
print 2**64*2**64
|
Convert this VB snippet to Python and keep its semantics consistent. | Imports System.Numerics
Module Module1
Sub Fun(ByRef a As BigInteger, ByRef b As BigInteger, c As Integer)
Dim t As BigInteger = a : a = b : b = b * c + t
End Sub
Sub SolvePell(n As Integer, ByRef a As BigInteger, ByRef b As BigInteger)
Dim x As Integer = Math.Sqrt(n), y As Integer = x, z As Integer = 1, r As Integer = x << 1,
e1 As BigInteger = 1, e2 As BigInteger = 0, f1 As BigInteger = 0, f2 As BigInteger = 1
While True
y = r * z - y : z = (n - y * y) / z : r = (x + y) / z
Fun(e1, e2, r) : Fun(f1, f2, r) : a = f2 : b = e2 : Fun(b, a, x)
If a * a - n * b * b = 1 Then Exit Sub
End While
End Sub
Sub Main()
Dim x As BigInteger, y As BigInteger
For Each n As Integer In {61, 109, 181, 277}
SolvePell(n, x, y)
Console.WriteLine("x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}", n, x, y)
Next
End Sub
End Module
| import math
def solvePell(n):
x = int(math.sqrt(n))
y, z, r = x, 1, x << 1
e1, e2 = 1, 0
f1, f2 = 0, 1
while True:
y = r * z - y
z = (n - y * y) // z
r = (x + y) // z
e1, e2 = e2, e1 + e2 * r
f1, f2 = f2, f1 + f2 * r
a, b = f2 * x + e2, f2
if a * a - n * b * b == 1:
return a, b
for n in [61, 109, 181, 277]:
x, y = solvePell(n)
print("x^2 - %3d * y^2 = 1 for x = %27d and y = %25d" % (n, x, y))
|
Change the programming language of this snippet from VB to Python without modifying what it does. | Option Explicit
Sub Main_Bulls_and_cows()
Dim strNumber As String, strInput As String, strMsg As String, strTemp As String
Dim boolEnd As Boolean
Dim lngCpt As Long
Dim i As Byte, bytCow As Byte, bytBull As Byte
Const NUMBER_OF_DIGITS As Byte = 4
Const MAX_LOOPS As Byte = 25
strNumber = Create_Number(NUMBER_OF_DIGITS)
Do
bytBull = 0: bytCow = 0: lngCpt = lngCpt + 1
If lngCpt > MAX_LOOPS Then strMsg = "Max of loops... Sorry you loose!": Exit Do
strInput = AskToUser(NUMBER_OF_DIGITS)
If strInput = "Exit Game" Then strMsg = "User abort": Exit Do
For i = 1 To Len(strNumber)
If Mid(strNumber, i, 1) = Mid(strInput, i, 1) Then
bytBull = bytBull + 1
ElseIf InStr(strNumber, Mid(strInput, i, 1)) > 0 Then
bytCow = bytCow + 1
End If
Next i
If bytBull = Len(strNumber) Then
boolEnd = True: strMsg = "You win in " & lngCpt & " loops!"
Else
strTemp = strTemp & vbCrLf & "With : " & strInput & " ,you have : " & bytBull & " bulls," & bytCow & " cows."
MsgBox strTemp
End If
Loop While Not boolEnd
MsgBox strMsg
End Sub
Function Create_Number(NbDigits As Byte) As String
Dim myColl As New Collection
Dim strTemp As String
Dim bytAlea As Byte
Randomize
Do
bytAlea = Int((Rnd * 9) + 1)
On Error Resume Next
myColl.Add CStr(bytAlea), CStr(bytAlea)
If Err <> 0 Then
On Error GoTo 0
Else
strTemp = strTemp & CStr(bytAlea)
End If
Loop While Len(strTemp) < NbDigits
Create_Number = strTemp
End Function
Function AskToUser(NbDigits As Byte) As String
Dim boolGood As Boolean, strIn As String, i As Byte, NbDiff As Byte
Do While Not boolGood
strIn = InputBox("Enter your number (" & NbDigits & " digits)", "Number")
If StrPtr(strIn) = 0 Then strIn = "Exit Game": Exit Do
If strIn <> "" Then
If Len(strIn) = NbDigits Then
NbDiff = 0
For i = 1 To Len(strIn)
If Len(Replace(strIn, Mid(strIn, i, 1), "")) < NbDigits - 1 Then
NbDiff = 1
Exit For
End If
Next i
If NbDiff = 0 Then boolGood = True
End If
End If
Loop
AskToUser = strIn
End Function
|
import random
digits = '123456789'
size = 4
chosen = ''.join(random.sample(digits,size))
print % (size, size)
guesses = 0
while True:
guesses += 1
while True:
guess = raw_input('\nNext guess [%i]: ' % guesses).strip()
if len(guess) == size and \
all(char in digits for char in guess) \
and len(set(guess)) == size:
break
print "Problem, try again. You need to enter %i unique digits from 1 to 9" % size
if guess == chosen:
print '\nCongratulations you guessed correctly in',guesses,'attempts'
break
bulls = cows = 0
for i in range(size):
if guess[i] == chosen[i]:
bulls += 1
elif guess[i] in chosen:
cows += 1
print ' %i Bulls\n %i Cows' % (bulls, cows)
|
Port the following code from VB to Python with equivalent syntax and logic. | Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
sortable.Shuffle()
Dim swapped As Boolean
Do
Dim index, bound As Integer
bound = sortable.Ubound
While index < bound
If sortable(index) > sortable(index + 1) Then
Dim s As Integer = sortable(index)
sortable.Remove(index)
sortable.Insert(index + 1, s)
swapped = True
End If
index = index + 1
Wend
Loop Until Not swapped
| def bubble_sort(seq):
changed = True
while changed:
changed = False
for i in range(len(seq) - 1):
if seq[i] > seq[i+1]:
seq[i], seq[i+1] = seq[i+1], seq[i]
changed = True
return seq
if __name__ == "__main__":
from random import shuffle
testset = [_ for _ in range(100)]
testcase = testset.copy()
shuffle(testcase)
assert testcase != testset
bubble_sort(testcase)
assert testcase == testset
|
Keep all operations the same but rewrite the snippet in Python. | Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
sortable.Shuffle()
Dim swapped As Boolean
Do
Dim index, bound As Integer
bound = sortable.Ubound
While index < bound
If sortable(index) > sortable(index + 1) Then
Dim s As Integer = sortable(index)
sortable.Remove(index)
sortable.Insert(index + 1, s)
swapped = True
End If
index = index + 1
Wend
Loop Until Not swapped
| def bubble_sort(seq):
changed = True
while changed:
changed = False
for i in range(len(seq) - 1):
if seq[i] > seq[i+1]:
seq[i], seq[i+1] = seq[i+1], seq[i]
changed = True
return seq
if __name__ == "__main__":
from random import shuffle
testset = [_ for _ in range(100)]
testcase = testset.copy()
shuffle(testcase)
assert testcase != testset
bubble_sort(testcase)
assert testcase == testset
|
Keep all operations the same but rewrite the snippet in Python. | Sub WriteToFile(input As FolderItem, output As FolderItem)
Dim tis As TextInputStream
Dim tos As TextOutputStream
tis = tis.Open(input)
tos = tos.Create(output)
While Not tis.EOF
tos.WriteLine(tis.ReadLine)
Wend
tis.Close
tos.Close
End Sub
| import shutil
shutil.copyfile('input.txt', 'output.txt')
|
Port the following code from VB to Python with equivalent syntax and logic. | Sub WriteToFile(input As FolderItem, output As FolderItem)
Dim tis As TextInputStream
Dim tos As TextOutputStream
tis = tis.Open(input)
tos = tos.Create(output)
While Not tis.EOF
tos.WriteLine(tis.ReadLine)
Wend
tis.Close
tos.Close
End Sub
| import shutil
shutil.copyfile('input.txt', 'output.txt')
|
Port the provided VB code into Python while preserving the original functionality. | START:
INPUT "Enter two integers (a,b):"; a!, b!
IF a = 0 THEN END
IF b = 0 THEN
PRINT "Second integer is zero. Zero not allowed for Quotient or Remainder."
GOTO START
END IF
PRINT
PRINT " Sum = "; a + b
PRINT " Difference = "; a - b
PRINT " Product = "; a * b
PRINT "Integer Quotient = "; a \ b, , "* Rounds toward 0."
PRINT " Remainder = "; a MOD b, , "* Sign matches first operand."
PRINT " Exponentiation = "; a ^ b
PRINT
INPUT "Again? (y/N)"; a$
IF UCASE$(a$) = "Y" THEN CLS: GOTO START
CLS
END
| x = int(raw_input("Number 1: "))
y = int(raw_input("Number 2: "))
print "Sum: %d" % (x + y)
print "Difference: %d" % (x - y)
print "Product: %d" % (x * y)
print "Quotient: %d" % (x / y)
print "Remainder: %d" % (x % y)
print "Quotient: %d with Remainder: %d" % divmod(x, y)
print "Power: %d" % x**y
raw_input( )
|
Ensure the translated Python code behaves exactly like the original VB snippet. | Function transpose(m As Variant) As Variant
transpose = WorksheetFunction.transpose(m)
End Function
| m=((1, 1, 1, 1),
(2, 4, 8, 16),
(3, 9, 27, 81),
(4, 16, 64, 256),
(5, 25,125, 625))
print(zip(*m))
|
Change the programming language of this snippet from VB to Python without modifying what it does. | Private Function a(i As Variant) As Boolean
Debug.Print "a: "; i = 1,
a = i
End Function
Private Function b(j As Variant) As Boolean
Debug.Print "b: "; j = 1;
b = j
End Function
Public Sub short_circuit()
Dim x As Boolean, y As Boolean
Debug.Print "=====AND=====" & vbCrLf
For p = 0 To 1
For q = 0 To 1
If a(p) Then
x = b(q)
End If
Debug.Print " = x"
Next q
Debug.Print
Next p
Debug.Print "======OR=====" & vbCrLf
For p = 0 To 1
For q = 0 To 1
If Not a(p) Then
x = b(q)
End If
Debug.Print " = x"
Next q
Debug.Print
Next p
Debug.Print
End Sub
| >>> def a(answer):
print("
return answer
>>> def b(answer):
print("
return answer
>>> for i in (False, True):
for j in (False, True):
print ("\nCalculating: x = a(i) and b(j)")
x = a(i) and b(j)
print ("Calculating: y = a(i) or b(j)")
y = a(i) or b(j)
Calculating: x = a(i) and b(j)
Calculating: y = a(i) or b(j)
Calculating: x = a(i) and b(j)
Calculating: y = a(i) or b(j)
Calculating: x = a(i) and b(j)
Calculating: y = a(i) or b(j)
Calculating: x = a(i) and b(j)
Calculating: y = a(i) or b(j)
|
Convert the following code from VB to Python, ensuring the logic remains intact. | Option Explicit
Sub Main()
Debug.Print "The limit is : " & Limite_Recursivite(0)
End Sub
Function Limite_Recursivite(Cpt As Long) As Long
Cpt = Cpt + 1
On Error Resume Next
Limite_Recursivite Cpt
On Error GoTo 0
Limite_Recursivite = Cpt
End Function
| import sys
print(sys.getrecursionlimit())
|
Generate an equivalent Python version of this VB code. | Option Explicit
Sub Main()
Debug.Print "The limit is : " & Limite_Recursivite(0)
End Sub
Function Limite_Recursivite(Cpt As Long) As Long
Cpt = Cpt + 1
On Error Resume Next
Limite_Recursivite Cpt
On Error GoTo 0
Limite_Recursivite = Cpt
End Function
| import sys
print(sys.getrecursionlimit())
|
Write the same algorithm in Python as shown in this VB implementation. | Imports System.Drawing.Imaging
Public Class frmSnowExercise
Dim bRunning As Boolean = True
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint _
Or ControlStyles.OptimizedDoubleBuffer, True)
UpdateStyles()
FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle
MaximizeBox = False
Width = 320 + Size.Width - ClientSize.Width
Height = 240 + Size.Height - ClientSize.Height
Show()
Activate()
Application.DoEvents()
RenderLoop()
Close()
End Sub
Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As _
System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
If e.KeyChar = ChrW(Keys.Escape) Then bRunning = False
End Sub
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As _
System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
e.Cancel = bRunning
bRunning = False
End Sub
Private Sub RenderLoop()
Const cfPadding As Single = 5.0F
Dim b As New Bitmap(ClientSize.Width, ClientSize.Width,
PixelFormat.Format32bppArgb)
Dim g As Graphics = Graphics.FromImage(b)
Dim r As New Random(Now.Millisecond)
Dim oBMPData As BitmapData = Nothing
Dim oPixels() As Integer = Nothing
Dim oBlackWhite() As Integer = {Color.White.ToArgb, Color.Black.ToArgb}
Dim oStopwatch As New Stopwatch
Dim fElapsed As Single = 0.0F
Dim iLoops As Integer = 0
Dim sFPS As String = "0.0 FPS"
Dim oFPSSize As SizeF = g.MeasureString(sFPS, Font)
Dim oFPSBG As RectangleF = New RectangleF(ClientSize.Width - cfPadding -
oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)
g.Clear(Color.Black)
oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),
ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)
Array.Resize(oPixels, b.Width * b.Height)
Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0,
oPixels, 0, oPixels.Length)
b.UnlockBits(oBMPData)
Do
fElapsed += oStopwatch.ElapsedMilliseconds / 1000.0F
oStopwatch.Reset() : oStopwatch.Start()
iLoops += 1
If fElapsed >= 1.0F Then
sFPS = (iLoops / fElapsed).ToString("0.0") & " FPS"
oFPSSize = g.MeasureString(sFPS, Font)
oFPSBG = New RectangleF(ClientSize.Width - cfPadding -
oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)
fElapsed -= 1.0F
iLoops = 0
End If
For i As Integer = 0 To oPixels.GetUpperBound(0)
oPixels(i) = oBlackWhite(r.Next(oBlackWhite.Length))
Next
oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),
ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)
Runtime.InteropServices.Marshal.Copy(oPixels, 0, oBMPData.Scan0,
oPixels.Length)
b.UnlockBits(oBMPData)
g.FillRectangle(Brushes.Black, oFPSBG)
g.DrawString(sFPS, Font, Brushes.Yellow, oFPSBG.Left, oFPSBG.Top)
BackgroundImage = b
Invalidate(ClientRectangle)
Application.DoEvents()
Loop While bRunning
End Sub
End Class
| black = color(0)
white = color(255)
def setup():
size(320, 240)
def draw():
loadPixels()
for i in range(len(pixels)):
if random(1) < 0.5:
pixels[i] = black
else:
pixels[i] = white
updatePixels()
fill(0, 128)
rect(0, 0, 60, 20)
fill(255)
text(frameRate, 5, 15)
|
Produce a language-to-language conversion: from VB to Python, same semantics. |
GraphicsWindow.DrawText(10, 10, "Hit any key to dump.")
GraphicsWindow.KeyDown = OnKeyDown
Sub OnKeyDown
TextWindow.WriteLine(GraphicsWindow.LastKey)
EndSub
|
try:
from msvcrt import getch
except ImportError:
def getch():
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
print "Press Y or N to continue"
while True:
char = getch()
if char.lower() in ("y", "n"):
print char
break
|
Please provide an equivalent version of this VB code in Python. |
GraphicsWindow.DrawText(10, 10, "Hit any key to dump.")
GraphicsWindow.KeyDown = OnKeyDown
Sub OnKeyDown
TextWindow.WriteLine(GraphicsWindow.LastKey)
EndSub
|
try:
from msvcrt import getch
except ImportError:
def getch():
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
print "Press Y or N to continue"
while True:
char = getch()
if char.lower() in ("y", "n"):
print char
break
|
Port the following code from VB to Python with equivalent syntax and logic. |
GraphicsWindow.DrawText(10, 10, "Hit any key to dump.")
GraphicsWindow.KeyDown = OnKeyDown
Sub OnKeyDown
TextWindow.WriteLine(GraphicsWindow.LastKey)
EndSub
|
try:
from msvcrt import getch
except ImportError:
def getch():
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
print "Press Y or N to continue"
while True:
char = getch()
if char.lower() in ("y", "n"):
print char
break
|
Generate an equivalent Python version of this VB code. | Private Function Factors(x As Long) As String
Application.Volatile
Dim i As Long
Dim cooresponding_factors As String
Factors = 1
corresponding_factors = x
For i = 2 To Sqr(x)
If x Mod i = 0 Then
Factors = Factors & ", " & i
If i <> x / i Then corresponding_factors = x / i & ", " & corresponding_factors
End If
Next i
If x <> 1 Then Factors = Factors & ", " & corresponding_factors
End Function
Private Function is_perfect(n As Long)
fs = Split(Factors(n), ", ")
Dim f() As Long
ReDim f(UBound(fs))
For i = 0 To UBound(fs)
f(i) = Val(fs(i))
Next i
is_perfect = WorksheetFunction.Sum(f) - n = n
End Function
Public Sub main()
Dim i As Long
For i = 2 To 100000
If is_perfect(i) Then Debug.Print i
Next i
End Sub
| def perf1(n):
sum = 0
for i in range(1, n):
if n % i == 0:
sum += i
return sum == n
|
Generate an equivalent Python version of this VB code. | Option Base 1
Private Function sq_add(arr As Variant, x As Double) As Variant
Dim res() As Variant
ReDim res(UBound(arr))
For i = 1 To UBound(arr)
res(i) = arr(i) + x
Next i
sq_add = res
End Function
Private Function beadsort(ByVal a As Variant) As Variant
Dim poles() As Variant
ReDim poles(WorksheetFunction.Max(a))
For i = 1 To UBound(a)
For j = 1 To a(i)
poles(j) = poles(j) + 1
Next j
Next i
For j = 1 To UBound(a)
a(j) = 0
Next j
For i = 1 To UBound(poles)
For j = 1 To poles(i)
a(j) = a(j) + 1
Next j
Next i
beadsort = a
End Function
Public Sub main()
Debug.Print Join(beadsort([{5, 3, 1, 7, 4, 1, 1, 20}]), ", ")
End Sub
|
from itertools import zip_longest
def beadsort(l):
return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))
print(beadsort([5,3,1,7,4,1,1]))
|
Generate an equivalent Python version of this VB code. | Imports System.Console
Imports BI = System.Numerics.BigInteger
Module Module1
Dim Implems() As String = {"Built-In", "Recursive", "Iterative"},
powers() As Integer = {5, 4, 3, 2}
Function intPowR(val As BI, exp As BI) As BI
If exp = 0 Then Return 1
Dim ne As BI, vs As BI = val * val
If exp.IsEven Then ne = exp >> 1 : Return If (ne > 1, intPowR(vs, ne), vs)
ne = (exp - 1) >> 1 : Return If (ne > 1, intPowR(vs, ne), vs) * val
End Function
Function intPowI(val As BI, exp As BI) As BI
intPowI = 1 : While (exp > 0) : If Not exp.IsEven Then intPowI *= val
val *= val : exp >>= 1 : End While
End Function
Sub DoOne(title As String, p() As Integer)
Dim st As DateTime = DateTime.Now, res As BI, resStr As String
Select Case (Array.IndexOf(Implems, title))
Case 0 : res = BI.Pow(p(0), CInt(BI.Pow(p(1), CInt(BI.Pow(p(2), p(3))))))
Case 1 : res = intPowR(p(0), intPowR(p(1), intPowR(p(2), p(3))))
Case Else : res = intPowI(p(0), intPowI(p(1), intPowI(p(2), p(3))))
End Select : resStr = res.ToString()
Dim et As TimeSpan = DateTime.Now - st
Debug.Assert(resStr.Length = 183231)
Debug.Assert(resStr.StartsWith("62060698786608744707"))
Debug.Assert(resStr.EndsWith("92256259918212890625"))
WriteLine("n = {0}", String.Join("^", powers))
WriteLine("n = {0}...{1}", resStr.Substring(0, 20), resStr.Substring(resStr.Length - 20, 20))
WriteLine("n digits = {0}", resStr.Length)
WriteLine("{0} elasped: {1} milliseconds." & vblf, title, et.TotalMilliseconds)
End Sub
Sub Main()
For Each itm As String in Implems : DoOne(itm, powers) : Next
If Debugger.IsAttached Then Console.ReadKey()
End Sub
End Module
| >>> y = str( 5**4**3**2 )
>>> print ("5**4**3**2 = %s...%s and has %i digits" % (y[:20], y[-20:], len(y)))
5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits
|
Port the following code from VB to Python with equivalent syntax and logic. | shades = Array(".", ":", "!", "*", "o", "e", "&", "#", "%", "@")
light = Array(30, 30, -50)
Sub Normalize(v)
length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))
v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length
End Sub
Function Dot(x, y)
d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)
If d < 0 Then Dot = -d Else Dot = 0 End If
End Function
Function Ceil(x)
Ceil = Int(x)
If Ceil <> x Then Ceil = Ceil + 1 End if
End Function
Sub DrawSphere(R, k, ambient)
Dim i, j, intensity, inten, b, x, y
Dim vec(3)
For i = Int(-R) to Ceil(R)
x = i + 0.5
line = ""
For j = Int(-2*R) to Ceil(2*R)
y = j / 2 + 0.5
If x * x + y * y <= R*R Then
vec(0) = x
vec(1) = y
vec(2) = Sqr(R * R - x * x - y * y)
Normalize vec
b = dot(light, vec)^k + ambient
intensity = Int((1 - b) * UBound(shades))
If intensity < 0 Then intensity = 0 End If
If intensity >= UBound(shades) Then
intensity = UBound(shades)
End If
line = line & shades(intensity)
Else
line = line & " "
End If
Next
WScript.StdOut.WriteLine line
Next
End Sub
Normalize light
DrawSphere 20, 4, 0.1
DrawSphere 10,2,0.4
| import math
shades = ('.',':','!','*','o','e','&','
def normalize(v):
len = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)
return (v[0]/len, v[1]/len, v[2]/len)
def dot(x,y):
d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
return -d if d < 0 else 0
def draw_sphere(r, k, ambient, light):
for i in range(int(math.floor(-r)),int(math.ceil(r)+1)):
x = i + 0.5
line = ''
for j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):
y = j/2 + 0.5
if x*x + y*y <= r*r:
vec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))
b = dot(light,vec)**k + ambient
intensity = int((1-b)*(len(shades)-1))
line += shades[intensity] if 0 <= intensity < len(shades) else shades[0]
else:
line += ' '
print(line)
light = normalize((30,30,-50))
draw_sphere(20,4,0.1, light)
draw_sphere(10,2,0.4, light)
|
Translate this program into Python but keep the logic exactly as in VB. | shades = Array(".", ":", "!", "*", "o", "e", "&", "#", "%", "@")
light = Array(30, 30, -50)
Sub Normalize(v)
length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))
v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length
End Sub
Function Dot(x, y)
d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)
If d < 0 Then Dot = -d Else Dot = 0 End If
End Function
Function Ceil(x)
Ceil = Int(x)
If Ceil <> x Then Ceil = Ceil + 1 End if
End Function
Sub DrawSphere(R, k, ambient)
Dim i, j, intensity, inten, b, x, y
Dim vec(3)
For i = Int(-R) to Ceil(R)
x = i + 0.5
line = ""
For j = Int(-2*R) to Ceil(2*R)
y = j / 2 + 0.5
If x * x + y * y <= R*R Then
vec(0) = x
vec(1) = y
vec(2) = Sqr(R * R - x * x - y * y)
Normalize vec
b = dot(light, vec)^k + ambient
intensity = Int((1 - b) * UBound(shades))
If intensity < 0 Then intensity = 0 End If
If intensity >= UBound(shades) Then
intensity = UBound(shades)
End If
line = line & shades(intensity)
Else
line = line & " "
End If
Next
WScript.StdOut.WriteLine line
Next
End Sub
Normalize light
DrawSphere 20, 4, 0.1
DrawSphere 10,2,0.4
| import math
shades = ('.',':','!','*','o','e','&','
def normalize(v):
len = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)
return (v[0]/len, v[1]/len, v[2]/len)
def dot(x,y):
d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
return -d if d < 0 else 0
def draw_sphere(r, k, ambient, light):
for i in range(int(math.floor(-r)),int(math.ceil(r)+1)):
x = i + 0.5
line = ''
for j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):
y = j/2 + 0.5
if x*x + y*y <= r*r:
vec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))
b = dot(light,vec)**k + ambient
intensity = int((1-b)*(len(shades)-1))
line += shades[intensity] if 0 <= intensity < len(shades) else shades[0]
else:
line += ' '
print(line)
light = normalize((30,30,-50))
draw_sphere(20,4,0.1, light)
draw_sphere(10,2,0.4, light)
|
Port the provided VB code into Python while preserving the original functionality. | Function gcd(u As Long, v As Long) As Long
Dim t As Long
Do While v
t = u
u = v
v = t Mod v
Loop
gcd = u
End Function
Function lcm(m As Long, n As Long) As Long
lcm = Abs(m * n) / gcd(m, n)
End Function
| >>> import fractions
>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0
>>> lcm(12, 18)
36
>>> lcm(-6, 14)
42
>>> assert lcm(0, 2) == lcm(2, 0) == 0
>>>
|
Rewrite the snippet below in Python so it works the same as the original VB code. | Function gcd(u As Long, v As Long) As Long
Dim t As Long
Do While v
t = u
u = v
v = t Mod v
Loop
gcd = u
End Function
Function lcm(m As Long, n As Long) As Long
lcm = Abs(m * n) / gcd(m, n)
End Function
| >>> import fractions
>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0
>>> lcm(12, 18)
36
>>> lcm(-6, 14)
42
>>> assert lcm(0, 2) == lcm(2, 0) == 0
>>>
|
Change the following VB code into Python without altering its purpose. | Function gcd(u As Long, v As Long) As Long
Dim t As Long
Do While v
t = u
u = v
v = t Mod v
Loop
gcd = u
End Function
Function lcm(m As Long, n As Long) As Long
lcm = Abs(m * n) / gcd(m, n)
End Function
| >>> import fractions
>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0
>>> lcm(12, 18)
36
>>> lcm(-6, 14)
42
>>> assert lcm(0, 2) == lcm(2, 0) == 0
>>>
|
Rewrite this program in Python while keeping its functionality equivalent to the VB version. | Public Sub LoopsBreak()
Dim value As Integer
Randomize
Do While True
value = Int(20 * Rnd)
Debug.Print value
If value = 10 Then Exit Do
Debug.Print Int(20 * Rnd)
Loop
End Sub
| from random import randrange
while True:
a = randrange(20)
print(a)
if a == 10:
break
b = randrange(20)
print(b)
|
Transform the following VB implementation into Python, maintaining the same output and logic. |
Module Module1
Sub Main(Args() As String)
Dim shoTow As Boolean = Environment.GetCommandLineArgs().Count > 1
Dim wta As Integer()() = {
New Integer() {1, 5, 3, 7, 2}, New Integer() {5, 3, 7, 2, 6, 4, 5, 9, 1, 2},
New Integer() {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},
New Integer() {5, 5, 5, 5}, New Integer() {5, 6, 7, 8},
New Integer() {8, 7, 7, 6}, New Integer() {6, 7, 10, 7, 6}}
Dim blk As String,
lf As String = vbLf,
tb = "██", wr = "≈≈", mt = " "
For i As Integer = 0 To wta.Length - 1
Dim bpf As Integer
blk = ""
Do
bpf = 0 : Dim floor As String = ""
For j As Integer = 0 To wta(i).Length - 1
If wta(i)(j) > 0 Then
floor &= tb : wta(i)(j) -= 1 : bpf += 1
Else
floor &= If(j > 0 AndAlso j < wta(i).Length - 1, wr, mt)
End If
Next
If bpf > 0 Then blk = floor & lf & blk
Loop Until bpf = 0
While blk.Contains(mt & wr) : blk = blk.Replace(mt & wr, mt & mt) : End While
While blk.Contains(wr & mt) : blk = blk.Replace(wr & mt, mt & mt) : End While
If shoTow Then Console.Write("{0}{1}", lf, blk)
Console.Write("Block {0} retains {1,2} water units.{2}", i + 1,
(blk.Length - blk.Replace(wr, "").Length) \ 2, lf)
Next
End Sub
End Module
| def water_collected(tower):
N = len(tower)
highest_left = [0] + [max(tower[:n]) for n in range(1,N)]
highest_right = [max(tower[n:N]) for n in range(1,N)] + [0]
water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0)
for n in range(N)]
print("highest_left: ", highest_left)
print("highest_right: ", highest_right)
print("water_level: ", water_level)
print("tower_level: ", tower)
print("total_water: ", sum(water_level))
print("")
return sum(water_level)
towers = [[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
[water_collected(tower) for tower in towers]
|
Translate this program into Python but keep the logic exactly as in VB. | Module Module1
Function Sieve(limit As Long) As List(Of Long)
Dim primes As New List(Of Long) From {2}
Dim c(limit + 1) As Boolean
Dim p = 3L
While True
Dim p2 = p * p
If p2 > limit Then
Exit While
End If
For i = p2 To limit Step 2 * p
c(i) = True
Next
While True
p += 2
If Not c(p) Then
Exit While
End If
End While
End While
For i = 3 To limit Step 2
If Not c(i) Then
primes.Add(i)
End If
Next
Return primes
End Function
Function SquareFree(from As Long, to_ As Long) As List(Of Long)
Dim limit = CType(Math.Sqrt(to_), Long)
Dim primes = Sieve(limit)
Dim results As New List(Of Long)
Dim i = from
While i <= to_
For Each p In primes
Dim p2 = p * p
If p2 > i Then
Exit For
End If
If (i Mod p2) = 0 Then
i += 1
Continue While
End If
Next
results.Add(i)
i += 1
End While
Return results
End Function
ReadOnly TRILLION As Long = 1_000_000_000_000
Sub Main()
Console.WriteLine("Square-free integers from 1 to 145:")
Dim sf = SquareFree(1, 145)
For index = 0 To sf.Count - 1
Dim v = sf(index)
If index > 1 AndAlso (index Mod 20) = 0 Then
Console.WriteLine()
End If
Console.Write("{0,4}", v)
Next
Console.WriteLine()
Console.WriteLine()
Console.WriteLine("Square-free integers from {0} to {1}:", TRILLION, TRILLION + 145)
sf = SquareFree(TRILLION, TRILLION + 145)
For index = 0 To sf.Count - 1
Dim v = sf(index)
If index > 1 AndAlso (index Mod 5) = 0 Then
Console.WriteLine()
End If
Console.Write("{0,14}", v)
Next
Console.WriteLine()
Console.WriteLine()
Console.WriteLine("Number of square-free integers:")
For Each to_ In {100, 1_000, 10_000, 100_000, 1_000_000}
Console.WriteLine(" from 1 to {0} = {1}", to_, SquareFree(1, to_).Count)
Next
End Sub
End Module
| import math
def SquareFree ( _number ) :
max = (int) (math.sqrt ( _number ))
for root in range ( 2, max+1 ):
if 0 == _number % ( root * root ):
return False
return True
def ListSquareFrees( _start, _end ):
count = 0
for i in range ( _start, _end+1 ):
if True == SquareFree( i ):
print ( "{}\t".format(i), end="" )
count += 1
print ( "\n\nTotal count of square-free numbers between {} and {}: {}".format(_start, _end, count))
ListSquareFrees( 1, 100 )
ListSquareFrees( 1000000000000, 1000000000145 )
|
Maintain the same structure and functionality when rewriting this code in Python. | Module Module1
Function Sieve(limit As Long) As List(Of Long)
Dim primes As New List(Of Long) From {2}
Dim c(limit + 1) As Boolean
Dim p = 3L
While True
Dim p2 = p * p
If p2 > limit Then
Exit While
End If
For i = p2 To limit Step 2 * p
c(i) = True
Next
While True
p += 2
If Not c(p) Then
Exit While
End If
End While
End While
For i = 3 To limit Step 2
If Not c(i) Then
primes.Add(i)
End If
Next
Return primes
End Function
Function SquareFree(from As Long, to_ As Long) As List(Of Long)
Dim limit = CType(Math.Sqrt(to_), Long)
Dim primes = Sieve(limit)
Dim results As New List(Of Long)
Dim i = from
While i <= to_
For Each p In primes
Dim p2 = p * p
If p2 > i Then
Exit For
End If
If (i Mod p2) = 0 Then
i += 1
Continue While
End If
Next
results.Add(i)
i += 1
End While
Return results
End Function
ReadOnly TRILLION As Long = 1_000_000_000_000
Sub Main()
Console.WriteLine("Square-free integers from 1 to 145:")
Dim sf = SquareFree(1, 145)
For index = 0 To sf.Count - 1
Dim v = sf(index)
If index > 1 AndAlso (index Mod 20) = 0 Then
Console.WriteLine()
End If
Console.Write("{0,4}", v)
Next
Console.WriteLine()
Console.WriteLine()
Console.WriteLine("Square-free integers from {0} to {1}:", TRILLION, TRILLION + 145)
sf = SquareFree(TRILLION, TRILLION + 145)
For index = 0 To sf.Count - 1
Dim v = sf(index)
If index > 1 AndAlso (index Mod 5) = 0 Then
Console.WriteLine()
End If
Console.Write("{0,14}", v)
Next
Console.WriteLine()
Console.WriteLine()
Console.WriteLine("Number of square-free integers:")
For Each to_ In {100, 1_000, 10_000, 100_000, 1_000_000}
Console.WriteLine(" from 1 to {0} = {1}", to_, SquareFree(1, to_).Count)
Next
End Sub
End Module
| import math
def SquareFree ( _number ) :
max = (int) (math.sqrt ( _number ))
for root in range ( 2, max+1 ):
if 0 == _number % ( root * root ):
return False
return True
def ListSquareFrees( _start, _end ):
count = 0
for i in range ( _start, _end+1 ):
if True == SquareFree( i ):
print ( "{}\t".format(i), end="" )
count += 1
print ( "\n\nTotal count of square-free numbers between {} and {}: {}".format(_start, _end, count))
ListSquareFrees( 1, 100 )
ListSquareFrees( 1000000000000, 1000000000145 )
|
Rewrite this program in Python while keeping its functionality equivalent to the VB version. | Option Explicit
Function JaroWinkler(text1 As String, text2 As String, Optional p As Double = 0.1) As Double
Dim dummyChar, match1, match2 As String
Dim i, f, t, j, m, l, s1, s2, limit As Integer
i = 1
Do
dummyChar = Chr(i)
i = i + 1
Loop Until InStr(1, text1 & text2, dummyChar, vbTextCompare) = 0
s1 = Len(text1)
s2 = Len(text2)
limit = WorksheetFunction.Max(0, Int(WorksheetFunction.Max(s1, s2) / 2) - 1)
match1 = String(s1, dummyChar)
match2 = String(s2, dummyChar)
For l = 1 To WorksheetFunction.Min(4, s1, s2)
If Mid(text1, l, 1) <> Mid(text2, l, 1) Then Exit For
Next l
l = l - 1
For i = 1 To s1
f = WorksheetFunction.Min(WorksheetFunction.Max(i - limit, 1), s2)
t = WorksheetFunction.Min(WorksheetFunction.Max(i + limit, 1), s2)
j = InStr(1, Mid(text2, f, t - f + 1), Mid(text1, i, 1), vbTextCompare)
If j > 0 Then
m = m + 1
text2 = Mid(text2, 1, f + j - 2) & dummyChar & Mid(text2, f + j)
match1 = Mid(match1, 1, i - 1) & Mid(text1, i, 1) & Mid(match1, i + 1)
match2 = Mid(match2, 1, f + j - 2) & Mid(text1, i, 1) & Mid(match2, f + j)
End If
Next i
match1 = Replace(match1, dummyChar, "", 1, -1, vbTextCompare)
match2 = Replace(match2, dummyChar, "", 1, -1, vbTextCompare)
t = 0
For i = 1 To m
If Mid(match1, i, 1) <> Mid(match2, i, 1) Then t = t + 1
Next i
JaroWinkler = (m / s1 + m / s2 + (m - t / 2) / m) / 3
JaroWinkler = JaroWinkler + (1 - JaroWinkler) * l * WorksheetFunction.Min(0.25, p)
End Function
|
from __future__ import division
def jaro(s, t):
s_len = len(s)
t_len = len(t)
if s_len == 0 and t_len == 0:
return 1
match_distance = (max(s_len, t_len) // 2) - 1
s_matches = [False] * s_len
t_matches = [False] * t_len
matches = 0
transpositions = 0
for i in range(s_len):
start = max(0, i - match_distance)
end = min(i + match_distance + 1, t_len)
for j in range(start, end):
if t_matches[j]:
continue
if s[i] != t[j]:
continue
s_matches[i] = True
t_matches[j] = True
matches += 1
break
if matches == 0:
return 0
k = 0
for i in range(s_len):
if not s_matches[i]:
continue
while not t_matches[k]:
k += 1
if s[i] != t[k]:
transpositions += 1
k += 1
return ((matches / s_len) +
(matches / t_len) +
((matches - transpositions / 2) / matches)) / 3
def main():
for s, t in [('MARTHA', 'MARHTA'),
('DIXON', 'DICKSONX'),
('JELLYFISH', 'SMELLYFISH')]:
print("jaro(%r, %r) = %.10f" % (s, t, jaro(s, t)))
if __name__ == '__main__':
main()
|
Transform the following VB implementation into Python, maintaining the same output and logic. | Module Module1
Function Turn(base As Integer, n As Integer) As Integer
Dim sum = 0
While n <> 0
Dim re = n Mod base
n \= base
sum += re
End While
Return sum Mod base
End Function
Sub Fairshare(base As Integer, count As Integer)
Console.Write("Base {0,2}:", base)
For i = 1 To count
Dim t = Turn(base, i - 1)
Console.Write(" {0,2}", t)
Next
Console.WriteLine()
End Sub
Sub TurnCount(base As Integer, count As Integer)
Dim cnt(base) As Integer
For i = 1 To base
cnt(i - 1) = 0
Next
For i = 1 To count
Dim t = Turn(base, i - 1)
cnt(t) += 1
Next
Dim minTurn = Integer.MaxValue
Dim maxTurn = Integer.MinValue
Dim portion = 0
For i = 1 To base
Dim num = cnt(i - 1)
If num > 0 Then
portion += 1
End If
If num < minTurn Then
minTurn = num
End If
If num > maxTurn Then
maxTurn = num
End If
Next
Console.Write(" With {0} people: ", base)
If 0 = minTurn Then
Console.WriteLine("Only {0} have a turn", portion)
ElseIf minTurn = maxTurn Then
Console.WriteLine(minTurn)
Else
Console.WriteLine("{0} or {1}", minTurn, maxTurn)
End If
End Sub
Sub Main()
Fairshare(2, 25)
Fairshare(3, 25)
Fairshare(5, 25)
Fairshare(11, 25)
Console.WriteLine("How many times does each get a turn in 50000 iterations?")
TurnCount(191, 50000)
TurnCount(1377, 50000)
TurnCount(49999, 50000)
TurnCount(50000, 50000)
TurnCount(50001, 50000)
End Sub
End Module
| from itertools import count, islice
def _basechange_int(num, b):
if num == 0:
return [0]
result = []
while num != 0:
num, d = divmod(num, b)
result.append(d)
return result[::-1]
def fairshare(b=2):
for i in count():
yield sum(_basechange_int(i, b)) % b
if __name__ == '__main__':
for b in (2, 3, 5, 11):
print(f"{b:>2}: {str(list(islice(fairshare(b), 25)))[1:-1]}")
|
Write a version of this VB function in Python with identical behavior. | Module Module1
Function Turn(base As Integer, n As Integer) As Integer
Dim sum = 0
While n <> 0
Dim re = n Mod base
n \= base
sum += re
End While
Return sum Mod base
End Function
Sub Fairshare(base As Integer, count As Integer)
Console.Write("Base {0,2}:", base)
For i = 1 To count
Dim t = Turn(base, i - 1)
Console.Write(" {0,2}", t)
Next
Console.WriteLine()
End Sub
Sub TurnCount(base As Integer, count As Integer)
Dim cnt(base) As Integer
For i = 1 To base
cnt(i - 1) = 0
Next
For i = 1 To count
Dim t = Turn(base, i - 1)
cnt(t) += 1
Next
Dim minTurn = Integer.MaxValue
Dim maxTurn = Integer.MinValue
Dim portion = 0
For i = 1 To base
Dim num = cnt(i - 1)
If num > 0 Then
portion += 1
End If
If num < minTurn Then
minTurn = num
End If
If num > maxTurn Then
maxTurn = num
End If
Next
Console.Write(" With {0} people: ", base)
If 0 = minTurn Then
Console.WriteLine("Only {0} have a turn", portion)
ElseIf minTurn = maxTurn Then
Console.WriteLine(minTurn)
Else
Console.WriteLine("{0} or {1}", minTurn, maxTurn)
End If
End Sub
Sub Main()
Fairshare(2, 25)
Fairshare(3, 25)
Fairshare(5, 25)
Fairshare(11, 25)
Console.WriteLine("How many times does each get a turn in 50000 iterations?")
TurnCount(191, 50000)
TurnCount(1377, 50000)
TurnCount(49999, 50000)
TurnCount(50000, 50000)
TurnCount(50001, 50000)
End Sub
End Module
| from itertools import count, islice
def _basechange_int(num, b):
if num == 0:
return [0]
result = []
while num != 0:
num, d = divmod(num, b)
result.append(d)
return result[::-1]
def fairshare(b=2):
for i in count():
yield sum(_basechange_int(i, b)) % b
if __name__ == '__main__':
for b in (2, 3, 5, 11):
print(f"{b:>2}: {str(list(islice(fairshare(b), 25)))[1:-1]}")
|
Ensure the translated Python code behaves exactly like the original VB snippet. | Module Module1
Class SymbolType
Public ReadOnly symbol As String
Public ReadOnly precedence As Integer
Public ReadOnly rightAssociative As Boolean
Public Sub New(symbol As String, precedence As Integer, rightAssociative As Boolean)
Me.symbol = symbol
Me.precedence = precedence
Me.rightAssociative = rightAssociative
End Sub
End Class
ReadOnly Operators As Dictionary(Of String, SymbolType) = New Dictionary(Of String, SymbolType) From
{
{"^", New SymbolType("^", 4, True)},
{"*", New SymbolType("*", 3, False)},
{"/", New SymbolType("/", 3, False)},
{"+", New SymbolType("+", 2, False)},
{"-", New SymbolType("-", 2, False)}
}
Function ToPostfix(infix As String) As String
Dim tokens = infix.Split(" ")
Dim stack As New Stack(Of String)
Dim output As New List(Of String)
Dim Print = Sub(action As String) Console.WriteLine("{0,-4} {1,-18} {2}", action + ":", $"stack[ {String.Join(" ", stack.Reverse())} ]", $"out[ {String.Join(" ", output)} ]")
For Each token In tokens
Dim iv As Integer
Dim op1 As SymbolType
Dim op2 As SymbolType
If Integer.TryParse(token, iv) Then
output.Add(token)
Print(token)
ElseIf Operators.TryGetValue(token, op1) Then
While stack.Count > 0 AndAlso Operators.TryGetValue(stack.Peek(), op2)
Dim c = op1.precedence.CompareTo(op2.precedence)
If c < 0 OrElse Not op1.rightAssociative AndAlso c <= 0 Then
output.Add(stack.Pop())
Else
Exit While
End If
End While
stack.Push(token)
Print(token)
ElseIf token = "(" Then
stack.Push(token)
Print(token)
ElseIf token = ")" Then
Dim top = ""
While stack.Count > 0
top = stack.Pop()
If top <> "(" Then
output.Add(top)
Else
Exit While
End If
End While
If top <> "(" Then
Throw New ArgumentException("No matching left parenthesis.")
End If
Print(token)
End If
Next
While stack.Count > 0
Dim top = stack.Pop()
If Not Operators.ContainsKey(top) Then
Throw New ArgumentException("No matching right parenthesis.")
End If
output.Add(top)
End While
Print("pop")
Return String.Join(" ", output)
End Function
Sub Main()
Dim infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"
Console.WriteLine(ToPostfix(infix))
End Sub
End Module
| from collections import namedtuple
from pprint import pprint as pp
OpInfo = namedtuple('OpInfo', 'prec assoc')
L, R = 'Left Right'.split()
ops = {
'^': OpInfo(prec=4, assoc=R),
'*': OpInfo(prec=3, assoc=L),
'/': OpInfo(prec=3, assoc=L),
'+': OpInfo(prec=2, assoc=L),
'-': OpInfo(prec=2, assoc=L),
'(': OpInfo(prec=9, assoc=L),
')': OpInfo(prec=0, assoc=L),
}
NUM, LPAREN, RPAREN = 'NUMBER ( )'.split()
def get_input(inp = None):
'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)'
if inp is None:
inp = input('expression: ')
tokens = inp.strip().split()
tokenvals = []
for token in tokens:
if token in ops:
tokenvals.append((token, ops[token]))
else:
tokenvals.append((NUM, token))
return tokenvals
def shunting(tokenvals):
outq, stack = [], []
table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')]
for token, val in tokenvals:
note = action = ''
if token is NUM:
action = 'Add number to output'
outq.append(val)
table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )
elif token in ops:
t1, (p1, a1) = token, val
v = t1
note = 'Pop ops from stack to output'
while stack:
t2, (p2, a2) = stack[-1]
if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2):
if t1 != RPAREN:
if t2 != LPAREN:
stack.pop()
action = '(Pop op)'
outq.append(t2)
else:
break
else:
if t2 != LPAREN:
stack.pop()
action = '(Pop op)'
outq.append(t2)
else:
stack.pop()
action = '(Pop & discard "(")'
table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )
break
table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )
v = note = ''
else:
note = ''
break
note = ''
note = ''
if t1 != RPAREN:
stack.append((token, val))
action = 'Push op token to stack'
else:
action = 'Discard ")"'
table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )
note = 'Drain stack to output'
while stack:
v = ''
t2, (p2, a2) = stack[-1]
action = '(Pop op)'
stack.pop()
outq.append(t2)
table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) )
v = note = ''
return table
if __name__ == '__main__':
infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3'
print( 'For infix expression: %r\n' % infix )
rp = shunting(get_input(infix))
maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)]
row = rp[0]
print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))
for row in rp[1:]:
print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))
print('\n The final output RPN is: %r' % rp[-1][2])
|
Write a version of this VB function in Python with identical behavior. | Function tpk(s)
arr = Split(s," ")
For i = UBound(arr) To 0 Step -1
n = fx(CDbl(arr(i)))
If n > 400 Then
WScript.StdOut.WriteLine arr(i) & " = OVERFLOW"
Else
WScript.StdOut.WriteLine arr(i) & " = " & n
End If
Next
End Function
Function fx(x)
fx = Sqr(Abs(x))+5*x^3
End Function
WScript.StdOut.Write "Please enter a series of numbers:"
list = WScript.StdIn.ReadLine
tpk(list)
| Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> def f(x): return abs(x) ** 0.5 + 5 * x**3
>>> print(', '.join('%s:%s' % (x, v if v<=400 else "TOO LARGE!")
for x,v in ((y, f(float(y))) for y in input('\nnumbers: ').strip().split()[:11][::-1])))
11 numbers: 1 2 3 4 5 6 7 8 9 10 11
11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0
>>>
|
Convert this VB block to Python, preserving its control flow and logic. | Option Explicit
Sub Main_Middle_three_digits()
Dim Numbers, i&
Numbers = Array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, _
100, -12345, 1, 2, -1, -10, 2002, -2002, 0)
For i = 0 To 16
Debug.Print Numbers(i) & " Return : " & Middle3digits(CStr(Numbers(i)))
Next
End Sub
Function Middle3digits(strNb As String) As String
If Left(strNb, 1) = "-" Then strNb = Right(strNb, Len(strNb) - 1)
If Len(strNb) < 3 Then
Middle3digits = "Error ! Number of digits must be >= 3"
ElseIf Len(strNb) Mod 2 = 0 Then
Middle3digits = "Error ! Number of digits must be odd"
Else
Middle3digits = Mid(strNb, 1 + (Len(strNb) - 3) / 2, 3)
End If
End Function
| >>> def middle_three_digits(i):
s = str(abs(i))
length = len(s)
assert length >= 3 and length % 2 == 1, "Need odd and >= 3 digits"
mid = length // 2
return s[mid-1:mid+2]
>>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]
>>> failing = [1, 2, -1, -10, 2002, -2002, 0]
>>> for x in passing + failing:
try:
answer = middle_three_digits(x)
except AssertionError as error:
answer = error
print("middle_three_digits(%s) returned: %r" % (x, answer))
middle_three_digits(123) returned: '123'
middle_three_digits(12345) returned: '234'
middle_three_digits(1234567) returned: '345'
middle_three_digits(987654321) returned: '654'
middle_three_digits(10001) returned: '000'
middle_three_digits(-10001) returned: '000'
middle_three_digits(-123) returned: '123'
middle_three_digits(-100) returned: '100'
middle_three_digits(100) returned: '100'
middle_three_digits(-12345) returned: '234'
middle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',)
middle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',)
>>>
|
Rewrite the snippet below in Python so it works the same as the original VB code. | Private Function OddWordFirst(W As String) As String
Dim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String
count = 1
Do
flag = Not flag
l = FindNextPunct(i, W) - count + 1
If flag Then
temp = temp & ExtractWord(W, count, l)
Else
temp = temp & ReverseWord(W, count, l)
End If
Loop While count < Len(W)
OddWordFirst = temp
End Function
Private Function FindNextPunct(d As Integer, W As String) As Integer
Const PUNCT As String = ",;:."
Do
d = d + 1
Loop While InStr(PUNCT, Mid(W, d, 1)) = 0
FindNextPunct = d
End Function
Private Function ExtractWord(W As String, c As Integer, i As Integer) As String
ExtractWord = Mid(W, c, i)
c = c + Len(ExtractWord)
End Function
Private Function ReverseWord(W As String, c As Integer, i As Integer) As String
Dim temp As String, sep As String
temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1)
sep = Right(Mid(W, c, i), 1)
ReverseWord = StrReverse(temp) & sep
c = c + Len(ReverseWord)
End Function
| from sys import stdin, stdout
def char_in(): return stdin.read(1)
def char_out(c): stdout.write(c)
def odd(prev = lambda: None):
a = char_in()
if not a.isalpha():
prev()
char_out(a)
return a != '.'
def clos():
char_out(a)
prev()
return odd(clos)
def even():
while True:
c = char_in()
char_out(c)
if not c.isalpha(): return c != '.'
e = False
while odd() if e else even():
e = not e
|
Transform the following VB implementation into Python, maintaining the same output and logic. | Private Function OddWordFirst(W As String) As String
Dim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String
count = 1
Do
flag = Not flag
l = FindNextPunct(i, W) - count + 1
If flag Then
temp = temp & ExtractWord(W, count, l)
Else
temp = temp & ReverseWord(W, count, l)
End If
Loop While count < Len(W)
OddWordFirst = temp
End Function
Private Function FindNextPunct(d As Integer, W As String) As Integer
Const PUNCT As String = ",;:."
Do
d = d + 1
Loop While InStr(PUNCT, Mid(W, d, 1)) = 0
FindNextPunct = d
End Function
Private Function ExtractWord(W As String, c As Integer, i As Integer) As String
ExtractWord = Mid(W, c, i)
c = c + Len(ExtractWord)
End Function
Private Function ReverseWord(W As String, c As Integer, i As Integer) As String
Dim temp As String, sep As String
temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1)
sep = Right(Mid(W, c, i), 1)
ReverseWord = StrReverse(temp) & sep
c = c + Len(ReverseWord)
End Function
| from sys import stdin, stdout
def char_in(): return stdin.read(1)
def char_out(c): stdout.write(c)
def odd(prev = lambda: None):
a = char_in()
if not a.isalpha():
prev()
char_out(a)
return a != '.'
def clos():
char_out(a)
prev()
return odd(clos)
def even():
while True:
c = char_in()
char_out(c)
if not c.isalpha(): return c != '.'
e = False
while odd() if e else even():
e = not e
|
Write a version of this VB function in Python with identical behavior. | Function Biorhythm(Birthdate As Date, Targetdate As Date) As String
TextArray = Array(Array("up and rising", "peak"), Array("up but falling", "transition"), Array("down and falling", "valley"), Array("down but rising", "transition"))
DaysBetween = Targetdate - Birthdate
positionP = DaysBetween Mod 23
positionE = DaysBetween Mod 28
positionM = DaysBetween Mod 33
Biorhythm = CStr(positionP) & "/" & CStr(positionE) & "/" & CStr(positionM)
quadrantP = Int(4 * positionP / 23)
quadrantE = Int(4 * positionE / 28)
quadrantM = Int(4 * positionM / 33)
percentageP = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionP / 23)), 1)
percentageE = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionE / 28)), 1)
percentageM = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionM / 33)), 1)
transitionP = Targetdate + WorksheetFunction.Floor((quadrantP + 1) / 4 * 23, 1) - positionP
transitionE = Targetdate + WorksheetFunction.Floor((quadrantE + 1) / 4 * 28, 1) - positionE
transitionM = Targetdate + WorksheetFunction.Floor((quadrantM + 1) / 4 * 33, 1) - positionM
Select Case True
Case percentageP > 95
textP = "Physical day " & positionP & " : " & "peak"
Case percentageP < -95
textP = "Physical day " & positionP & " : " & "valley"
Case percentageP < 5 And percentageP > -5
textP = "Physical day " & positionP & " : " & "critical transition"
Case Else
textP = "Physical day " & positionP & " : " & percentageP & "% (" & TextArray(quadrantP)(0) & ", next " & TextArray(quadrantP)(1) & " " & transitionP & ")"
End Select
Select Case True
Case percentageE > 95
textE = "Emotional day " & positionE & " : " & "peak"
Case percentageE < -95
textE = "Emotional day " & positionE & " : " & "valley"
Case percentageE < 5 And percentageE > -5
textE = "Emotional day " & positionE & " : " & "critical transition"
Case Else
textE = "Emotional day " & positionE & " : " & percentageE & "% (" & TextArray(quadrantE)(0) & ", next " & TextArray(quadrantE)(1) & " " & transitionE & ")"
End Select
Select Case True
Case percentageM > 95
textM = "Mental day " & positionM & " : " & "peak"
Case percentageM < -95
textM = "Mental day " & positionM & " : " & "valley"
Case percentageM < 5 And percentageM > -5
textM = "Mental day " & positionM & " : " & "critical transition"
Case Else
textM = "Mental day " & positionM & " : " & percentageM & "% (" & TextArray(quadrantM)(0) & ", next " & TextArray(quadrantM)(1) & " " & transitionM & ")"
End Select
Header1Text = "Born " & Birthdate & ", Target " & Targetdate
Header2Text = "Day " & DaysBetween
Debug.Print Header1Text
Debug.Print Header2Text
Debug.Print textP
Debug.Print textE
Debug.Print textM
Debug.Print ""
End Function
|
from datetime import date, timedelta
from math import floor, sin, pi
def biorhythms(birthdate,targetdate):
print("Born: "+birthdate+" Target: "+targetdate)
birthdate = date.fromisoformat(birthdate)
targetdate = date.fromisoformat(targetdate)
days = (targetdate - birthdate).days
print("Day: "+str(days))
cycle_labels = ["Physical", "Emotional", "Mental"]
cycle_lengths = [23, 28, 33]
quadrants = [("up and rising", "peak"), ("up but falling", "transition"),
("down and falling", "valley"), ("down but rising", "transition")]
for i in range(3):
label = cycle_labels[i]
length = cycle_lengths[i]
position = days % length
quadrant = int(floor((4 * position) / length))
percentage = int(round(100 * sin(2 * pi * position / length),0))
transition_date = targetdate + timedelta(days=floor((quadrant + 1)/4 * length) - position)
trend, next = quadrants[quadrant]
if percentage > 95:
description = "peak"
elif percentage < -95:
description = "valley"
elif abs(percentage) < 5:
description = "critical transition"
else:
description = str(percentage)+"% ("+trend+", next "+next+" "+str(transition_date)+")"
print(label+" day "+str(position)+": "+description)
biorhythms("1943-03-09","1972-07-11")
|
Preserve the algorithm and functionality while converting the code from VB to Python. | Function Biorhythm(Birthdate As Date, Targetdate As Date) As String
TextArray = Array(Array("up and rising", "peak"), Array("up but falling", "transition"), Array("down and falling", "valley"), Array("down but rising", "transition"))
DaysBetween = Targetdate - Birthdate
positionP = DaysBetween Mod 23
positionE = DaysBetween Mod 28
positionM = DaysBetween Mod 33
Biorhythm = CStr(positionP) & "/" & CStr(positionE) & "/" & CStr(positionM)
quadrantP = Int(4 * positionP / 23)
quadrantE = Int(4 * positionE / 28)
quadrantM = Int(4 * positionM / 33)
percentageP = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionP / 23)), 1)
percentageE = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionE / 28)), 1)
percentageM = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionM / 33)), 1)
transitionP = Targetdate + WorksheetFunction.Floor((quadrantP + 1) / 4 * 23, 1) - positionP
transitionE = Targetdate + WorksheetFunction.Floor((quadrantE + 1) / 4 * 28, 1) - positionE
transitionM = Targetdate + WorksheetFunction.Floor((quadrantM + 1) / 4 * 33, 1) - positionM
Select Case True
Case percentageP > 95
textP = "Physical day " & positionP & " : " & "peak"
Case percentageP < -95
textP = "Physical day " & positionP & " : " & "valley"
Case percentageP < 5 And percentageP > -5
textP = "Physical day " & positionP & " : " & "critical transition"
Case Else
textP = "Physical day " & positionP & " : " & percentageP & "% (" & TextArray(quadrantP)(0) & ", next " & TextArray(quadrantP)(1) & " " & transitionP & ")"
End Select
Select Case True
Case percentageE > 95
textE = "Emotional day " & positionE & " : " & "peak"
Case percentageE < -95
textE = "Emotional day " & positionE & " : " & "valley"
Case percentageE < 5 And percentageE > -5
textE = "Emotional day " & positionE & " : " & "critical transition"
Case Else
textE = "Emotional day " & positionE & " : " & percentageE & "% (" & TextArray(quadrantE)(0) & ", next " & TextArray(quadrantE)(1) & " " & transitionE & ")"
End Select
Select Case True
Case percentageM > 95
textM = "Mental day " & positionM & " : " & "peak"
Case percentageM < -95
textM = "Mental day " & positionM & " : " & "valley"
Case percentageM < 5 And percentageM > -5
textM = "Mental day " & positionM & " : " & "critical transition"
Case Else
textM = "Mental day " & positionM & " : " & percentageM & "% (" & TextArray(quadrantM)(0) & ", next " & TextArray(quadrantM)(1) & " " & transitionM & ")"
End Select
Header1Text = "Born " & Birthdate & ", Target " & Targetdate
Header2Text = "Day " & DaysBetween
Debug.Print Header1Text
Debug.Print Header2Text
Debug.Print textP
Debug.Print textE
Debug.Print textM
Debug.Print ""
End Function
|
from datetime import date, timedelta
from math import floor, sin, pi
def biorhythms(birthdate,targetdate):
print("Born: "+birthdate+" Target: "+targetdate)
birthdate = date.fromisoformat(birthdate)
targetdate = date.fromisoformat(targetdate)
days = (targetdate - birthdate).days
print("Day: "+str(days))
cycle_labels = ["Physical", "Emotional", "Mental"]
cycle_lengths = [23, 28, 33]
quadrants = [("up and rising", "peak"), ("up but falling", "transition"),
("down and falling", "valley"), ("down but rising", "transition")]
for i in range(3):
label = cycle_labels[i]
length = cycle_lengths[i]
position = days % length
quadrant = int(floor((4 * position) / length))
percentage = int(round(100 * sin(2 * pi * position / length),0))
transition_date = targetdate + timedelta(days=floor((quadrant + 1)/4 * length) - position)
trend, next = quadrants[quadrant]
if percentage > 95:
description = "peak"
elif percentage < -95:
description = "valley"
elif abs(percentage) < 5:
description = "critical transition"
else:
description = str(percentage)+"% ("+trend+", next "+next+" "+str(transition_date)+")"
print(label+" day "+str(position)+": "+description)
biorhythms("1943-03-09","1972-07-11")
|
Produce a functionally identical Python code for the snippet given in VB. | Option Explicit
Dim objFSO, DBSource
Set objFSO = CreateObject("Scripting.FileSystemObject")
DBSource = objFSO.GetParentFolderName(WScript.ScriptFullName) & "\postal_address.accdb"
With CreateObject("ADODB.Connection")
.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DBSource
.Execute "CREATE TABLE ADDRESS (STREET VARCHAR(30) NOT NULL," &_
"CITY VARCHAR(30) NOT NULL, STATE CHAR(2) NOT NULL,ZIP CHAR(5) NOT NULL)"
.Close
End With
| >>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> conn.execute()
<sqlite3.Cursor object at 0x013265C0>
>>>
|
Keep all operations the same but rewrite the snippet in Python. | Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Module1
Dim l As List(Of Integer) = {1, 1}.ToList()
Function gcd(ByVal a As Integer, ByVal b As Integer) As Integer
Return If(a > 0, If(a < b, gcd(b Mod a, a), gcd(a Mod b, b)), b)
End Function
Sub Main(ByVal args As String())
Dim max As Integer = 1000, take As Integer = 15, i As Integer = 1,
selection As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100}
Do : l.AddRange({l(i) + l(i - 1), l(i)}.ToList) : i += 1
Loop While l.Count < max OrElse l(l.Count - 2) <> selection.Last()
Console.Write("The first {0} items In the Stern-Brocot sequence: ", take)
Console.WriteLine("{0}" & vbLf, String.Join(", ", l.Take(take)))
Console.WriteLine("The locations of where the selected numbers (1-to-10, & 100) first appear:")
For Each ii As Integer In selection
Dim j As Integer = l.FindIndex(Function(x) x = ii) + 1
Console.WriteLine("{0,3}: {1:n0}", ii, j)
Next : Console.WriteLine() : Dim good As Boolean = True : For i = 1 To max
If gcd(l(i), l(i - 1)) <> 1 Then good = False : Exit For
Next
Console.WriteLine("The greatest common divisor of all the two consecutive items of the" &
" series up to the {0}th item is {1}always one.", max, If(good, "", "not "))
End Sub
End Module
| def stern_brocot(predicate=lambda series: len(series) < 20):
sb, i = [1, 1], 0
while predicate(sb):
sb += [sum(sb[i:i + 2]), sb[i + 1]]
i += 1
return sb
if __name__ == '__main__':
from fractions import gcd
n_first = 15
print('The first %i values:\n ' % n_first,
stern_brocot(lambda series: len(series) < n_first)[:n_first])
print()
n_max = 10
for n_occur in list(range(1, n_max + 1)) + [100]:
print('1-based index of the first occurrence of %3i in the series:' % n_occur,
stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1)
print()
n_gcd = 1000
s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd]
assert all(gcd(prev, this) == 1
for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'
|
Produce a functionally identical Python code for the snippet given in VB. |
tt=array( _
"Ashcraft","Ashcroft","Gauss","Ghosh","Hilbert","Heilbronn","Lee","Lloyd", _
"Moses","Pfister","Robert","Rupert","Rubin","Tymczak","Soundex","Example")
tv=array( _
"A261","A261","G200","G200","H416","H416","L000","L300", _
"M220","P236","R163","R163","R150","T522","S532","E251")
For i=lbound(tt) To ubound(tt)
ts=soundex(tt(i))
If ts<>tv(i) Then ok=" KO "& tv(i) Else ok=""
Wscript.echo right(" "& i ,2) & " " & left( tt(i) &space(12),12) & " " & ts & ok
Next
Function getCode(c)
Select Case c
Case "B", "F", "P", "V"
getCode = "1"
Case "C", "G", "J", "K", "Q", "S", "X", "Z"
getCode = "2"
Case "D", "T"
getCode = "3"
Case "L"
getCode = "4"
Case "M", "N"
getCode = "5"
Case "R"
getCode = "6"
Case "W","H"
getCode = "-"
End Select
End Function
Function soundex(s)
Dim code, previous, i
code = UCase(Mid(s, 1, 1))
previous = getCode(UCase(Mid(s, 1, 1)))
For i = 2 To Len(s)
current = getCode(UCase(Mid(s, i, 1)))
If current <> "" And current <> "-" And current <> previous Then code = code & current
If current <> "-" Then previous = current
Next
soundex = Mid(code & "000", 1, 4)
End Function
| from itertools import groupby
def soundex(word):
codes = ("bfpv","cgjkqsxz", "dt", "l", "mn", "r")
soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod)
cmap2 = lambda kar: soundDict.get(kar, '9')
sdx = ''.join(cmap2(kar) for kar in word.lower())
sdx2 = word[0].upper() + ''.join(k for k,g in list(groupby(sdx))[1:] if k!='9')
sdx3 = sdx2[0:4].ljust(4,'0')
return sdx3
|
Rewrite this program in Python while keeping its functionality equivalent to the VB version. | Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Module Module1
Class State
Private ReadOnly client As TcpClient
Private ReadOnly sb As New StringBuilder
Public Sub New(name As String, client As TcpClient)
Me.Name = name
Me.client = client
End Sub
Public ReadOnly Property Name As String
Public Sub Send(text As String)
Dim bytes = Encoding.ASCII.GetBytes(String.Format("{0}" & vbCrLf, text))
client.GetStream().Write(bytes, 0, bytes.Length)
End Sub
End Class
ReadOnly connections As New Dictionary(Of Integer, State)
Dim listen As TcpListener
Dim serverThread As Thread
Sub Main()
listen = New TcpListener(Net.IPAddress.Parse("127.0.0.1"), 4004)
serverThread = New Thread(New ThreadStart(AddressOf DoListen))
serverThread.Start()
End Sub
Private Sub DoListen()
listen.Start()
Console.WriteLine("Server: Started server")
Do
Console.Write("Server: Waiting...")
Dim client = listen.AcceptTcpClient()
Console.WriteLine(" Connected")
Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf DoClient))
clientThread.Start(client)
Loop
End Sub
Private Sub DoClient(client As TcpClient)
Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId)
Dim bytes = Encoding.ASCII.GetBytes("Enter name: ")
client.GetStream().Write(bytes, 0, bytes.Length)
Dim done As Boolean
Dim name As String
Do
If Not client.Connected Then
Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId)
client.Close()
Thread.CurrentThread.Abort()
End If
name = Receive(client)
done = True
For Each cl In connections
Dim state = cl.Value
If state.Name = name Then
bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: ")
client.GetStream().Write(bytes, 0, bytes.Length)
done = False
End If
Next
Loop While Not done
connections.Add(Thread.CurrentThread.ManagedThreadId, New State(name, client))
Console.WriteLine(vbTab & "Total connections: {0}", connections.Count)
Broadcast(String.Format("+++ {0} arrived +++", name))
Do
Dim text = Receive(client)
If text = "/quit" Then
Broadcast(String.Format("Connection from {0} closed.", name))
connections.Remove(Thread.CurrentThread.ManagedThreadId)
Console.WriteLine(vbTab & "Total connections: {0}", connections.Count)
Exit Do
End If
If Not client.Connected Then
Exit Do
End If
Broadcast(String.Format("{0}> {1}", name, text))
Loop
Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId)
client.Close()
Thread.CurrentThread.Abort()
End Sub
Private Function Receive(client As TcpClient) As String
Dim sb As New StringBuilder
Do
If client.Available > 0 Then
While client.Available > 0
Dim ch = Chr(client.GetStream.ReadByte())
If ch = vbCr Then
Continue While
End If
If ch = vbLf Then
Return sb.ToString()
End If
sb.Append(ch)
End While
Thread.Sleep(100)
End If
Loop
End Function
Private Sub Broadcast(text As String)
Console.WriteLine(text)
For Each client In connections
If client.Key <> Thread.CurrentThread.ManagedThreadId Then
Dim state = client.Value
state.Send(text)
End If
Next
End Sub
End Module
|
import socket
import thread
import time
HOST = ""
PORT = 4004
def accept(conn):
def threaded():
while True:
conn.send("Please enter your name: ")
try:
name = conn.recv(1024).strip()
except socket.error:
continue
if name in users:
conn.send("Name entered is already in use.\n")
elif name:
conn.setblocking(False)
users[name] = conn
broadcast(name, "+++ %s arrived +++" % name)
break
thread.start_new_thread(threaded, ())
def broadcast(name, message):
print message
for to_name, conn in users.items():
if to_name != name:
try:
conn.send(message + "\n")
except socket.error:
pass
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.setblocking(False)
server.bind((HOST, PORT))
server.listen(1)
print "Listening on %s" % ("%s:%s" % server.getsockname())
users = {}
while True:
try:
while True:
try:
conn, addr = server.accept()
except socket.error:
break
accept(conn)
for name, conn in users.items():
try:
message = conn.recv(1024)
except socket.error:
continue
if not message:
del users[name]
broadcast(name, "--- %s leaves ---" % name)
else:
broadcast(name, "%s> %s" % (name, message.strip()))
time.sleep(.1)
except (SystemExit, KeyboardInterrupt):
break
|
Preserve the algorithm and functionality while converting the code from VB to Python. | Sub truncate(fpath,n)
Set objfso = CreateObject("Scripting.FileSystemObject")
If objfso.FileExists(fpath) = False Then
WScript.Echo fpath & " does not exist"
Exit Sub
End If
content = ""
Set objinstream = CreateObject("Adodb.Stream")
With objinstream
.Type = 1
.Open
.LoadFromFile(fpath)
If n <= .Size Then
content = .Read(n)
Else
WScript.Echo "The specified size is larger than the file content"
Exit Sub
End If
.Close
End With
Set objoutstream = CreateObject("Adodb.Stream")
With objoutstream
.Type = 1
.Open
.Write content
.SaveToFile fpath,2
.Close
End With
Set objinstream = Nothing
Set objoutstream = Nothing
Set objfso = Nothing
End Sub
Call truncate("C:\temp\test.txt",30)
| def truncate_file(name, length):
if not os.path.isfile(name):
return False
if length >= os.path.getsize(name):
return False
with open(name, 'ab') as f:
f.truncate(length)
return True
|
Generate a Python translation of this VB snippet without changing its computational steps. | Sub truncate(fpath,n)
Set objfso = CreateObject("Scripting.FileSystemObject")
If objfso.FileExists(fpath) = False Then
WScript.Echo fpath & " does not exist"
Exit Sub
End If
content = ""
Set objinstream = CreateObject("Adodb.Stream")
With objinstream
.Type = 1
.Open
.LoadFromFile(fpath)
If n <= .Size Then
content = .Read(n)
Else
WScript.Echo "The specified size is larger than the file content"
Exit Sub
End If
.Close
End With
Set objoutstream = CreateObject("Adodb.Stream")
With objoutstream
.Type = 1
.Open
.Write content
.SaveToFile fpath,2
.Close
End With
Set objinstream = Nothing
Set objoutstream = Nothing
Set objfso = Nothing
End Sub
Call truncate("C:\temp\test.txt",30)
| def truncate_file(name, length):
if not os.path.isfile(name):
return False
if length >= os.path.getsize(name):
return False
with open(name, 'ab') as f:
f.truncate(length)
return True
|
Produce a functionally identical Python code for the snippet given in VB. | Public Declare Function GetTickCount Lib "kernel32.dll" () As Long
Private Function DecimalToBinary(DecimalNum As Long) As String
Dim tmp As String
Dim n As Long
n = DecimalNum
tmp = Trim(CStr(n Mod 2))
n = n \ 2
Do While n <> 0
tmp = Trim(CStr(n Mod 2)) & tmp
n = n \ 2
Loop
DecimalToBinary = tmp
End Function
Function Dec2Bin(ByVal DecimalIn As Variant, _
Optional NumberOfBits As Variant) As String
Dec2Bin = ""
DecimalIn = Int(CDec(DecimalIn))
Do While DecimalIn <> 0
Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin
DecimalIn = Int(DecimalIn / 2)
Loop
If Not IsMissing(NumberOfBits) Then
If Len(Dec2Bin) > NumberOfBits Then
Dec2Bin = "Error - Number exceeds specified bit size"
Else
Dec2Bin = Right$(String$(NumberOfBits, _
"0") & Dec2Bin, NumberOfBits)
End If
End If
End Function
Public Sub base()
Time1 = GetTickCount
Dim n As Long
Dim three(19) As Integer
Dim pow3(19) As Variant
Dim full3 As Variant
Dim trail As Variant
Dim check As Long
Dim len3 As Integer
Dim carry As Boolean
Dim i As Integer, j As Integer
Dim s As String
Dim t As String
pow3(0) = CDec(1)
For i = 1 To 19
pow3(i) = 3 * pow3(i - 1)
Next i
Debug.Print String$(5, " "); "iter"; String$(7, " "); "decimal"; String$(18, " "); "binary";
Debug.Print String$(30, " "); "ternary"
n = 0: full3 = 0: t = "0": s = "0"
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
n = 0: full3 = 1: t = "1": s = "1"
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
number = 0
n = 1
len3 = 0
full3 = 3
Do
three(0) = three(0) + 1
carry = False
If three(0) = 3 Then
three(0) = 0
carry = True
j = 1
Do While carry
three(j) = three(j) + 1
If three(j) = 3 Then
three(j) = 0
j = j + 1
Else
carry = False
End If
Loop
If len3 < j Then
trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)
len3 = j
full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail
For i = 0 To j - 1
full3 = full3 - 2 * pow3(len3 - i)
Next i
full3 = full3 + 1
Else
full3 = full3 + pow3(len3 + 2)
For i = 0 To j - 1
full3 = full3 - 2 * pow3(len3 - i)
Next i
full3 = full3 + pow3(len3 - j)
End If
Else
full3 = full3 + pow3(len3 + 2) + pow3(len3)
End If
s = ""
For i = 0 To len3
s = s & CStr(three(i))
Next i
t = Dec2Bin(full3)
If t = StrReverse(t) Then
number = number + 1
s = StrReverse(s) & "1" & s
If n < 200000 Then
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
If number = 4 Then
Debug.Print "Completed in"; (GetTickCount - Time1) / 1000; "seconds"
Time2 = GetTickCount
Application.ScreenUpdating = False
End If
Else
Debug.Print n, full3, Len(t), t, Len(s), s
Debug.Print "Completed in"; (Time2 - Time1) / 1000; "seconds";
Time3 = GetTickCount
End If
End If
n = n + 1
Loop Until number = 5
Debug.Print "Completed in"; (Time3 - Time1) / 1000; "seconds"
Application.ScreenUpdating = True
End Sub
| from itertools import islice
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
def baseN(num,b):
if num == 0: return "0"
result = ""
while num != 0:
num, d = divmod(num, b)
result += digits[d]
return result[::-1]
def pal2(num):
if num == 0 or num == 1: return True
based = bin(num)[2:]
return based == based[::-1]
def pal_23():
yield 0
yield 1
n = 1
while True:
n += 1
b = baseN(n, 3)
revb = b[::-1]
for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),
'{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):
t = int(trial, 3)
if pal2(t):
yield t
for pal23 in islice(pal_23(), 6):
print(pal23, baseN(pal23, 3), baseN(pal23, 2))
|
Write a version of this VB function in Python with identical behavior. | Public Declare Function GetTickCount Lib "kernel32.dll" () As Long
Private Function DecimalToBinary(DecimalNum As Long) As String
Dim tmp As String
Dim n As Long
n = DecimalNum
tmp = Trim(CStr(n Mod 2))
n = n \ 2
Do While n <> 0
tmp = Trim(CStr(n Mod 2)) & tmp
n = n \ 2
Loop
DecimalToBinary = tmp
End Function
Function Dec2Bin(ByVal DecimalIn As Variant, _
Optional NumberOfBits As Variant) As String
Dec2Bin = ""
DecimalIn = Int(CDec(DecimalIn))
Do While DecimalIn <> 0
Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin
DecimalIn = Int(DecimalIn / 2)
Loop
If Not IsMissing(NumberOfBits) Then
If Len(Dec2Bin) > NumberOfBits Then
Dec2Bin = "Error - Number exceeds specified bit size"
Else
Dec2Bin = Right$(String$(NumberOfBits, _
"0") & Dec2Bin, NumberOfBits)
End If
End If
End Function
Public Sub base()
Time1 = GetTickCount
Dim n As Long
Dim three(19) As Integer
Dim pow3(19) As Variant
Dim full3 As Variant
Dim trail As Variant
Dim check As Long
Dim len3 As Integer
Dim carry As Boolean
Dim i As Integer, j As Integer
Dim s As String
Dim t As String
pow3(0) = CDec(1)
For i = 1 To 19
pow3(i) = 3 * pow3(i - 1)
Next i
Debug.Print String$(5, " "); "iter"; String$(7, " "); "decimal"; String$(18, " "); "binary";
Debug.Print String$(30, " "); "ternary"
n = 0: full3 = 0: t = "0": s = "0"
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
n = 0: full3 = 1: t = "1": s = "1"
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
number = 0
n = 1
len3 = 0
full3 = 3
Do
three(0) = three(0) + 1
carry = False
If three(0) = 3 Then
three(0) = 0
carry = True
j = 1
Do While carry
three(j) = three(j) + 1
If three(j) = 3 Then
three(j) = 0
j = j + 1
Else
carry = False
End If
Loop
If len3 < j Then
trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)
len3 = j
full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail
For i = 0 To j - 1
full3 = full3 - 2 * pow3(len3 - i)
Next i
full3 = full3 + 1
Else
full3 = full3 + pow3(len3 + 2)
For i = 0 To j - 1
full3 = full3 - 2 * pow3(len3 - i)
Next i
full3 = full3 + pow3(len3 - j)
End If
Else
full3 = full3 + pow3(len3 + 2) + pow3(len3)
End If
s = ""
For i = 0 To len3
s = s & CStr(three(i))
Next i
t = Dec2Bin(full3)
If t = StrReverse(t) Then
number = number + 1
s = StrReverse(s) & "1" & s
If n < 200000 Then
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
If number = 4 Then
Debug.Print "Completed in"; (GetTickCount - Time1) / 1000; "seconds"
Time2 = GetTickCount
Application.ScreenUpdating = False
End If
Else
Debug.Print n, full3, Len(t), t, Len(s), s
Debug.Print "Completed in"; (Time2 - Time1) / 1000; "seconds";
Time3 = GetTickCount
End If
End If
n = n + 1
Loop Until number = 5
Debug.Print "Completed in"; (Time3 - Time1) / 1000; "seconds"
Application.ScreenUpdating = True
End Sub
| from itertools import islice
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
def baseN(num,b):
if num == 0: return "0"
result = ""
while num != 0:
num, d = divmod(num, b)
result += digits[d]
return result[::-1]
def pal2(num):
if num == 0 or num == 1: return True
based = bin(num)[2:]
return based == based[::-1]
def pal_23():
yield 0
yield 1
n = 1
while True:
n += 1
b = baseN(n, 3)
revb = b[::-1]
for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),
'{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):
t = int(trial, 3)
if pal2(t):
yield t
for pal23 in islice(pal_23(), 6):
print(pal23, baseN(pal23, 3), baseN(pal23, 2))
|
Convert this VB block to Python, preserving its control flow and logic. | Public Declare Function GetTickCount Lib "kernel32.dll" () As Long
Private Function DecimalToBinary(DecimalNum As Long) As String
Dim tmp As String
Dim n As Long
n = DecimalNum
tmp = Trim(CStr(n Mod 2))
n = n \ 2
Do While n <> 0
tmp = Trim(CStr(n Mod 2)) & tmp
n = n \ 2
Loop
DecimalToBinary = tmp
End Function
Function Dec2Bin(ByVal DecimalIn As Variant, _
Optional NumberOfBits As Variant) As String
Dec2Bin = ""
DecimalIn = Int(CDec(DecimalIn))
Do While DecimalIn <> 0
Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin
DecimalIn = Int(DecimalIn / 2)
Loop
If Not IsMissing(NumberOfBits) Then
If Len(Dec2Bin) > NumberOfBits Then
Dec2Bin = "Error - Number exceeds specified bit size"
Else
Dec2Bin = Right$(String$(NumberOfBits, _
"0") & Dec2Bin, NumberOfBits)
End If
End If
End Function
Public Sub base()
Time1 = GetTickCount
Dim n As Long
Dim three(19) As Integer
Dim pow3(19) As Variant
Dim full3 As Variant
Dim trail As Variant
Dim check As Long
Dim len3 As Integer
Dim carry As Boolean
Dim i As Integer, j As Integer
Dim s As String
Dim t As String
pow3(0) = CDec(1)
For i = 1 To 19
pow3(i) = 3 * pow3(i - 1)
Next i
Debug.Print String$(5, " "); "iter"; String$(7, " "); "decimal"; String$(18, " "); "binary";
Debug.Print String$(30, " "); "ternary"
n = 0: full3 = 0: t = "0": s = "0"
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
n = 0: full3 = 1: t = "1": s = "1"
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
number = 0
n = 1
len3 = 0
full3 = 3
Do
three(0) = three(0) + 1
carry = False
If three(0) = 3 Then
three(0) = 0
carry = True
j = 1
Do While carry
three(j) = three(j) + 1
If three(j) = 3 Then
three(j) = 0
j = j + 1
Else
carry = False
End If
Loop
If len3 < j Then
trail = full3 - (n - 1) * pow3(len3 + 2) - pow3(len3 + 1)
len3 = j
full3 = n * pow3(len3 + 2) + pow3(len3 + 1) + 3 * trail
For i = 0 To j - 1
full3 = full3 - 2 * pow3(len3 - i)
Next i
full3 = full3 + 1
Else
full3 = full3 + pow3(len3 + 2)
For i = 0 To j - 1
full3 = full3 - 2 * pow3(len3 - i)
Next i
full3 = full3 + pow3(len3 - j)
End If
Else
full3 = full3 + pow3(len3 + 2) + pow3(len3)
End If
s = ""
For i = 0 To len3
s = s & CStr(three(i))
Next i
t = Dec2Bin(full3)
If t = StrReverse(t) Then
number = number + 1
s = StrReverse(s) & "1" & s
If n < 200000 Then
Debug.Print String$(8 - Len(CStr(n)), " "); n; String$(12 - Len(CStr(full3)), " ");
Debug.Print full3; String$((41 - Len(t)) / 2, " "); t; String$((41 - Len(t)) / 2, " ");
Debug.Print String$((31 - Len(s)) / 2, " "); s
If number = 4 Then
Debug.Print "Completed in"; (GetTickCount - Time1) / 1000; "seconds"
Time2 = GetTickCount
Application.ScreenUpdating = False
End If
Else
Debug.Print n, full3, Len(t), t, Len(s), s
Debug.Print "Completed in"; (Time2 - Time1) / 1000; "seconds";
Time3 = GetTickCount
End If
End If
n = n + 1
Loop Until number = 5
Debug.Print "Completed in"; (Time3 - Time1) / 1000; "seconds"
Application.ScreenUpdating = True
End Sub
| from itertools import islice
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
def baseN(num,b):
if num == 0: return "0"
result = ""
while num != 0:
num, d = divmod(num, b)
result += digits[d]
return result[::-1]
def pal2(num):
if num == 0 or num == 1: return True
based = bin(num)[2:]
return based == based[::-1]
def pal_23():
yield 0
yield 1
n = 1
while True:
n += 1
b = baseN(n, 3)
revb = b[::-1]
for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),
'{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):
t = int(trial, 3)
if pal2(t):
yield t
for pal23 in islice(pal_23(), 6):
print(pal23, baseN(pal23, 3), baseN(pal23, 2))
|
Change the programming language of this snippet from VB to Python without modifying what it does. | Module Module1
Sub Main()
Dim bufferHeight = Console.BufferHeight
Dim bufferWidth = Console.BufferWidth
Dim windowHeight = Console.WindowHeight
Dim windowWidth = Console.WindowWidth
Console.Write("Buffer Height: ")
Console.WriteLine(bufferHeight)
Console.Write("Buffer Width: ")
Console.WriteLine(bufferWidth)
Console.Write("Window Height: ")
Console.WriteLine(windowHeight)
Console.Write("Window Width: ")
Console.WriteLine(windowWidth)
End Sub
End Module
| import os
def get_windows_terminal():
from ctypes import windll, create_string_buffer
h = windll.kernel32.GetStdHandle(-12)
csbi = create_string_buffer(22)
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
if not res: return 80, 25
import struct
(bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy)\
= struct.unpack("hhhhHhhhhhh", csbi.raw)
width = right - left + 1
height = bottom - top + 1
return width, height
def get_linux_terminal():
width = os.popen('tput cols', 'r').readline()
height = os.popen('tput lines', 'r').readline()
return int(width), int(height)
print get_linux_terminal() if os.name == 'posix' else get_windows_terminal()
|
Generate an equivalent Python version of this VB code. | Module Module1
Sub Main()
Dim bufferHeight = Console.BufferHeight
Dim bufferWidth = Console.BufferWidth
Dim windowHeight = Console.WindowHeight
Dim windowWidth = Console.WindowWidth
Console.Write("Buffer Height: ")
Console.WriteLine(bufferHeight)
Console.Write("Buffer Width: ")
Console.WriteLine(bufferWidth)
Console.Write("Window Height: ")
Console.WriteLine(windowHeight)
Console.Write("Window Width: ")
Console.WriteLine(windowWidth)
End Sub
End Module
| import os
def get_windows_terminal():
from ctypes import windll, create_string_buffer
h = windll.kernel32.GetStdHandle(-12)
csbi = create_string_buffer(22)
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
if not res: return 80, 25
import struct
(bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy)\
= struct.unpack("hhhhHhhhhhh", csbi.raw)
width = right - left + 1
height = bottom - top + 1
return width, height
def get_linux_terminal():
width = os.popen('tput cols', 'r').readline()
height = os.popen('tput lines', 'r').readline()
return int(width), int(height)
print get_linux_terminal() if os.name == 'posix' else get_windows_terminal()
|
Transform the following VB implementation into Python, maintaining the same output and logic. | Enum states
READY
WAITING
DISPENSE
REFUND
QU1T
End Enum
Public Sub finite_state_machine()
Dim state As Integer: state = READY: ch = " "
Do While True
Debug.Print ch
Select Case state
Case READY: Debug.Print "Machine is READY. (D)eposit or (Q)uit :"
Do While True
If ch = "D" Then
state = WAITING
Exit Do
End If
If ch = "Q" Then
state = QU1T
Exit Do
End If
ch = InputBox("Machine is READY. (D)eposit or (Q)uit :")
Loop
Case WAITING: Debug.Print "(S)elect product or choose to (R)efund :"
Do While True
If ch = "S" Then
state = DISPENSE
Exit Do
End If
If ch = "R" Then
state = REFUND
Exit Do
End If
ch = InputBox("(S)elect product or choose to (R)efund :")
Loop
Case DISPENSE: Debug.Print "Dispensing product..."
Do While True
If ch = "C" Then
state = READY
Exit Do
End If
ch = InputBox("Please (C)ollect product. :")
Loop
Case REFUND: Debug.Print "Please collect refund."
state = READY
ch = " "
Case QU1T: Debug.Print "Thank you, shutting down now."
Exit Sub
End Select
Loop
End Sub
|
states = { 'ready':{
'prompt' : 'Machine ready: (d)eposit, or (q)uit?',
'responses' : ['d','q']},
'waiting':{
'prompt' : 'Machine waiting: (s)elect, or (r)efund?',
'responses' : ['s','r']},
'dispense' : {
'prompt' : 'Machine dispensing: please (r)emove product',
'responses' : ['r']},
'refunding' : {
'prompt' : 'Refunding money',
'responses' : []},
'exit' :{}
}
transitions = { 'ready': {
'd': 'waiting',
'q': 'exit'},
'waiting' : {
's' : 'dispense',
'r' : 'refunding'},
'dispense' : {
'r' : 'ready'},
'refunding' : {
'' : 'ready'}}
def Acceptor(prompt, valids):
if not valids:
print(prompt)
return ''
else:
while True:
resp = input(prompt)[0].lower()
if resp in valids:
return resp
def finite_state_machine(initial_state, exit_state):
response = True
next_state = initial_state
current_state = states[next_state]
while response != exit_state:
response = Acceptor(current_state['prompt'], current_state['responses'])
next_state = transitions[next_state][response]
current_state = states[next_state]
if __name__ == "__main__":
finite_state_machine('ready','q')
|
Port the provided VB code into Python while preserving the original functionality. | Enum states
READY
WAITING
DISPENSE
REFUND
QU1T
End Enum
Public Sub finite_state_machine()
Dim state As Integer: state = READY: ch = " "
Do While True
Debug.Print ch
Select Case state
Case READY: Debug.Print "Machine is READY. (D)eposit or (Q)uit :"
Do While True
If ch = "D" Then
state = WAITING
Exit Do
End If
If ch = "Q" Then
state = QU1T
Exit Do
End If
ch = InputBox("Machine is READY. (D)eposit or (Q)uit :")
Loop
Case WAITING: Debug.Print "(S)elect product or choose to (R)efund :"
Do While True
If ch = "S" Then
state = DISPENSE
Exit Do
End If
If ch = "R" Then
state = REFUND
Exit Do
End If
ch = InputBox("(S)elect product or choose to (R)efund :")
Loop
Case DISPENSE: Debug.Print "Dispensing product..."
Do While True
If ch = "C" Then
state = READY
Exit Do
End If
ch = InputBox("Please (C)ollect product. :")
Loop
Case REFUND: Debug.Print "Please collect refund."
state = READY
ch = " "
Case QU1T: Debug.Print "Thank you, shutting down now."
Exit Sub
End Select
Loop
End Sub
|
states = { 'ready':{
'prompt' : 'Machine ready: (d)eposit, or (q)uit?',
'responses' : ['d','q']},
'waiting':{
'prompt' : 'Machine waiting: (s)elect, or (r)efund?',
'responses' : ['s','r']},
'dispense' : {
'prompt' : 'Machine dispensing: please (r)emove product',
'responses' : ['r']},
'refunding' : {
'prompt' : 'Refunding money',
'responses' : []},
'exit' :{}
}
transitions = { 'ready': {
'd': 'waiting',
'q': 'exit'},
'waiting' : {
's' : 'dispense',
'r' : 'refunding'},
'dispense' : {
'r' : 'ready'},
'refunding' : {
'' : 'ready'}}
def Acceptor(prompt, valids):
if not valids:
print(prompt)
return ''
else:
while True:
resp = input(prompt)[0].lower()
if resp in valids:
return resp
def finite_state_machine(initial_state, exit_state):
response = True
next_state = initial_state
current_state = states[next_state]
while response != exit_state:
response = Acceptor(current_state['prompt'], current_state['responses'])
next_state = transitions[next_state][response]
current_state = states[next_state]
if __name__ == "__main__":
finite_state_machine('ready','q')
|
Convert this VB snippet to Python and keep its semantics consistent. | Imports System.Numerics
Module Module1
ReadOnly BIG = BigInteger.Pow(10, 50) + 151
Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)
Dim n = BigInteger.Parse(ns)
Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)
Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)
If ls(n) <> 1 Then
Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)
End If
Dim a = BigInteger.Zero
Dim omega2 As BigInteger
Do
omega2 = (a * a + p - n) Mod p
If ls(omega2) = p - 1 Then
Exit Do
End If
a += 1
Loop
Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))
Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)
End Function
Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)
Dim s = Tuple.Create(a, BigInteger.One)
Dim nn = ((p + 1) >> 1) Mod p
While nn > 0
If nn Mod 2 = 1 Then
r = mul(r, s)
End If
s = mul(s, s)
nn >>= 1
End While
If r.Item2 <> 0 Then
Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)
End If
If r.Item1 * r.Item1 Mod p <> n Then
Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)
End If
Return Tuple.Create(r.Item1, p - r.Item1, True)
End Function
Sub Main()
Console.WriteLine(C("10", "13"))
Console.WriteLine(C("56", "101"))
Console.WriteLine(C("8218", "10007"))
Console.WriteLine(C("8219", "10007"))
Console.WriteLine(C("331575", "1000003"))
Console.WriteLine(C("665165880", "1000000007"))
Console.WriteLine(C("881398088036", "1000000000039"))
Console.WriteLine(C("34035243914635549601583369544560650254325084643201", ""))
End Sub
End Module
|
def convertToBase(n, b):
if(n < 2):
return [n];
temp = n;
ans = [];
while(temp != 0):
ans = [temp % b]+ ans;
temp /= b;
return ans;
def cipolla(n,p):
n %= p
if(n == 0 or n == 1):
return (n,-n%p)
phi = p - 1
if(pow(n, phi/2, p) != 1):
return ()
if(p%4 == 3):
ans = pow(n,(p+1)/4,p)
return (ans,-ans%p)
aa = 0
for i in xrange(1,p):
temp = pow((i*i-n)%p,phi/2,p)
if(temp == phi):
aa = i
break;
exponent = convertToBase((p+1)/2,2)
def cipollaMult((a,b),(c,d),w,p):
return ((a*c+b*d*w)%p,(a*d+b*c)%p)
x1 = (aa,1)
x2 = cipollaMult(x1,x1,aa*aa-n,p)
for i in xrange(1,len(exponent)):
if(exponent[i] == 0):
x2 = cipollaMult(x2,x1,aa*aa-n,p)
x1 = cipollaMult(x1,x1,aa*aa-n,p)
else:
x1 = cipollaMult(x1,x2,aa*aa-n,p)
x2 = cipollaMult(x2,x2,aa*aa-n,p)
return (x1[0],-x1[0]%p)
print "Roots of 2 mod 7: " +str(cipolla(2,7))
print "Roots of 8218 mod 10007: " +str(cipolla(8218,10007))
print "Roots of 56 mod 101: " +str(cipolla(56,101))
print "Roots of 1 mod 11: " +str(cipolla(1,11))
print "Roots of 8219 mod 10007: " +str(cipolla(8219,10007))
|
Convert this VB block to Python, preserving its control flow and logic. | Imports System.Numerics
Module Module1
ReadOnly BIG = BigInteger.Pow(10, 50) + 151
Function C(ns As String, ps As String) As Tuple(Of BigInteger, BigInteger, Boolean)
Dim n = BigInteger.Parse(ns)
Dim p = If(ps.Length > 0, BigInteger.Parse(ps), BIG)
Dim ls = Function(a0 As BigInteger) BigInteger.ModPow(a0, (p - 1) / 2, p)
If ls(n) <> 1 Then
Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)
End If
Dim a = BigInteger.Zero
Dim omega2 As BigInteger
Do
omega2 = (a * a + p - n) Mod p
If ls(omega2) = p - 1 Then
Exit Do
End If
a += 1
Loop
Dim mul = Function(aa As Tuple(Of BigInteger, BigInteger), bb As Tuple(Of BigInteger, BigInteger))
Return Tuple.Create((aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * omega2) Mod p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) Mod p)
End Function
Dim r = Tuple.Create(BigInteger.One, BigInteger.Zero)
Dim s = Tuple.Create(a, BigInteger.One)
Dim nn = ((p + 1) >> 1) Mod p
While nn > 0
If nn Mod 2 = 1 Then
r = mul(r, s)
End If
s = mul(s, s)
nn >>= 1
End While
If r.Item2 <> 0 Then
Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)
End If
If r.Item1 * r.Item1 Mod p <> n Then
Return Tuple.Create(BigInteger.Zero, BigInteger.Zero, False)
End If
Return Tuple.Create(r.Item1, p - r.Item1, True)
End Function
Sub Main()
Console.WriteLine(C("10", "13"))
Console.WriteLine(C("56", "101"))
Console.WriteLine(C("8218", "10007"))
Console.WriteLine(C("8219", "10007"))
Console.WriteLine(C("331575", "1000003"))
Console.WriteLine(C("665165880", "1000000007"))
Console.WriteLine(C("881398088036", "1000000000039"))
Console.WriteLine(C("34035243914635549601583369544560650254325084643201", ""))
End Sub
End Module
|
def convertToBase(n, b):
if(n < 2):
return [n];
temp = n;
ans = [];
while(temp != 0):
ans = [temp % b]+ ans;
temp /= b;
return ans;
def cipolla(n,p):
n %= p
if(n == 0 or n == 1):
return (n,-n%p)
phi = p - 1
if(pow(n, phi/2, p) != 1):
return ()
if(p%4 == 3):
ans = pow(n,(p+1)/4,p)
return (ans,-ans%p)
aa = 0
for i in xrange(1,p):
temp = pow((i*i-n)%p,phi/2,p)
if(temp == phi):
aa = i
break;
exponent = convertToBase((p+1)/2,2)
def cipollaMult((a,b),(c,d),w,p):
return ((a*c+b*d*w)%p,(a*d+b*c)%p)
x1 = (aa,1)
x2 = cipollaMult(x1,x1,aa*aa-n,p)
for i in xrange(1,len(exponent)):
if(exponent[i] == 0):
x2 = cipollaMult(x2,x1,aa*aa-n,p)
x1 = cipollaMult(x1,x1,aa*aa-n,p)
else:
x1 = cipollaMult(x1,x2,aa*aa-n,p)
x2 = cipollaMult(x2,x2,aa*aa-n,p)
return (x1[0],-x1[0]%p)
print "Roots of 2 mod 7: " +str(cipolla(2,7))
print "Roots of 8218 mod 10007: " +str(cipolla(8218,10007))
print "Roots of 56 mod 101: " +str(cipolla(56,101))
print "Roots of 1 mod 11: " +str(cipolla(1,11))
print "Roots of 8219 mod 10007: " +str(cipolla(8219,10007))
|
Convert this VB snippet to Python and keep its semantics consistent. | Private Sub sierpinski(Order_ As Integer, Side As Double)
Dim Circumradius As Double, Inradius As Double
Dim Height As Double, Diagonal As Double, HeightDiagonal As Double
Dim Pi As Double, p(5) As String, Shp As Shape
Circumradius = Sqr(50 + 10 * Sqr(5)) / 10
Inradius = Sqr(25 + 10 * Sqr(5)) / 10
Height = Circumradius + Inradius
Diagonal = (1 + Sqr(5)) / 2
HeightDiagonal = Sqr(10 + 2 * Sqr(5)) / 4
Pi = WorksheetFunction.Pi
Ratio = Height / (2 * Height + HeightDiagonal)
Set Shp = ThisWorkbook.Worksheets(1).Shapes.AddShape(msoShapeRegularPentagon, _
2 * Side, 3 * Side / 2 + (Circumradius - Inradius) * Side, Diagonal * Side, Height * Side)
p(0) = Shp.Name
Shp.Rotation = 180
Shp.Line.Weight = 0
For j = 1 To Order_
For i = 0 To 4
Set Shp = Shp.Duplicate
p(i + 1) = Shp.Name
If i = 0 Then Shp.Rotation = 0
Shp.Left = 2 * Side + Side * Inradius * 2 * Cos(2 * Pi * (i - 1 / 4) / 5)
Shp.Top = 3 * Side / 2 + Side * Inradius * 2 * Sin(2 * Pi * (i - 1 / 4) / 5)
Shp.Visible = msoTrue
Next i
Set Shp = ThisWorkbook.Worksheets(1).Shapes.Range(p()).Group
p(0) = Shp.Name
If j < Order_ Then
Shp.ScaleHeight Ratio, False
Shp.ScaleWidth Ratio, False
Shp.Rotation = 180
Shp.Left = 2 * Side
Shp.Top = 3 * Side / 2 + (Circumradius - Inradius) * Side
End If
Next j
End Sub
Public Sub main()
sierpinski Order_:=5, Side:=200
End Sub
| from turtle import *
import math
speed(0)
hideturtle()
part_ratio = 2 * math.cos(math.radians(72))
side_ratio = 1 / (part_ratio + 2)
hide_turtles = True
path_color = "black"
fill_color = "black"
def pentagon(t, s):
t.color(path_color, fill_color)
t.pendown()
t.right(36)
t.begin_fill()
for i in range(5):
t.forward(s)
t.right(72)
t.end_fill()
def sierpinski(i, t, s):
t.setheading(0)
new_size = s * side_ratio
if i > 1:
i -= 1
for j in range(4):
t.right(36)
short = s * side_ratio / part_ratio
dist = [short, s, s, short][j]
spawn = Turtle()
if hide_turtles:spawn.hideturtle()
spawn.penup()
spawn.setposition(t.position())
spawn.setheading(t.heading())
spawn.forward(dist)
sierpinski(i, spawn, new_size)
sierpinski(i, t, new_size)
else:
pentagon(t, s)
del t
def main():
t = Turtle()
t.hideturtle()
t.penup()
screen = t.getscreen()
y = screen.window_height()
t.goto(0, y/2-20)
i = 5
size = 300
size *= part_ratio
sierpinski(i, t, size)
main()
|
Transform the following VB implementation into Python, maintaining the same output and logic. | Function rep_string(s)
max_len = Int(Len(s)/2)
tmp = ""
If max_len = 0 Then
rep_string = "No Repeating String"
Exit Function
End If
For i = 1 To max_len
If InStr(i+1,s,tmp & Mid(s,i,1))Then
tmp = tmp & Mid(s,i,1)
Else
Exit For
End If
Next
Do While Len(tmp) > 0
If Mid(s,Len(tmp)+1,Len(tmp)) = tmp Then
rep_string = tmp
Exit Do
Else
tmp = Mid(tmp,1,Len(tmp)-1)
End If
Loop
If Len(tmp) > 0 Then
rep_string = tmp
Else
rep_string = "No Repeating String"
End If
End Function
arr = Array("1001110011","1110111011","0010010010","1010101010",_
"1111111111","0100101101","0100100","101","11","00","1")
For n = 0 To UBound(arr)
WScript.StdOut.Write arr(n) & ": " & rep_string(arr(n))
WScript.StdOut.WriteLine
Next
| def is_repeated(text):
'check if the first part of the string is repeated throughout the string'
for x in range(len(text)//2, 0, -1):
if text.startswith(text[x:]): return x
return 0
matchstr =
for line in matchstr.split():
ln = is_repeated(line)
print('%r has a repetition length of %i i.e. %s'
% (line, ln, repr(line[:ln]) if ln else '*not* a rep-string'))
|
Change the programming language of this snippet from VB to Python without modifying what it does. | Debug.Print "Tom said, ""The fox ran away."""
Debug.Print "Tom said,
| 'c' == "c"
'text' == "text"
' " '
" ' "
'\x20' == ' '
u'unicode string'
u'\u05d0'
|
Write the same code in Python as shown below in VB. | TYPE syswindowstru
screenheight AS INTEGER
screenwidth AS INTEGER
maxheight AS INTEGER
maxwidth AS INTEGER
END TYPE
DIM syswindow AS syswindowstru
syswindow.screenwidth = Screen.Width / Screen.TwipsPerPixelX
syswindow.screenheight=Screen.Height / Screen.TwipsPerPixelY
|
import tkinter as tk
root = tk.Tk()
root.state('zoomed')
root.update_idletasks()
tk.Label(root, text=(str(root.winfo_width())+ " x " +str(root.winfo_height())),
font=("Helvetica", 25)).pack()
root.mainloop()
|
Rewrite this program in Python while keeping its functionality equivalent to the VB version. |
Enum fruits
apple
banana
cherry
End Enum
Enum fruits2
pear = 5
mango = 10
kiwi = 20
pineapple = 20
End Enum
Sub test()
Dim f As fruits
f = apple
Debug.Print "apple equals "; f
Debug.Print "kiwi equals "; kiwi
Debug.Print "cherry plus kiwi plus pineapple equals "; cherry + kiwi + pineapple
End Sub
| >>> from enum import Enum
>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')
>>> Contact.__members__
mappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)]))
>>>
>>>
>>> class Contact2(Enum):
FIRST_NAME = 1
LAST_NAME = 2
PHONE = 3
>>> Contact2.__members__
mappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))
>>>
|
Translate the given VB code snippet into Python without altering its behavior. | Sub pentagram()
With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400)
.Fill.ForeColor.RGB = RGB(255, 0, 0)
.Line.Weight = 3
.Line.ForeColor.RGB = RGB(0, 0, 255)
End With
End Sub
| import turtle
turtle.bgcolor("green")
t = turtle.Turtle()
t.color("red", "blue")
t.begin_fill()
for i in range(0, 5):
t.forward(200)
t.right(144)
t.end_fill()
|
Ensure the translated Python code behaves exactly like the original VB snippet. | Sub pentagram()
With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400)
.Fill.ForeColor.RGB = RGB(255, 0, 0)
.Line.Weight = 3
.Line.ForeColor.RGB = RGB(0, 0, 255)
End With
End Sub
| import turtle
turtle.bgcolor("green")
t = turtle.Turtle()
t.color("red", "blue")
t.begin_fill()
for i in range(0, 5):
t.forward(200)
t.right(144)
t.end_fill()
|
Port the following code from VB to Python with equivalent syntax and logic. | Function parse_ip(addr)
Set ipv4_pattern = New RegExp
ipv4_pattern.Global = True
ipv4_pattern.Pattern = "(\d{1,3}\.){3}\d{1,3}"
Set ipv6_pattern = New RegExp
ipv6_pattern.Global = True
ipv6_pattern.Pattern = "([0-9a-fA-F]{0,4}:){2}[0-9a-fA-F]{0,4}"
If ipv4_pattern.Test(addr) Then
port = Split(addr,":")
octet = Split(port(0),".")
ipv4_hex = ""
For i = 0 To UBound(octet)
If octet(i) <= 255 And octet(i) >= 0 Then
ipv4_hex = ipv4_hex & Right("0" & Hex(octet(i)),2)
Else
ipv4_hex = "Erroneous Address"
Exit For
End If
Next
parse_ip = "Test Case: " & addr & vbCrLf &_
"Address: " & ipv4_hex & vbCrLf
If UBound(port) = 1 Then
If port(1) <= 65535 And port(1) >= 0 Then
parse_ip = parse_ip & "Port: " & port(1) & vbCrLf
Else
parse_ip = parse_ip & "Port: Invalid" & vbCrLf
End If
End If
End If
If ipv6_pattern.Test(addr) Then
parse_ip = "Test Case: " & addr & vbCrLf
port_v6 = "Port: "
ipv6_hex = ""
If InStr(1,addr,"[") Then
port_v6 = port_v6 & Mid(addr,InStrRev(addr,"]")+2,Len(addr)-Len(Mid(addr,1,InStrRev(addr,"]")+1)))
addr = Mid(addr,InStrRev(addr,"[")+1,InStrRev(addr,"]")-(InStrRev(addr,"[")+1))
End If
word = Split(addr,":")
word_count = 0
For i = 0 To UBound(word)
If word(i) = "" Then
If i < UBound(word) Then
If Int((7-(i+1))/2) = 1 Then
k = 1
ElseIf UBound(word) < 6 Then
k = Int((7-(i+1))/2)
ElseIf UBound(word) >= 6 Then
k = Int((7-(i+1))/2)-1
End If
For j = 0 To k
ipv6_hex = ipv6_hex & "0000"
word_count = word_count + 1
Next
Else
For j = 0 To (7-word_count)
ipv6_hex = ipv6_hex & "0000"
Next
End If
Else
ipv6_hex = ipv6_hex & Right("0000" & word(i),4)
word_count = word_count + 1
End If
Next
parse_ip = parse_ip & "Address: " & ipv6_hex &_
vbCrLf & port_v6 & vbCrLf
End If
If ipv4_pattern.Test(addr) = False And ipv6_pattern.Test(addr) = False Then
parse_ip = "Test Case: " & addr & vbCrLf &_
"Address: Invalid Address" & vbCrLf
End If
End Function
ip_arr = Array("127.0.0.1","127.0.0.1:80","::1",_
"[::1]:80","2605:2700:0:3::4713:93e3","[2605:2700:0:3::4713:93e3]:80","RosettaCode")
For n = 0 To UBound(ip_arr)
WScript.StdOut.Write parse_ip(ip_arr(n)) & vbCrLf
Next
| from ipaddress import ip_address
from urllib.parse import urlparse
tests = [
"127.0.0.1",
"127.0.0.1:80",
"::1",
"[::1]:80",
"::192.168.0.1",
"2605:2700:0:3::4713:93e3",
"[2605:2700:0:3::4713:93e3]:80" ]
def parse_ip_port(netloc):
try:
ip = ip_address(netloc)
port = None
except ValueError:
parsed = urlparse('//{}'.format(netloc))
ip = ip_address(parsed.hostname)
port = parsed.port
return ip, port
for address in tests:
ip, port = parse_ip_port(address)
hex_ip = {4:'{:08X}', 6:'{:032X}'}[ip.version].format(int(ip))
print("{:39s} {:>32s} IPv{} port={}".format(
str(ip), hex_ip, ip.version, port ))
|
Port the following code from VB to Python with equivalent syntax and logic. | Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
"\unixdict.txt",1)
Set objKeyMap = CreateObject("Scripting.Dictionary")
With objKeyMap
.Add "ABC", "2" : .Add "DEF", "3" : .Add "GHI", "4" : .Add "JKL", "5"
.Add "MNO", "6" : .Add "PQRS", "7" : .Add "TUV", "8" : .Add "WXYZ", "9"
End With
TotalWords = 0
UniqueCombinations = 0
Set objUniqueWords = CreateObject("Scripting.Dictionary")
Set objMoreThanOneWord = CreateObject("Scripting.Dictionary")
Do Until objInFile.AtEndOfStream
Word = objInFile.ReadLine
c = 0
Num = ""
If Word <> "" Then
For i = 1 To Len(Word)
For Each Key In objKeyMap.Keys
If InStr(1,Key,Mid(Word,i,1),1) > 0 Then
Num = Num & objKeyMap.Item(Key)
c = c + 1
End If
Next
Next
If c = Len(Word) Then
TotalWords = TotalWords + 1
If objUniqueWords.Exists(Num) = False Then
objUniqueWords.Add Num, ""
UniqueCombinations = UniqueCombinations + 1
Else
If objMoreThanOneWord.Exists(Num) = False Then
objMoreThanOneWord.Add Num, ""
End If
End If
End If
End If
Loop
WScript.Echo "There are " & TotalWords & " words in ""unixdict.txt"" which can be represented by the digit key mapping." & vbCrLf &_
"They require " & UniqueCombinations & " digit combinations to represent them." & vbCrLf &_
objMoreThanOneWord.Count & " digit combinations represent Textonyms."
objInFile.Close
| from collections import defaultdict
import urllib.request
CH2NUM = {ch: str(num) for num, chars in enumerate('abc def ghi jkl mno pqrs tuv wxyz'.split(), 2) for ch in chars}
URL = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'
def getwords(url):
return urllib.request.urlopen(url).read().decode("utf-8").lower().split()
def mapnum2words(words):
number2words = defaultdict(list)
reject = 0
for word in words:
try:
number2words[''.join(CH2NUM[ch] for ch in word)].append(word)
except KeyError:
reject += 1
return dict(number2words), reject
def interactiveconversions():
global inp, ch, num
while True:
inp = input("\nType a number or a word to get the translation and textonyms: ").strip().lower()
if inp:
if all(ch in '23456789' for ch in inp):
if inp in num2words:
print(" Number {0} has the following textonyms in the dictionary: {1}".format(inp, ', '.join(
num2words[inp])))
else:
print(" Number {0} has no textonyms in the dictionary.".format(inp))
elif all(ch in CH2NUM for ch in inp):
num = ''.join(CH2NUM[ch] for ch in inp)
print(" Word {0} is{1} in the dictionary and is number {2} with textonyms: {3}".format(
inp, ('' if inp in wordset else "n't"), num, ', '.join(num2words[num])))
else:
print(" I don't understand %r" % inp)
else:
print("Thank you")
break
if __name__ == '__main__':
words = getwords(URL)
print("Read %i words from %r" % (len(words), URL))
wordset = set(words)
num2words, reject = mapnum2words(words)
morethan1word = sum(1 for w in num2words if len(num2words[w]) > 1)
maxwordpernum = max(len(values) for values in num2words.values())
print(.format(len(words) - reject, URL, len(num2words), morethan1word))
print("\nThe numbers mapping to the most words map to %i words each:" % maxwordpernum)
maxwpn = sorted((key, val) for key, val in num2words.items() if len(val) == maxwordpernum)
for num, wrds in maxwpn:
print(" %s maps to: %s" % (num, ', '.join(wrds)))
interactiveconversions()
|
Change the following VB code into Python without altering its purpose. | Public Function RangeExtraction(AList) As String
Const RangeDelim = "-"
Dim result As String
Dim InRange As Boolean
Dim Posn, ub, lb, rangestart, rangelen As Integer
result = ""
ub = UBound(AList)
lb = LBound(AList)
Posn = lb
While Posn < ub
rangestart = Posn
rangelen = 0
InRange = True
While InRange
rangelen = rangelen + 1
If Posn = ub Then
InRange = False
Else
InRange = (AList(Posn + 1) = AList(Posn) + 1)
Posn = Posn + 1
End If
Wend
If rangelen > 2 Then
result = result & "," & Format$(AList(rangestart)) & RangeDelim & Format$(AList(rangestart + rangelen - 1))
Else
For i = rangestart To rangestart + rangelen - 1
result = result & "," & Format$(AList(i))
Next
End If
Posn = rangestart + rangelen
Wend
RangeExtraction = Mid$(result, 2)
End Function
Public Sub RangeTest()
Dim MyList As Variant
MyList = Array(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39)
Debug.Print "a) "; RangeExtraction(MyList)
Dim MyOtherList(1 To 20) As Integer
MyOtherList(1) = -6
MyOtherList(2) = -3
MyOtherList(3) = -2
MyOtherList(4) = -1
MyOtherList(5) = 0
MyOtherList(6) = 1
MyOtherList(7) = 3
MyOtherList(8) = 4
MyOtherList(9) = 5
MyOtherList(10) = 7
MyOtherList(11) = 8
MyOtherList(12) = 9
MyOtherList(13) = 10
MyOtherList(14) = 11
MyOtherList(15) = 14
MyOtherList(16) = 15
MyOtherList(17) = 17
MyOtherList(18) = 18
MyOtherList(19) = 19
MyOtherList(20) = 20
Debug.Print "b) "; RangeExtraction(MyOtherList)
End Sub
| def range_extract(lst):
'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints'
lenlst = len(lst)
i = 0
while i< lenlst:
low = lst[i]
while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1
hi = lst[i]
if hi - low >= 2:
yield (low, hi)
elif hi - low == 1:
yield (low,)
yield (hi,)
else:
yield (low,)
i += 1
def printr(ranges):
print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r)
for r in ranges ) )
if __name__ == '__main__':
for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7,
8, 9, 10, 11, 14, 15, 17, 18, 19, 20],
[0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]:
printr(range_extract(lst))
|
Convert this VB snippet to Python and keep its semantics consistent. |
Set objfso = CreateObject("Scripting.FileSystemObject")
Set objinfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_
"\triangle.txt",1,False)
row = Split(objinfile.ReadAll,vbCrLf)
For i = UBound(row) To 0 Step -1
row(i) = Split(row(i)," ")
If i < UBound(row) Then
For j = 0 To UBound(row(i))
If (row(i)(j) + row(i+1)(j)) > (row(i)(j) + row(i+1)(j+1)) Then
row(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j))
Else
row(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j+1))
End If
Next
End If
Next
WScript.Echo row(0)(0)
objinfile.Close
Set objfso = Nothing
| fun maxpathsum(t):
let a = val t
for i in a.length-1..-1..1, c in linearindices a[r]:
a[r, c] += max(a[r+1, c], a[r=1, c+1])
return a[1, 1]
let test = [
[55],
[94, 48],
[95, 30, 96],
[77, 71, 26, 67],
[97, 13, 76, 38, 45],
[07, 36, 79, 16, 37, 68],
[48, 07, 09, 18, 70, 26, 06],
[18, 72, 79, 46, 59, 79, 29, 90],
[20, 76, 87, 11, 32, 07, 07, 49, 18],
[27, 83, 58, 35, 71, 11, 25, 57, 29, 85],
[14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55],
[02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23],
[92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42],
[56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72],
[44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36],
[85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52],
[06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15],
[27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]
]
@print maxpathsum test
|
Change the programming language of this snippet from VB to Python without modifying what it does. | Public n As Variant
Private Sub init()
n = [{-1,0;-1,1;0,1;1,1;1,0;1,-1;0,-1;-1,-1;-1,0}]
End Sub
Private Function AB(text As Variant, y As Integer, x As Integer, step As Integer) As Variant
Dim wtb As Integer
Dim bn As Integer
Dim prev As String: prev = "#"
Dim next_ As String
Dim p2468 As String
For i = 1 To UBound(n)
next_ = Mid(text(y + n(i, 1)), x + n(i, 2), 1)
wtb = wtb - (prev = "." And next_ <= "#")
bn = bn - (i > 1 And next_ <= "#")
If (i And 1) = 0 Then p2468 = p2468 & prev
prev = next_
Next i
If step = 2 Then
p2468 = Mid(p2468, 3, 2) & Mid(p2468, 1, 2)
End If
Dim ret(2) As Variant
ret(0) = wtb
ret(1) = bn
ret(2) = p2468
AB = ret
End Function
Private Sub Zhang_Suen(text As Variant)
Dim wtb As Integer
Dim bn As Integer
Dim changed As Boolean, changes As Boolean
Dim p2468 As String
Dim x As Integer, y As Integer, step As Integer
Do While True
changed = False
For step = 1 To 2
changes = False
For y = 1 To UBound(text) - 1
For x = 2 To Len(text(y)) - 1
If Mid(text(y), x, 1) = "#" Then
ret = AB(text, y, x, step)
wtb = ret(0)
bn = ret(1)
p2468 = ret(2)
If wtb = 1 _
And bn >= 2 And bn <= 6 _
And InStr(1, Mid(p2468, 1, 3), ".") _
And InStr(1, Mid(p2468, 2, 3), ".") Then
changes = True
text(y) = Left(text(y), x - 1) & "!" & Right(text(y), Len(text(y)) - x)
End If
End If
Next x
Next y
If changes Then
For y = 1 To UBound(text) - 1
text(y) = Replace(text(y), "!", ".")
Next y
changed = True
End If
Next step
If Not changed Then Exit Do
Loop
Debug.Print Join(text, vbCrLf)
End Sub
Public Sub main()
init
Dim Small_rc(9) As String
Small_rc(0) = "................................"
Small_rc(1) = ".#########.......########......."
Small_rc(2) = ".###...####.....####..####......"
Small_rc(3) = ".###....###.....###....###......"
Small_rc(4) = ".###...####.....###............."
Small_rc(5) = ".#########......###............."
Small_rc(6) = ".###.####.......###....###......"
Small_rc(7) = ".###..####..###.####..####.###.."
Small_rc(8) = ".###...####.###..########..###.."
Small_rc(9) = "................................"
Zhang_Suen (Small_rc)
End Sub
|
beforeTxt =
smallrc01 =
rc01 =
def intarray(binstring):
return [[1 if ch == '1' else 0 for ch in line]
for line in binstring.strip().split()]
def chararray(intmatrix):
return '\n'.join(''.join(str(p) for p in row) for row in intmatrix)
def toTxt(intmatrix):
Return 8-neighbours of point p1 of picture, in order'''
i = image
x1, y1, x_1, y_1 = x+1, y-1, x-1, y+1
return [i[y1][x], i[y1][x1], i[y][x1], i[y_1][x1],
i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1]]
def transitions(neighbours):
n = neighbours + neighbours[0:1]
return sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:]))
def zhangSuen(image):
changing1 = changing2 = [(-1, -1)]
while changing1 or changing2:
changing1 = []
for y in range(1, len(image) - 1):
for x in range(1, len(image[0]) - 1):
P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)
if (image[y][x] == 1 and
P4 * P6 * P8 == 0 and
P2 * P4 * P6 == 0 and
transitions(n) == 1 and
2 <= sum(n) <= 6):
changing1.append((x,y))
for x, y in changing1: image[y][x] = 0
changing2 = []
for y in range(1, len(image) - 1):
for x in range(1, len(image[0]) - 1):
P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)
if (image[y][x] == 1 and
P2 * P6 * P8 == 0 and
P2 * P4 * P8 == 0 and
transitions(n) == 1 and
2 <= sum(n) <= 6):
changing2.append((x,y))
for x, y in changing2: image[y][x] = 0
return image
if __name__ == '__main__':
for picture in (beforeTxt, smallrc01, rc01):
image = intarray(picture)
print('\nFrom:\n%s' % toTxt(image))
after = zhangSuen(image)
print('\nTo thinned:\n%s' % toTxt(after))
|
Produce a functionally identical Python code for the snippet given in VB. | Option Strict On
Option Explicit On
Imports System.IO
Module vMain
Public Sub Main
Dim s As Integer() = New Integer(){1, 2, 2, 3, 4, 4, 5}
For i As Integer = 0 To Ubound(s)
Dim curr As Integer = s(i)
Dim prev As Integer
If i > 1 AndAlso curr = prev Then
Console.Out.WriteLine(i)
End If
prev = curr
Next i
End Sub
End Module
| s = [1, 2, 2, 3, 4, 4, 5]
for i in range(len(s)):
curr = s[i]
if i > 0 and curr == prev:
print(i)
prev = curr
|
Preserve the algorithm and functionality while converting the code from VB to Python. | 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:
if ori<0 then ori = ori+pi*2
end sub
public sub lt(i):
ori=(ori + i*iang)
if ori>(pi*2) then ori=ori-pi*2
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
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 koch (n,le)
if n=0 then x.fw le :exit sub
koch n-1, le/3
x.lt 1
koch n-1, le/3
x.rt 2
koch n-1, le/3
x.lt 1
koch n-1, le/3
end sub
dim x,i
set x=new turtle
x.iangle=60
x.orient=0
x.incr=3
x.x=100:x.y=300
for i=0 to 3
koch 7,100
x.rt 2
next
set x=nothing
| l = 300
def setup():
size(400, 400)
background(0, 0, 255)
stroke(255)
translate(width / 2.0, height / 2.0)
translate(-l / 2.0, l * sqrt(3) / 6.0)
for i in range(4):
kcurve(0, l)
rotate(radians(120))
translate(-l, 0)
def kcurve(x1, x2):
s = (x2 - x1) / 3.0
if s < 5:
pushMatrix()
translate(x1, 0)
line(0, 0, s, 0)
line(2 * s, 0, 3 * s, 0)
translate(s, 0)
rotate(radians(60))
line(0, 0, s, 0)
translate(s, 0)
rotate(radians(-120))
line(0, 0, s, 0)
popMatrix()
return
pushMatrix()
translate(x1, 0)
kcurve(0, s)
kcurve(2 * s, 3 * s)
translate(s, 0)
rotate(radians(60))
kcurve(0, s)
translate(s, 0)
rotate(radians(-120))
kcurve(0, s)
popMatrix()
|
Generate a Python translation of this VB snippet without changing its computational steps. | Sub draw()
Dim sh As Shape, sl As Shape
Set sh = ActiveDocument.Shapes.AddCanvas(100, 100, 320, 240)
Set sl = sh.CanvasItems.AddLine(100, 100, 101, 100)
sl.Line.ForeColor.RGB = RGB(Red:=255, Green:=0, Blue:=0)
End Sub
| from PIL import Image
img = Image.new('RGB', (320, 240))
pixels = img.load()
pixels[100,100] = (255,0,0)
img.show()
|
Write the same algorithm in Python as shown in this VB implementation. | with createobject("ADODB.Stream")
.charset ="UTF-8"
.open
.loadfromfile("unixdict.txt")
s=.readtext
end with
a=split (s,vblf)
set d=createobject("scripting.dictionary")
redim b(ubound(a))
i=0
for each x in a
s=trim(x)
if len(s)>=9 then
if len(s)= 9 then d.add s,""
b(i)=s
i=i+1
end if
next
redim preserve b(i-1)
wscript.echo i
j=1
for i=0 to ubound(b)-9
s9=mid(b(i+0),1,1)& mid(b(i+1),2,1)& mid(b(i+2),3,1)& mid(b(i+3),4,1)& mid(b(i+4),5,1)&_
mid(b(i+5),6,1)& mid(b(i+6),7,1)& mid(b(i+7),8,1)& mid(b(i+8),9,1)
if d.exists(s9) then
wscript.echo j,s9
d.remove(s9)
j=j+1
end if
next
|
import urllib.request
from collections import Counter
urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt")
dictionary = open("unixdict.txt","r")
wordList = dictionary.read().split('\n')
dictionary.close()
filteredWords = [chosenWord for chosenWord in wordList if len(chosenWord)>=9]
for word in filteredWords[:-9]:
position = filteredWords.index(word)
newWord = "".join([filteredWords[position+i][i] for i in range(0,9)])
if newWord in filteredWords:
print(newWord)
|
Generate a Python translation of this VB snippet without changing its computational steps. | Private Function unicode_2_utf8(x As Long) As Byte()
Dim y() As Byte
Dim r As Long
Select Case x
Case 0 To &H7F
ReDim y(0)
y(0) = x
Case &H80 To &H7FF
ReDim y(1)
y(0) = 192 + x \ 64
y(1) = 128 + x Mod 64
Case &H800 To &H7FFF
ReDim y(2)
y(2) = 128 + x Mod 64
r = x \ 64
y(1) = 128 + r Mod 64
y(0) = 224 + r \ 64
Case 32768 To 65535
ReDim y(2)
y(2) = 128 + x Mod 64
r = x \ 64
y(1) = 128 + r Mod 64
y(0) = 224 + r \ 64
Case &H10000 To &H10FFFF
ReDim y(3)
y(3) = 128 + x Mod 64
r = x \ 64
y(2) = 128 + r Mod 64
r = r \ 64
y(1) = 128 + r Mod 64
y(0) = 240 + r \ 64
Case Else
MsgBox "what else?" & x & " " & Hex(x)
End Select
unicode_2_utf8 = y
End Function
Private Function utf8_2_unicode(x() As Byte) As Long
Dim first As Long, second As Long, third As Long, fourth As Long
Dim total As Long
Select Case UBound(x) - LBound(x)
Case 0
If x(0) < 128 Then
total = x(0)
Else
MsgBox "highest bit set error"
End If
Case 1
If x(0) \ 32 = 6 Then
first = x(0) Mod 32
If x(1) \ 64 = 2 Then
second = x(1) Mod 64
Else
MsgBox "mask error"
End If
Else
MsgBox "leading byte error"
End If
total = 64 * first + second
Case 2
If x(0) \ 16 = 14 Then
first = x(0) Mod 16
If x(1) \ 64 = 2 Then
second = x(1) Mod 64
If x(2) \ 64 = 2 Then
third = x(2) Mod 64
Else
MsgBox "mask error last byte"
End If
Else
MsgBox "mask error middle byte"
End If
Else
MsgBox "leading byte error"
End If
total = 4096 * first + 64 * second + third
Case 3
If x(0) \ 8 = 30 Then
first = x(0) Mod 8
If x(1) \ 64 = 2 Then
second = x(1) Mod 64
If x(2) \ 64 = 2 Then
third = x(2) Mod 64
If x(3) \ 64 = 2 Then
fourth = x(3) Mod 64
Else
MsgBox "mask error last byte"
End If
Else
MsgBox "mask error third byte"
End If
Else
MsgBox "mask error second byte"
End If
Else
MsgBox "mask error leading byte"
End If
total = CLng(262144 * first + 4096 * second + 64 * third + fourth)
Case Else
MsgBox "more bytes than expected"
End Select
utf8_2_unicode = total
End Function
Public Sub program()
Dim cp As Variant
Dim r() As Byte, s As String
cp = [{65, 246, 1046, 8364, 119070}]
Debug.Print "ch unicode UTF-8 encoded decoded"
For Each cpi In cp
r = unicode_2_utf8(CLng(cpi))
On Error Resume Next
s = CStr(Hex(cpi))
Debug.Print ChrW(cpi); String$(10 - Len(s), " "); s,
If Err.Number = 5 Then Debug.Print "?"; String$(10 - Len(s), " "); s,
s = ""
For Each yz In r
s = s & CStr(Hex(yz)) & " "
Next yz
Debug.Print String$(13 - Len(s), " "); s;
s = CStr(Hex(utf8_2_unicode(r)))
Debug.Print String$(8 - Len(s), " "); s
Next cpi
End Sub
|
from unicodedata import name
def unicode_code(ch):
return 'U+{:04x}'.format(ord(ch))
def utf8hex(ch):
return " ".join([hex(c)[2:] for c in ch.encode('utf8')]).upper()
if __name__ == "__main__":
print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'UTF-8 encoding (hex)'))
chars = ['A', 'ö', 'Ж', '€', '𝄞']
for char in chars:
print('{:<11} {:<36} {:<15} {:<15}'.format(char, name(char), unicode_code(char), utf8hex(char)))
|
Convert the following code from VB to Python, ensuring the logic remains intact. |
n=8
pattern="1001011001101001"
size=n*n: w=len(size)
mult=n\4
wscript.echo "Magic square : " & n & " x " & n
i=0
For r=0 To n-1
l=""
For c=0 To n-1
bit=Mid(pattern, c\mult+(r\mult)*4+1, 1)
If bit="1" Then t=i+1 Else t=size-i
l=l & Right(Space(w) & t, w) & " "
i=i+1
Next
wscript.echo l
Next
wscript.echo "Magic constant=" & (n*n+1)*n/2
| def MagicSquareDoublyEven(order):
sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]
n1 = order/4
for r in range(n1):
r1 = sq[r][n1:-n1]
r2 = sq[order -r - 1][n1:-n1]
r1.reverse()
r2.reverse()
sq[r][n1:-n1] = r2
sq[order -r - 1][n1:-n1] = r1
for r in range(n1, order-n1):
r1 = sq[r][:n1]
r2 = sq[order -r - 1][order-n1:]
r1.reverse()
r2.reverse()
sq[r][:n1] = r2
sq[order -r - 1][order-n1:] = r1
return sq
def printsq(s):
n = len(s)
bl = len(str(n**2))+1
for i in range(n):
print ''.join( [ ("%"+str(bl)+"s")%(str(x)) for x in s[i]] )
print "\nMagic constant = %d"%sum(s[0])
printsq(MagicSquareDoublyEven(8))
|
Rewrite this program in Python while keeping its functionality equivalent to the VB version. | 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
| 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!'
|
Port the provided VB code into Python while preserving the original functionality. | Set objShell = CreateObject("WScript.Shell")
objShell.Run "%comspec% /K dir",3,True
| import os
exit_code = os.system('ls')
output = os.popen('ls').read()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.