Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Preserve the algorithm and functionality while converting the code from VB to Python.
Option explicit Function fileexists(fn) fileexists= CreateObject("Scripting.FileSystemObject").FileExists(fn) End Function Function xmlvalid(strfilename) Dim xmldoc,xmldoc2,objSchemas Set xmlDoc = CreateObject("Msxml2.DOMDocument.6.0") If fileexists(Replace(strfilename,".xml",".dtd")) Then xmlDoc.setProperty "ProhibitDTD", False xmlDoc.setProperty "ResolveExternals", True xmlDoc.validateOnParse = True xmlDoc.async = False xmlDoc.load(strFileName) ElseIf fileexists(Replace(strfilename,".xml",".xsd")) Then xmlDoc.setProperty "ProhibitDTD", True xmlDoc.setProperty "ResolveExternals", True xmlDoc.validateOnParse = True xmlDoc.async = False xmlDoc.load(strFileName) Set xmlDoc2 = CreateObject("Msxml2.DOMDocument.6.0") xmlDoc2.validateOnParse = True xmlDoc2.async = False xmlDoc2.load(Replace (strfilename,".xml",".xsd")) Set objSchemas = CreateObject("MSXML2.XMLSchemaCache.6.0") objSchemas.Add "", xmlDoc2 Else Set xmlvalid= Nothing:Exit Function End If Set xmlvalid=xmldoc.parseError End Function Sub displayerror (parserr) Dim strresult If parserr is Nothing Then strresult= "could not find dtd or xsd for " & strFileName Else With parserr Select Case .errorcode Case 0 strResult = "Valid: " & strFileName & vbCr Case Else strResult = vbCrLf & "ERROR! Failed to validate " & _ strFileName & vbCrLf &.reason & vbCr & _ "Error code: " & .errorCode & ", Line: " & _ .line & ", Character: " & _ .linepos & ", Source: """ & _ .srcText & """ - " & vbCrLf End Select End With End If WScript.Echo strresult End Sub Dim strfilename strfilename="shiporder.xml" displayerror xmlvalid (strfilename)
from __future__ import print_function import lxml from lxml import etree if __name__=="__main__": parser = etree.XMLParser(dtd_validation=True) schema_root = etree.XML() schema = etree.XMLSchema(schema_root) parser = etree.XMLParser(schema = schema) try: root = etree.fromstring("<a>5</a>", parser) print ("Finished validating good xml") except lxml.etree.XMLSyntaxError as err: print (err) parser = etree.XMLParser(schema = schema) try: root = etree.fromstring("<a>5<b>foobar</b></a>", parser) except lxml.etree.XMLSyntaxError as err: print (err)
Produce a language-to-language conversion: from VB to Python, same semantics.
Function LIS(arr) n = UBound(arr) Dim p() ReDim p(n) Dim m() ReDim m(n) l = 0 For i = 0 To n lo = 1 hi = l Do While lo <= hi middle = Int((lo+hi)/2) If arr(m(middle)) < arr(i) Then lo = middle + 1 Else hi = middle - 1 End If Loop newl = lo p(i) = m(newl-1) m(newl) = i If newL > l Then l = newl End If Next Dim s() ReDim s(l) k = m(l) For i = l-1 To 0 Step - 1 s(i) = arr(k) k = p(k) Next LIS = Join(s,",") End Function WScript.StdOut.WriteLine LIS(Array(3,2,6,4,5,1)) WScript.StdOut.WriteLine LIS(Array(0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15))
def longest_increasing_subsequence(X): N = len(X) P = [0] * N M = [0] * (N+1) L = 0 for i in range(N): lo = 1 hi = L while lo <= hi: mid = (lo+hi)//2 if (X[M[mid]] < X[i]): lo = mid+1 else: hi = mid-1 newL = lo P[i] = M[newL-1] M[newL] = i if (newL > L): L = newL S = [] k = M[L] for i in range(L-1, -1, -1): S.append(X[k]) k = P[k] return S[::-1] if __name__ == '__main__': for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]: print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))
Translate this program into Python but keep the logic exactly as in VB.
option explicit const x_=0 const y_=1 const z_=2 const r_=3 function clamp(x,b,t) if x<b then clamp=b elseif x>t then clamp =t else clamp=x end if end function function dot(v,w) dot=v(x_)*w(x_)+v(y_)*w(y_)+v(z_)*w(z_): end function function normal (byval v) dim ilen:ilen=1/sqr(dot(v,v)): v(x_)=v(x_)*ilen: v(y_)=v(y_)*ilen: v(z_)=v(z_)*ilen: normal=v: end function function hittest(s,x,y) dim z z = s(r_)^2 - (x-s(x_))^2 - (y-s(y_))^2 if z>=0 then z=sqr(z) hittest=array(s(z_)-z,s(z_)+z) else hittest=0 end if end function sub deathstar(pos, neg, sun, k, amb) dim x,y,shades,result,shade,hp,hn,xx,b shades=array(" ",".",":","!","*","o","e","&","#","%","@") for y = pos(y_)-pos(r_)-0.5 to pos(y_)+pos(r_)+0.5 for x = pos(x_)-pos(r_)-0.5 to pos(x_)+pos(r_)+.5 hp=hittest (pos, x, y) hn=hittest(neg,x,y) if not isarray(hp) then result=0 elseif not isarray(hn) then result=1 elseif hn(0)>hp(0) then result=1 elseif hn(1)>hp(1) then result=0 elseif hn(1)>hp(0) then result=2 else result=1 end if shade=-1 select case result case 0 shade=0 case 1 xx=normal(array(x-pos(x_),y-pos(y_),hp(0)-pos(z_))) case 2 xx=normal(array(neg(x_)-x,neg(y_)-y,neg(z_)-hn(1))) end select if shade <>0 then b=dot(sun,xx)^k+amb shade=clamp((1-b) *ubound(shades),1,ubound(shades)) end if wscript.stdout.write string(2,shades(shade)) next wscript.stdout.write vbcrlf next end sub deathstar array(20, 20, 0, 20),array(10,10,-15,10), normal(array(-2,1,3)), 2, 0.1
import sys, math, collections Sphere = collections.namedtuple("Sphere", "cx cy cz r") V3 = collections.namedtuple("V3", "x y z") def normalize((x, y, z)): len = math.sqrt(x**2 + y**2 + z**2) return V3(x / len, y / len, z / len) def dot(v1, v2): d = v1.x*v2.x + v1.y*v2.y + v1.z*v2.z return -d if d < 0 else 0.0 def hit_sphere(sph, x0, y0): x = x0 - sph.cx y = y0 - sph.cy zsq = sph.r ** 2 - (x ** 2 + y ** 2) if zsq < 0: return (False, 0, 0) szsq = math.sqrt(zsq) return (True, sph.cz - szsq, sph.cz + szsq) def draw_sphere(k, ambient, light): shades = ".:!*oe& pos = Sphere(20.0, 20.0, 0.0, 20.0) neg = Sphere(1.0, 1.0, -6.0, 20.0) for i in xrange(int(math.floor(pos.cy - pos.r)), int(math.ceil(pos.cy + pos.r) + 1)): y = i + 0.5 for j in xrange(int(math.floor(pos.cx - 2 * pos.r)), int(math.ceil(pos.cx + 2 * pos.r) + 1)): x = (j - pos.cx) / 2.0 + 0.5 + pos.cx (h, zb1, zb2) = hit_sphere(pos, x, y) if not h: hit_result = 0 else: (h, zs1, zs2) = hit_sphere(neg, x, y) if not h: hit_result = 1 elif zs1 > zb1: hit_result = 1 elif zs2 > zb2: hit_result = 0 elif zs2 > zb1: hit_result = 2 else: hit_result = 1 if hit_result == 0: sys.stdout.write(' ') continue elif hit_result == 1: vec = V3(x - pos.cx, y - pos.cy, zb1 - pos.cz) elif hit_result == 2: vec = V3(neg.cx-x, neg.cy-y, neg.cz-zs2) vec = normalize(vec) b = dot(light, vec) ** k + ambient intensity = int((1 - b) * len(shades)) intensity = min(len(shades), max(0, intensity)) sys.stdout.write(shades[intensity]) print light = normalize(V3(-50, 30, 50)) draw_sphere(2, 0.5, light)
Produce a functionally identical Python code for the snippet given in VB.
Public c As Variant Public pi As Double Dim arclists() As Variant Public Enum circles_ xc = 0 yc rc End Enum Public Enum arclists_ rho x_ y_ i_ End Enum Public Enum shoelace_axis u = 0 v End Enum Private Sub give_a_list_of_circles() c = Array(Array(1.6417233788, 1.6121789534, 0.0848270516), _ Array(-1.4944608174, 1.2077959613, 1.1039549836), _ Array(0.6110294452, -0.6907087527, 0.9089162485), _ Array(0.3844862411, 0.2923344616, 0.2375743054), _ Array(-0.249589295, -0.3832854473, 1.0845181219), _ Array(1.7813504266, 1.6178237031, 0.8162655711), _ Array(-0.1985249206, -0.8343333301, 0.0538864941), _ Array(-1.7011985145, -0.1263820964, 0.4776976918), _ Array(-0.4319462812, 1.4104420482, 0.7886291537), _ Array(0.2178372997, -0.9499557344, 0.0357871187), _ Array(-0.6294854565, -1.3078893852, 0.7653357688), _ Array(1.7952608455, 0.6281269104, 0.2727652452), _ Array(1.4168575317, 1.0683357171, 1.1016025378), _ Array(1.4637371396, 0.9463877418, 1.1846214562), _ Array(-0.5263668798, 1.7315156631, 1.4428514068), _ Array(-1.2197352481, 0.9144146579, 1.0727263474), _ Array(-0.1389358881, 0.109280578, 0.7350208828), _ Array(1.5293954595, 0.0030278255, 1.2472867347), _ Array(-0.5258728625, 1.3782633069, 1.3495508831), _ Array(-0.1403562064, 0.2437382535, 1.3804956588), _ Array(0.8055826339, -0.0482092025, 0.3327165165), _ Array(-0.6311979224, 0.7184578971, 0.2491045282), _ Array(1.4685857879, -0.8347049536, 1.3670667538), _ Array(-0.6855727502, 1.6465021616, 1.0593087096), _ Array(0.0152957411, 0.0638919221, 0.9771215985)) pi = WorksheetFunction.pi() End Sub Private Function shoelace(s As Collection) As Double Dim t As Double If s.Count > 2 Then s.Add s(1) For i = 1 To s.Count - 1 t = t + s(i + 1)(u) * s(i)(v) - s(i)(u) * s(i + 1)(v) Next i End If shoelace = t / 2 End Function Private Sub arc_sub(acol As Collection, f0 As Double, u0 As Double, v0 As Double, _ f1 As Double, u1 As Double, v1 As Double, this As Integer, j As Integer) If acol.Count = 0 Then Exit Sub Debug.Assert acol.Count Mod 2 = 0 Debug.Assert f0 <> f1 If f1 = pi Or f1 + pi < 5E-16 Then f1 = -f1 If f0 = pi Or f0 + pi < 5E-16 Then f0 = -f0 If f0 < f1 Then If f1 < acol(1)(rho) Or f0 > acol(acol.Count)(rho) Then Exit Sub i = acol.Count + 1 start = 1 Do i = i - 1 Loop Until f1 > acol(i)(rho) If i Mod 2 = start Then acol.Add Array(f1, u1, v1, j), after:=i End If i = 0 Do i = i + 1 Loop Until f0 < acol(i)(rho) If i Mod 2 = 1 - start Then acol.Add Array(f0, u0, v0, j), before:=i i = i + 1 End If Do While acol(i)(rho) < f1 acol.Remove i If i > acol.Count Then Exit Do Loop Else start = 1 If f0 > acol(1)(rho) Then i = acol.Count + 1 Do i = i - 1 Loop While f0 < acol(i)(0) If f0 = pi Then acol.Add Array(f0, u0, v0, j), before:=i Else If i Mod 2 = start Then acol.Add Array(f0, u0, v0, j), after:=i End If End If End If If f1 <= acol(acol.Count)(rho) Then i = 0 Do i = i + 1 Loop While f1 > acol(i)(rho) If f1 + pi < 5E-16 Then acol.Add Array(f1, u1, v1, j), after:=i Else If i Mod 2 = 1 - start Then acol.Add Array(f1, u1, v1, j), before:=i End If End If End If Do While acol(acol.Count)(rho) > f0 Or acol(acol.Count)(i_) = -1 acol.Remove acol.Count If acol.Count = 0 Then Exit Do Loop If acol.Count > 0 Then Do While acol(1)(rho) < f1 Or (f1 = -pi And acol(1)(i_) = this) acol.Remove 1 If acol.Count = 0 Then Exit Do Loop End If End If End Sub Private Sub circle_cross() ReDim arclists(LBound(c) To UBound(c)) Dim alpha As Double, beta As Double Dim x3 As Double, x4 As Double, y3 As Double, y4 As Double Dim i As Integer, j As Integer For i = LBound(c) To UBound(c) Dim arccol As New Collection arccol.Add Array(-pi, c(i)(xc) - c(i)(r), c(i)(yc), i) arccol.Add Array(pi, c(i)(xc) - c(i)(r), c(i)(yc), -1) For j = LBound(c) To UBound(c) If i <> j Then x0 = c(i)(xc) y0 = c(i)(yc) r0 = c(i)(rc) x1 = c(j)(xc) y1 = c(j)(yc) r1 = c(j)(rc) d = Sqr((x0 - x1) ^ 2 + (y0 - y1) ^ 2) If d >= r0 + r1 Or d <= Abs(r0 - r1) Then Else a = (r0 ^ 2 - r1 ^ 2 + d ^ 2) / (2 * d) h = Sqr(r0 ^ 2 - a ^ 2) x2 = x0 + a * (x1 - x0) / d y2 = y0 + a * (y1 - y0) / d x3 = x2 + h * (y1 - y0) / d y3 = y2 - h * (x1 - x0) / d alpha = WorksheetFunction.Atan2(x3 - x0, y3 - y0) x4 = x2 - h * (y1 - y0) / d y4 = y2 + h * (x1 - x0) / d beta = WorksheetFunction.Atan2(x4 - x0, y4 - y0) arc_sub arccol, alpha, x3, y3, beta, x4, y4, i, j End If End If Next j Set arclists(i) = arccol Set arccol = Nothing Next i End Sub Private Sub make_path() Dim pathcol As New Collection, arcsum As Double i0 = UBound(arclists) finished = False Do While True arcsum = 0 Do While arclists(i0).Count = 0 i0 = i0 - 1 Loop j0 = arclists(i0).Count next_i = i0 next_j = j0 Do While True x = arclists(next_i)(next_j)(x_) y = arclists(next_i)(next_j)(y_) pathcol.Add Array(x, y) prev_i = next_i prev_j = next_j If arclists(next_i)(next_j - 1)(i_) = next_i Then next_j = arclists(next_i).Count - 1 If next_j = 1 Then Exit Do Else next_j = next_j - 1 End If r = c(next_i)(rc) a1 = arclists(next_i)(prev_j)(rho) a2 = arclists(next_i)(next_j)(rho) If a1 > a2 Then alpha = a1 - a2 Else alpha = 2 * pi - a2 + a1 End If arcsum = arcsum + r * r * (alpha - Sin(alpha)) / 2 next_i = arclists(next_i)(next_j)(i_) next_j = arclists(next_i).Count If next_j = 0 Then Exit Do Do While arclists(next_i)(next_j)(i_) <> prev_i next_j = next_j - 1 Loop If next_i = i0 And next_j = j0 Then finished = True Exit Do End If Loop If finished Then Exit Do i0 = i0 - 1 Set pathcol = Nothing Loop Debug.Print shoelace(pathcol) + arcsum End Sub Public Sub total_circles() give_a_list_of_circles circle_cross make_path End Sub
from collections import namedtuple Circle = namedtuple("Circle", "x y r") circles = [ Circle( 1.6417233788, 1.6121789534, 0.0848270516), Circle(-1.4944608174, 1.2077959613, 1.1039549836), Circle( 0.6110294452, -0.6907087527, 0.9089162485), Circle( 0.3844862411, 0.2923344616, 0.2375743054), Circle(-0.2495892950, -0.3832854473, 1.0845181219), Circle( 1.7813504266, 1.6178237031, 0.8162655711), Circle(-0.1985249206, -0.8343333301, 0.0538864941), Circle(-1.7011985145, -0.1263820964, 0.4776976918), Circle(-0.4319462812, 1.4104420482, 0.7886291537), Circle( 0.2178372997, -0.9499557344, 0.0357871187), Circle(-0.6294854565, -1.3078893852, 0.7653357688), Circle( 1.7952608455, 0.6281269104, 0.2727652452), Circle( 1.4168575317, 1.0683357171, 1.1016025378), Circle( 1.4637371396, 0.9463877418, 1.1846214562), Circle(-0.5263668798, 1.7315156631, 1.4428514068), Circle(-1.2197352481, 0.9144146579, 1.0727263474), Circle(-0.1389358881, 0.1092805780, 0.7350208828), Circle( 1.5293954595, 0.0030278255, 1.2472867347), Circle(-0.5258728625, 1.3782633069, 1.3495508831), Circle(-0.1403562064, 0.2437382535, 1.3804956588), Circle( 0.8055826339, -0.0482092025, 0.3327165165), Circle(-0.6311979224, 0.7184578971, 0.2491045282), Circle( 1.4685857879, -0.8347049536, 1.3670667538), Circle(-0.6855727502, 1.6465021616, 1.0593087096), Circle( 0.0152957411, 0.0638919221, 0.9771215985)] def main(): x_min = min(c.x - c.r for c in circles) x_max = max(c.x + c.r for c in circles) y_min = min(c.y - c.r for c in circles) y_max = max(c.y + c.r for c in circles) box_side = 500 dx = (x_max - x_min) / box_side dy = (y_max - y_min) / box_side count = 0 for r in xrange(box_side): y = y_min + r * dy for c in xrange(box_side): x = x_min + c * dx if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2) for circle in circles): count += 1 print "Approximated area:", count * dx * dy main()
Translate the given VB code snippet into Python without altering its behavior.
Public c As Variant Public pi As Double Dim arclists() As Variant Public Enum circles_ xc = 0 yc rc End Enum Public Enum arclists_ rho x_ y_ i_ End Enum Public Enum shoelace_axis u = 0 v End Enum Private Sub give_a_list_of_circles() c = Array(Array(1.6417233788, 1.6121789534, 0.0848270516), _ Array(-1.4944608174, 1.2077959613, 1.1039549836), _ Array(0.6110294452, -0.6907087527, 0.9089162485), _ Array(0.3844862411, 0.2923344616, 0.2375743054), _ Array(-0.249589295, -0.3832854473, 1.0845181219), _ Array(1.7813504266, 1.6178237031, 0.8162655711), _ Array(-0.1985249206, -0.8343333301, 0.0538864941), _ Array(-1.7011985145, -0.1263820964, 0.4776976918), _ Array(-0.4319462812, 1.4104420482, 0.7886291537), _ Array(0.2178372997, -0.9499557344, 0.0357871187), _ Array(-0.6294854565, -1.3078893852, 0.7653357688), _ Array(1.7952608455, 0.6281269104, 0.2727652452), _ Array(1.4168575317, 1.0683357171, 1.1016025378), _ Array(1.4637371396, 0.9463877418, 1.1846214562), _ Array(-0.5263668798, 1.7315156631, 1.4428514068), _ Array(-1.2197352481, 0.9144146579, 1.0727263474), _ Array(-0.1389358881, 0.109280578, 0.7350208828), _ Array(1.5293954595, 0.0030278255, 1.2472867347), _ Array(-0.5258728625, 1.3782633069, 1.3495508831), _ Array(-0.1403562064, 0.2437382535, 1.3804956588), _ Array(0.8055826339, -0.0482092025, 0.3327165165), _ Array(-0.6311979224, 0.7184578971, 0.2491045282), _ Array(1.4685857879, -0.8347049536, 1.3670667538), _ Array(-0.6855727502, 1.6465021616, 1.0593087096), _ Array(0.0152957411, 0.0638919221, 0.9771215985)) pi = WorksheetFunction.pi() End Sub Private Function shoelace(s As Collection) As Double Dim t As Double If s.Count > 2 Then s.Add s(1) For i = 1 To s.Count - 1 t = t + s(i + 1)(u) * s(i)(v) - s(i)(u) * s(i + 1)(v) Next i End If shoelace = t / 2 End Function Private Sub arc_sub(acol As Collection, f0 As Double, u0 As Double, v0 As Double, _ f1 As Double, u1 As Double, v1 As Double, this As Integer, j As Integer) If acol.Count = 0 Then Exit Sub Debug.Assert acol.Count Mod 2 = 0 Debug.Assert f0 <> f1 If f1 = pi Or f1 + pi < 5E-16 Then f1 = -f1 If f0 = pi Or f0 + pi < 5E-16 Then f0 = -f0 If f0 < f1 Then If f1 < acol(1)(rho) Or f0 > acol(acol.Count)(rho) Then Exit Sub i = acol.Count + 1 start = 1 Do i = i - 1 Loop Until f1 > acol(i)(rho) If i Mod 2 = start Then acol.Add Array(f1, u1, v1, j), after:=i End If i = 0 Do i = i + 1 Loop Until f0 < acol(i)(rho) If i Mod 2 = 1 - start Then acol.Add Array(f0, u0, v0, j), before:=i i = i + 1 End If Do While acol(i)(rho) < f1 acol.Remove i If i > acol.Count Then Exit Do Loop Else start = 1 If f0 > acol(1)(rho) Then i = acol.Count + 1 Do i = i - 1 Loop While f0 < acol(i)(0) If f0 = pi Then acol.Add Array(f0, u0, v0, j), before:=i Else If i Mod 2 = start Then acol.Add Array(f0, u0, v0, j), after:=i End If End If End If If f1 <= acol(acol.Count)(rho) Then i = 0 Do i = i + 1 Loop While f1 > acol(i)(rho) If f1 + pi < 5E-16 Then acol.Add Array(f1, u1, v1, j), after:=i Else If i Mod 2 = 1 - start Then acol.Add Array(f1, u1, v1, j), before:=i End If End If End If Do While acol(acol.Count)(rho) > f0 Or acol(acol.Count)(i_) = -1 acol.Remove acol.Count If acol.Count = 0 Then Exit Do Loop If acol.Count > 0 Then Do While acol(1)(rho) < f1 Or (f1 = -pi And acol(1)(i_) = this) acol.Remove 1 If acol.Count = 0 Then Exit Do Loop End If End If End Sub Private Sub circle_cross() ReDim arclists(LBound(c) To UBound(c)) Dim alpha As Double, beta As Double Dim x3 As Double, x4 As Double, y3 As Double, y4 As Double Dim i As Integer, j As Integer For i = LBound(c) To UBound(c) Dim arccol As New Collection arccol.Add Array(-pi, c(i)(xc) - c(i)(r), c(i)(yc), i) arccol.Add Array(pi, c(i)(xc) - c(i)(r), c(i)(yc), -1) For j = LBound(c) To UBound(c) If i <> j Then x0 = c(i)(xc) y0 = c(i)(yc) r0 = c(i)(rc) x1 = c(j)(xc) y1 = c(j)(yc) r1 = c(j)(rc) d = Sqr((x0 - x1) ^ 2 + (y0 - y1) ^ 2) If d >= r0 + r1 Or d <= Abs(r0 - r1) Then Else a = (r0 ^ 2 - r1 ^ 2 + d ^ 2) / (2 * d) h = Sqr(r0 ^ 2 - a ^ 2) x2 = x0 + a * (x1 - x0) / d y2 = y0 + a * (y1 - y0) / d x3 = x2 + h * (y1 - y0) / d y3 = y2 - h * (x1 - x0) / d alpha = WorksheetFunction.Atan2(x3 - x0, y3 - y0) x4 = x2 - h * (y1 - y0) / d y4 = y2 + h * (x1 - x0) / d beta = WorksheetFunction.Atan2(x4 - x0, y4 - y0) arc_sub arccol, alpha, x3, y3, beta, x4, y4, i, j End If End If Next j Set arclists(i) = arccol Set arccol = Nothing Next i End Sub Private Sub make_path() Dim pathcol As New Collection, arcsum As Double i0 = UBound(arclists) finished = False Do While True arcsum = 0 Do While arclists(i0).Count = 0 i0 = i0 - 1 Loop j0 = arclists(i0).Count next_i = i0 next_j = j0 Do While True x = arclists(next_i)(next_j)(x_) y = arclists(next_i)(next_j)(y_) pathcol.Add Array(x, y) prev_i = next_i prev_j = next_j If arclists(next_i)(next_j - 1)(i_) = next_i Then next_j = arclists(next_i).Count - 1 If next_j = 1 Then Exit Do Else next_j = next_j - 1 End If r = c(next_i)(rc) a1 = arclists(next_i)(prev_j)(rho) a2 = arclists(next_i)(next_j)(rho) If a1 > a2 Then alpha = a1 - a2 Else alpha = 2 * pi - a2 + a1 End If arcsum = arcsum + r * r * (alpha - Sin(alpha)) / 2 next_i = arclists(next_i)(next_j)(i_) next_j = arclists(next_i).Count If next_j = 0 Then Exit Do Do While arclists(next_i)(next_j)(i_) <> prev_i next_j = next_j - 1 Loop If next_i = i0 And next_j = j0 Then finished = True Exit Do End If Loop If finished Then Exit Do i0 = i0 - 1 Set pathcol = Nothing Loop Debug.Print shoelace(pathcol) + arcsum End Sub Public Sub total_circles() give_a_list_of_circles circle_cross make_path End Sub
from collections import namedtuple Circle = namedtuple("Circle", "x y r") circles = [ Circle( 1.6417233788, 1.6121789534, 0.0848270516), Circle(-1.4944608174, 1.2077959613, 1.1039549836), Circle( 0.6110294452, -0.6907087527, 0.9089162485), Circle( 0.3844862411, 0.2923344616, 0.2375743054), Circle(-0.2495892950, -0.3832854473, 1.0845181219), Circle( 1.7813504266, 1.6178237031, 0.8162655711), Circle(-0.1985249206, -0.8343333301, 0.0538864941), Circle(-1.7011985145, -0.1263820964, 0.4776976918), Circle(-0.4319462812, 1.4104420482, 0.7886291537), Circle( 0.2178372997, -0.9499557344, 0.0357871187), Circle(-0.6294854565, -1.3078893852, 0.7653357688), Circle( 1.7952608455, 0.6281269104, 0.2727652452), Circle( 1.4168575317, 1.0683357171, 1.1016025378), Circle( 1.4637371396, 0.9463877418, 1.1846214562), Circle(-0.5263668798, 1.7315156631, 1.4428514068), Circle(-1.2197352481, 0.9144146579, 1.0727263474), Circle(-0.1389358881, 0.1092805780, 0.7350208828), Circle( 1.5293954595, 0.0030278255, 1.2472867347), Circle(-0.5258728625, 1.3782633069, 1.3495508831), Circle(-0.1403562064, 0.2437382535, 1.3804956588), Circle( 0.8055826339, -0.0482092025, 0.3327165165), Circle(-0.6311979224, 0.7184578971, 0.2491045282), Circle( 1.4685857879, -0.8347049536, 1.3670667538), Circle(-0.6855727502, 1.6465021616, 1.0593087096), Circle( 0.0152957411, 0.0638919221, 0.9771215985)] def main(): x_min = min(c.x - c.r for c in circles) x_max = max(c.x + c.r for c in circles) y_min = min(c.y - c.r for c in circles) y_max = max(c.y + c.r for c in circles) box_side = 500 dx = (x_max - x_min) / box_side dy = (y_max - y_min) / box_side count = 0 for r in xrange(box_side): y = y_min + r * dy for c in xrange(box_side): x = x_min + c * dx if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2) for circle in circles): count += 1 print "Approximated area:", count * dx * dy main()
Produce a language-to-language conversion: from VB to Python, same semantics.
Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean Dim Total As Long, Ei As Long, i As Integer Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double Debug.Print "[1] ""Data set:"" "; For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies) Total = Total + ObservationFrequencies(i) Debug.Print ObservationFrequencies(i); " "; Next i DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies) Ei = Total / (DegreesOfFreedom + 1) For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies) ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei Next i p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True) Debug.Print Debug.Print " Chi-squared test for given frequencies" Debug.Print "X-squared ="; ChiSquared; ", "; Debug.Print "df ="; DegreesOfFreedom; ", "; Debug.Print "p-value = "; Format(p_value, "0.0000") Test4DiscreteUniformDistribution = p_value > Significance End Function Public Sub test() Dim O() As Variant O = [{199809,200665,199607,200270,199649}] Debug.Print "[1] ""Uniform? "; Test4DiscreteUniformDistribution(O, 0.05); """" O = [{522573,244456,139979,71531,21461}] Debug.Print "[1] ""Uniform? "; Test4DiscreteUniformDistribution(O, 0.05); """" End Sub
import math import random def GammaInc_Q( a, x): a1 = a-1 a2 = a-2 def f0( t ): return t**a1*math.exp(-t) def df0(t): return (a1-t)*t**a2*math.exp(-t) y = a1 while f0(y)*(x-y) >2.0e-8 and y < x: y += .3 if y > x: y = x h = 3.0e-4 n = int(y/h) h = y/n hh = 0.5*h gamax = h * sum( f0(t)+hh*df0(t) for t in ( h*j for j in xrange(n-1, -1, -1))) return gamax/gamma_spounge(a) c = None def gamma_spounge( z): global c a = 12 if c is None: k1_factrl = 1.0 c = [] c.append(math.sqrt(2.0*math.pi)) for k in range(1,a): c.append( math.exp(a-k) * (a-k)**(k-0.5) / k1_factrl ) k1_factrl *= -k accm = c[0] for k in range(1,a): accm += c[k] / (z+k) accm *= math.exp( -(z+a)) * (z+a)**(z+0.5) return accm/z; def chi2UniformDistance( dataSet ): expected = sum(dataSet)*1.0/len(dataSet) cntrd = (d-expected for d in dataSet) return sum(x*x for x in cntrd)/expected def chi2Probability(dof, distance): return 1.0 - GammaInc_Q( 0.5*dof, 0.5*distance) def chi2IsUniform(dataSet, significance): dof = len(dataSet)-1 dist = chi2UniformDistance(dataSet) return chi2Probability( dof, dist ) > significance dset1 = [ 199809, 200665, 199607, 200270, 199649 ] dset2 = [ 522573, 244456, 139979, 71531, 21461 ] for ds in (dset1, dset2): print "Data set:", ds dof = len(ds)-1 distance =chi2UniformDistance(ds) print "dof: %d distance: %.4f" % (dof, distance), prob = chi2Probability( dof, distance) print "probability: %.4f"%prob, print "uniform? ", "Yes"if chi2IsUniform(ds,0.05) else "No"
Produce a language-to-language conversion: from VB to Python, same semantics.
Module Module1 Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String) Dim out As New List(Of String) Dim comma = False While Not String.IsNullOrEmpty(s) Dim gs = GetItem(s, depth) Dim g = gs.Item1 s = gs.Item2 If String.IsNullOrEmpty(s) Then Exit While End If out.AddRange(g) If s(0) = "}" Then If comma Then Return Tuple.Create(out, s.Substring(1)) End If Return Tuple.Create(out.Select(Function(a) "{" + a + "}").ToList(), s.Substring(1)) End If If s(0) = "," Then comma = True s = s.Substring(1) End If End While Return Nothing End Function Function GetItem(s As String, Optional depth As Integer = 0) As Tuple(Of List(Of String), String) Dim out As New List(Of String) From {""} While Not String.IsNullOrEmpty(s) Dim c = s(0) If depth > 0 AndAlso (c = "," OrElse c = "}") Then Return Tuple.Create(out, s) End If If c = "{" Then Dim x = GetGroup(s.Substring(1), depth + 1) If Not IsNothing(x) Then Dim tout As New List(Of String) For Each a In out For Each b In x.Item1 tout.Add(a + b) Next Next out = tout s = x.Item2 Continue While End If End If If c = "\" AndAlso s.Length > 1 Then c += s(1) s = s.Substring(1) End If out = out.Select(Function(a) a + c).ToList() s = s.Substring(1) End While Return Tuple.Create(out, s) End Function Sub Main() For Each s In { "It{{em,alic}iz,erat}e{d,}, please.", "~/{Downloads,Pictures}/*.{jpg,gif,png}", "{,{,gotta have{ ,\, again\, }}more }cowbell!", "{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}" } Dim fmt = "{0}" + vbNewLine + vbTab + "{1}" Dim parts = GetItem(s) Dim res = String.Join(vbNewLine + vbTab, parts.Item1) Console.WriteLine(fmt, s, res) Next End Sub End Module
def getitem(s, depth=0): out = [""] while s: c = s[0] if depth and (c == ',' or c == '}'): return out,s if c == '{': x = getgroup(s[1:], depth+1) if x: out,s = [a+b for a in out for b in x[0]], x[1] continue if c == '\\' and len(s) > 1: s, c = s[1:], c + s[1] out, s = [a+c for a in out], s[1:] return out,s def getgroup(s, depth): out, comma = [], False while s: g,s = getitem(s, depth) if not s: break out += g if s[0] == '}': if comma: return out, s[1:] return ['{' + a + '}' for a in out], s[1:] if s[0] == ',': comma,s = True, s[1:] return None for s in .split('\n'): print "\n\t".join([s] + getitem(s)[0]) + "\n"
Write the same code in Python as shown below in VB.
Function no_arguments() As String no_arguments = "ok" End Function Function fixed_number(argument1 As Integer, argument2 As Integer) fixed_number = argument1 + argument2 End Function Function optional_parameter(Optional argument1 = 1) As Integer optional_parameter = argument1 End Function Function variable_number(arguments As Variant) As Integer variable_number = UBound(arguments) End Function Function named_arguments(argument1 As Integer, argument2 As Integer) As Integer named_arguments = argument1 + argument2 End Function Function statement() As String Debug.Print "function called as statement" statement = "ok" End Function Function return_value() As String return_value = "ok" End Function Sub foo() Debug.Print "subroutine", End Sub Function bar() As String bar = "function" End Function Function passed_by_value(ByVal s As String) As String s = "written over" passed_by_value = "passed by value" End Function Function passed_by_reference(ByRef s As String) As String s = "written over" passed_by_reference = "passed by reference" End Function Sub no_parentheses(myargument As String) Debug.Print myargument, End Sub Public Sub calling_a_function() Debug.Print "no arguments", , no_arguments Debug.Print "no arguments", , no_arguments() Debug.Print "fixed_number", , fixed_number(1, 1) Debug.Print "optional parameter", optional_parameter Debug.Print "optional parameter", optional_parameter(2) Debug.Print "variable number", variable_number([{"hello", "there"}]) Debug.Print "named arguments", named_arguments(argument2:=1, argument1:=1) statement s = "no_arguments" Debug.Print "first-class context", Application.Run(s) returnvalue = return_value Debug.Print "obtained return value", returnvalue foo Debug.Print , bar Dim t As String t = "unaltered" Debug.Print passed_by_value(t), t Debug.Print passed_by_reference(t), t no_parentheses "calling a subroutine" Debug.Print "does not require parentheses" Call no_parentheses("deprecated use") Debug.Print "of parentheses" End Sub
def no_args(): pass no_args() def fixed_args(x, y): print('x=%r, y=%r' % (x, y)) fixed_args(1, 2) fixed_args(y=2, x=1) myargs=(1,2) fixed_args(*myargs) def opt_args(x=1): print(x) opt_args() opt_args(3.141) def var_args(*v): print(v) var_args(1, 2, 3) var_args(1, (2,3)) var_args() fixed_args(y=2, x=1) if 1: no_args() assert no_args() is None def return_something(): return 1 x = return_something() def is_builtin(x): print(x.__name__ in dir(__builtins__)) is_builtin(pow) is_builtin(is_builtin) def takes_anything(*args, **kwargs): for each in args: print(each) for key, value in sorted(kwargs.items()): print("%s:%s" % (key, value)) wrapped_fn(*args, **kwargs)
Please provide an equivalent version of this VB code in Python.
Function no_arguments() As String no_arguments = "ok" End Function Function fixed_number(argument1 As Integer, argument2 As Integer) fixed_number = argument1 + argument2 End Function Function optional_parameter(Optional argument1 = 1) As Integer optional_parameter = argument1 End Function Function variable_number(arguments As Variant) As Integer variable_number = UBound(arguments) End Function Function named_arguments(argument1 As Integer, argument2 As Integer) As Integer named_arguments = argument1 + argument2 End Function Function statement() As String Debug.Print "function called as statement" statement = "ok" End Function Function return_value() As String return_value = "ok" End Function Sub foo() Debug.Print "subroutine", End Sub Function bar() As String bar = "function" End Function Function passed_by_value(ByVal s As String) As String s = "written over" passed_by_value = "passed by value" End Function Function passed_by_reference(ByRef s As String) As String s = "written over" passed_by_reference = "passed by reference" End Function Sub no_parentheses(myargument As String) Debug.Print myargument, End Sub Public Sub calling_a_function() Debug.Print "no arguments", , no_arguments Debug.Print "no arguments", , no_arguments() Debug.Print "fixed_number", , fixed_number(1, 1) Debug.Print "optional parameter", optional_parameter Debug.Print "optional parameter", optional_parameter(2) Debug.Print "variable number", variable_number([{"hello", "there"}]) Debug.Print "named arguments", named_arguments(argument2:=1, argument1:=1) statement s = "no_arguments" Debug.Print "first-class context", Application.Run(s) returnvalue = return_value Debug.Print "obtained return value", returnvalue foo Debug.Print , bar Dim t As String t = "unaltered" Debug.Print passed_by_value(t), t Debug.Print passed_by_reference(t), t no_parentheses "calling a subroutine" Debug.Print "does not require parentheses" Call no_parentheses("deprecated use") Debug.Print "of parentheses" End Sub
def no_args(): pass no_args() def fixed_args(x, y): print('x=%r, y=%r' % (x, y)) fixed_args(1, 2) fixed_args(y=2, x=1) myargs=(1,2) fixed_args(*myargs) def opt_args(x=1): print(x) opt_args() opt_args(3.141) def var_args(*v): print(v) var_args(1, 2, 3) var_args(1, (2,3)) var_args() fixed_args(y=2, x=1) if 1: no_args() assert no_args() is None def return_something(): return 1 x = return_something() def is_builtin(x): print(x.__name__ in dir(__builtins__)) is_builtin(pow) is_builtin(is_builtin) def takes_anything(*args, **kwargs): for each in args: print(each) for key, value in sorted(kwargs.items()): print("%s:%s" % (key, value)) wrapped_fn(*args, **kwargs)
Can you help me rewrite this code in Python instead of VB, keeping it the same logically?
VERSION 5.00 Begin VB.Form Form1 Caption = "Form1" ClientHeight = 2265 ClientLeft = 60 ClientTop = 600 ClientWidth = 2175 LinkTopic = "Form1" ScaleHeight = 2265 ScaleWidth = 2175 StartUpPosition = 3 Begin VB.CommandButton cmdRnd Caption = "Random" Height = 495 Left = 120 TabIndex = 2 Top = 1680 Width = 1215 End Begin VB.CommandButton cmdInc Caption = "Increment" Height = 495 Left = 120 TabIndex = 1 Top = 1080 Width = 1215 End Begin VB.TextBox txtValue Height = 495 Left = 120 TabIndex = 0 Text = "0" Top = 240 Width = 1215 End End Attribute VB_Name = "Form1" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Private Sub Form_Load() Randomize Timer End Sub Private Sub cmdRnd_Click() If MsgBox("Random?", vbYesNo) Then txtValue.Text = Int(Rnd * 11) End Sub Private Sub cmdInc_Click() If Val(txtValue.Text) < 10 Then txtValue.Text = Val(txtValue.Text) + 1 End Sub Private Sub txtValue_KeyPress(KeyAscii As Integer) Select Case KeyAscii Case 8, 43, 45, 48 To 57 Case Else KeyAscii = 0 End Select End Sub
import random, tkMessageBox from Tkinter import * window = Tk() window.geometry("300x50+100+100") options = { "padx":5, "pady":5} s=StringVar() s.set(1) def increase(): s.set(int(s.get())+1) def rand(): if tkMessageBox.askyesno("Confirmation", "Reset to random value ?"): s.set(random.randrange(0,5000)) def update(e): if not e.char.isdigit(): tkMessageBox.showerror('Error', 'Invalid input !') return "break" e = Entry(text=s) e.grid(column=0, row=0, **options) e.bind('<Key>', update) b1 = Button(text="Increase", command=increase, **options ) b1.grid(column=1, row=0, **options) b2 = Button(text="Random", command=rand, **options) b2.grid(column=2, row=0, **options) mainloop()
Convert the following code from VB to Python, ensuring the logic remains intact.
Dim chosen(10) For j = 1 To 1000000 c = one_of_n(10) chosen(c) = chosen(c) + 1 Next For k = 1 To 10 WScript.StdOut.WriteLine k & ". " & chosen(k) Next Function one_of_n(n) Randomize For i = 1 To n If Rnd(1) < 1/i Then one_of_n = i End If Next End Function
from random import randrange try: range = xrange except: pass def one_of_n(lines): choice = None for i, line in enumerate(lines): if randrange(i+1) == 0: choice = line return choice def one_of_n_test(n=10, trials=1000000): bins = [0] * n if n: for i in range(trials): bins[one_of_n(range(n))] += 1 return bins print(one_of_n_test())
Rewrite this program in Python while keeping its functionality equivalent to the VB version.
Private Function ordinal(s As String) As String Dim irregs As New Collection irregs.Add "first", "one" irregs.Add "second", "two" irregs.Add "third", "three" irregs.Add "fifth", "five" irregs.Add "eighth", "eight" irregs.Add "ninth", "nine" irregs.Add "twelfth", "twelve" Dim i As Integer For i = Len(s) To 1 Step -1 ch = Mid(s, i, 1) If ch = " " Or ch = "-" Then Exit For Next i On Error GoTo 1 ord = irregs(Right(s, Len(s) - i)) ordinal = Left(s, i) & ord Exit Function 1: If Right(s, 1) = "y" Then s = Left(s, Len(s) - 1) & "ieth" Else s = s & "th" End If ordinal = s End Function Public Sub ordinals() tests = [{1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003, 123, 00123.0, 1.23E2}] init For i = 1 To UBound(tests) Debug.Print ordinal(spell(tests(i))) Next i End Sub
irregularOrdinals = { "one": "first", "two": "second", "three": "third", "five": "fifth", "eight": "eighth", "nine": "ninth", "twelve": "twelfth", } def num2ordinal(n): conversion = int(float(n)) num = spell_integer(conversion) hyphen = num.rsplit("-", 1) num = num.rsplit(" ", 1) delim = " " if len(num[-1]) > len(hyphen[-1]): num = hyphen delim = "-" if num[-1] in irregularOrdinals: num[-1] = delim + irregularOrdinals[num[-1]] elif num[-1].endswith("y"): num[-1] = delim + num[-1][:-1] + "ieth" else: num[-1] = delim + num[-1] + "th" return "".join(num) if __name__ == "__main__": tests = "1 2 3 4 5 11 65 100 101 272 23456 8007006005004003 123 00123.0 1.23e2".split() for num in tests: print("{} => {}".format(num, num2ordinal(num))) TENS = [None, None, "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] SMALL = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] HUGE = [None, None] + [h + "illion" for h in ("m", "b", "tr", "quadr", "quint", "sext", "sept", "oct", "non", "dec")] def nonzero(c, n, connect=''): return "" if n == 0 else connect + c + spell_integer(n) def last_and(num): if ',' in num: pre, last = num.rsplit(',', 1) if ' and ' not in last: last = ' and' + last num = ''.join([pre, ',', last]) return num def big(e, n): if e == 0: return spell_integer(n) elif e == 1: return spell_integer(n) + " thousand" else: return spell_integer(n) + " " + HUGE[e] def base1000_rev(n): while n != 0: n, r = divmod(n, 1000) yield r def spell_integer(n): if n < 0: return "minus " + spell_integer(-n) elif n < 20: return SMALL[n] elif n < 100: a, b = divmod(n, 10) return TENS[a] + nonzero("-", b) elif n < 1000: a, b = divmod(n, 100) return SMALL[a] + " hundred" + nonzero(" ", b, ' and') else: num = ", ".join([big(e, x) for e, x in enumerate(base1000_rev(n)) if x][::-1]) return last_and(num)
Change the following VB code into Python without altering its purpose.
Function IsSelfDescribing(n) IsSelfDescribing = False Set digit = CreateObject("Scripting.Dictionary") For i = 1 To Len(n) k = Mid(n,i,1) If digit.Exists(k) Then digit.Item(k) = digit.Item(k) + 1 Else digit.Add k,1 End If Next c = 0 For j = 0 To Len(n)-1 l = Mid(n,j+1,1) If digit.Exists(CStr(j)) Then If digit.Item(CStr(j)) = CInt(l) Then c = c + 1 End If ElseIf l = 0 Then c = c + 1 Else Exit For End If Next If c = Len(n) Then IsSelfDescribing = True End If End Function start_time = Now s = "" For m = 1 To 100000000 If IsSelfDescribing(m) Then WScript.StdOut.WriteLine m End If Next end_time = Now WScript.StdOut.WriteLine "Elapse Time: " & DateDiff("s",start_time,end_time) & " seconds"
>>> def isSelfDescribing(n): s = str(n) return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s)) >>> [x for x in range(4000000) if isSelfDescribing(x)] [1210, 2020, 21200, 3211000] >>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)] [(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]
Write the same algorithm in Python as shown in this VB implementation.
Module Module1 Function Prepend(n As Integer, seq As List(Of Integer)) As List(Of Integer) Dim result As New List(Of Integer) From { n } result.AddRange(seq) Return result End Function Function CheckSeq(pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer) If pos > min_len OrElse seq(0) > n Then Return Tuple.Create(min_len, 0) End If If seq(0) = n Then Return Tuple.Create(pos, 1) End If If pos < min_len Then Return TryPerm(0, pos, seq, n, min_len) End If Return Tuple.Create(min_len, 0) End Function Function TryPerm(i As Integer, pos As Integer, seq As List(Of Integer), n As Integer, min_len As Integer) As Tuple(Of Integer, Integer) If i > pos Then Return Tuple.Create(min_len, 0) End If Dim res1 = CheckSeq(pos + 1, Prepend(seq(0) + seq(i), seq), n, min_len) Dim res2 = TryPerm(i + 1, pos, seq, n, res1.Item1) If res2.Item1 < res1.Item1 Then Return res2 End If If res2.Item1 = res1.Item1 Then Return Tuple.Create(res2.Item1, res1.Item2 + res2.Item2) End If Throw New Exception("TryPerm exception") End Function Function InitTryPerm(x As Integer) As Tuple(Of Integer, Integer) Return TryPerm(0, 0, New List(Of Integer) From {1}, x, 12) End Function Sub FindBrauer(num As Integer) Dim res = InitTryPerm(num) Console.WriteLine("N = {0}", num) Console.WriteLine("Minimum length of chains: L(n) = {0}", res.Item1) Console.WriteLine("Number of minimum length Brauer chains: {0}", res.Item2) Console.WriteLine() End Sub Sub Main() Dim nums() = {7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379} Array.ForEach(nums, Sub(n) FindBrauer(n)) End Sub End Module
def prepend(n, seq): return [n] + seq def check_seq(pos, seq, n, min_len): if pos > min_len or seq[0] > n: return min_len, 0 if seq[0] == n: return pos, 1 if pos < min_len: return try_perm(0, pos, seq, n, min_len) return min_len, 0 def try_perm(i, pos, seq, n, min_len): if i > pos: return min_len, 0 res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len) res2 = try_perm(i + 1, pos, seq, n, res1[0]) if res2[0] < res1[0]: return res2 if res2[0] == res1[0]: return res2[0], res1[1] + res2[1] raise Exception("try_perm exception") def init_try_perm(x): return try_perm(0, 0, [1], x, 12) def find_brauer(num): res = init_try_perm(num) print print "N = ", num print "Minimum length of chains: L(n) = ", res[0] print "Number of minimum length Brauer chains: ", res[1] nums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379] for i in nums: find_brauer(i)
Write a version of this VB function in Python with identical behavior.
Private Sub Repeat(rid As String, n As Integer) For i = 1 To n Application.Run rid Next i End Sub Private Sub Hello() Debug.Print "Hello" End Sub Public Sub main() Repeat "Hello", 5 End Sub
def repeat(f,n): for i in range(n): f(); def procedure(): print("Example"); repeat(procedure,3);
Please provide an equivalent version of this VB code in Python.
sub ensure_cscript() if instrrev(ucase(WScript.FullName),"WSCRIPT.EXE")then createobject("wscript.shell").run "CSCRIPT //nologo """ &_ WScript.ScriptFullName &"""" ,,0 wscript.quit end if end sub class bargraph private bar,mn,mx,nn,cnt Private sub class_initialize() bar=chrw(&h2581)&chrw(&h2582)&chrw(&h2583)&chrw(&h2584)&chrw(&h2585)&_ chrw(&h2586)&chrw(&h2587)&chrw(&h2588) nn=8 end sub public function bg (s) a=split(replace(replace(s,","," ")," "," ")," ") mn=999999:mx=-999999:cnt=ubound(a)+1 for i=0 to ubound(a) a(i)=cdbl(trim(a(i))) if a(i)>mx then mx=a(i) if a(i)<mn then mn=a(i) next ss="Data: " for i=0 to ubound(a) :ss=ss & right (" "& a(i),6) :next ss=ss+vbcrlf + "sparkline: " for i=0 to ubound(a) x=scale(a(i)) ss=ss & string(6,mid(bar,x,1)) next bg=ss &vbcrlf & "min: "&mn & " max: "& mx & _ " cnt: "& ubound(a)+1 &vbcrlf end function private function scale(x) if x=<mn then scale=1 elseif x>=mx then scale=nn else scale=int(nn* (x-mn)/(mx-mn)+1) end if end function end class ensure_cscript set b=new bargraph wscript.stdout.writeblanklines 2 wscript.echo b.bg("1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1") wscript.echo b.bg("1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5") wscript.echo b.bg("0, 1, 19, 20") wscript.echo b.bg("0, 999, 4000, 4999, 7000, 7999") set b=nothing wscript.echo "If bars don "font to DejaVu Sans Mono or any other that has the bargrph characters" & _ vbcrlf wscript.stdout.write "Press any key.." : wscript.stdin.read 1
bar = '▁▂▃▄▅▆▇█' barcount = len(bar) def sparkline(numbers): mn, mx = min(numbers), max(numbers) extent = mx - mn sparkline = ''.join(bar[min([barcount - 1, int((n - mn) / extent * barcount)])] for n in numbers) return mn, mx, sparkline if __name__ == '__main__': import re for line in ("0 0 1 1; 0 1 19 20; 0 999 4000 4999 7000 7999;" "1 2 3 4 5 6 7 8 7 6 5 4 3 2 1;" "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 ").split(';'): print("\nNumbers:", line) numbers = [float(n) for n in re.split(r'[\s,]+', line.strip())] mn, mx, sp = sparkline(numbers) print(' min: %5f; max: %5f' % (mn, mx)) print(" " + sp)
Preserve the algorithm and functionality while converting the code from VB to Python.
Private Function mul_inv(a As Long, n As Long) As Variant If n < 0 Then n = -n If a < 0 Then a = n - ((-a) Mod n) Dim t As Long: t = 0 Dim nt As Long: nt = 1 Dim r As Long: r = n Dim nr As Long: nr = a Dim q As Long Do While nr <> 0 q = r \ nr tmp = t t = nt nt = tmp - q * nt tmp = r r = nr nr = tmp - q * nr Loop If r > 1 Then mul_inv = "a is not invertible" Else If t < 0 Then t = t + n mul_inv = t End If End Function Public Sub mi() Debug.Print mul_inv(42, 2017) Debug.Print mul_inv(40, 1) Debug.Print mul_inv(52, -217) Debug.Print mul_inv(-486, 217) Debug.Print mul_inv(40, 2018) End Sub
>>> def extended_gcd(aa, bb): lastremainder, remainder = abs(aa), abs(bb) x, lastx, y, lasty = 0, 1, 1, 0 while remainder: lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder) x, lastx = lastx - quotient*x, x y, lasty = lasty - quotient*y, y return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1) >>> def modinv(a, m): g, x, y = extended_gcd(a, m) if g != 1: raise ValueError return x % m >>> modinv(42, 2017) 1969 >>>
Change the following VB code into Python without altering its purpose.
Class HTTPSock Inherits TCPSocket Event Sub DataAvailable() Dim headers As New InternetHeaders headers.AppendHeader("Content-Length", Str(LenB("Goodbye, World!"))) headers.AppendHeader("Content-Type", "text/plain") headers.AppendHeader("Content-Encoding", "identity") headers.AppendHeader("Connection", "close") Dim data As String = "HTTP/1.1 200 OK" + EndOfLine.Windows + headers.Source + EndOfLine.Windows + EndOfLine.Windows + "Goodbye, World!" Me.Write(data) Me.Close End Sub End Class Class HTTPServ Inherits ServerSocket Event Sub AddSocket() As TCPSocket Return New HTTPSock End Sub End Class Class App Inherits Application Event Sub Run(Args() As String) Dim sock As New HTTPServ sock.Port = 8080 sock.Listen() While True App.DoEvents Wend End Sub End Class
from wsgiref.simple_server import make_server def app(environ, start_response): start_response('200 OK', [('Content-Type','text/html')]) yield b"<h1>Goodbye, World!</h1>" server = make_server('127.0.0.1', 8080, app) server.serve_forever()
Convert the following code from VB to Python, ensuring the logic remains intact.
Option Strict On Option Explicit On Imports System.IO Module OwnDigitsPowerSum Public Sub Main Dim used(9) As Integer Dim check(9) As Integer Dim power(9, 9) As Long For i As Integer = 0 To 9 check(i) = 0 Next i For i As Integer = 1 To 9 power(1, i) = i Next i For j As Integer = 2 To 9 For i As Integer = 1 To 9 power(j, i) = power(j - 1, i) * i Next i Next j Dim lowestDigit(9) As Integer lowestDigit(1) = -1 lowestDigit(2) = -1 Dim p10 As Long = 100 For i As Integer = 3 To 9 For p As Integer = 2 To 9 Dim np As Long = power(i, p) * i If Not ( np < p10) Then Exit For lowestDigit(i) = p Next p p10 *= 10 Next i Dim maxZeros(9, 9) As Integer For i As Integer = 1 To 9 For j As Integer = 1 To 9 maxZeros(i, j) = 0 Next j Next i p10 = 1000 For w As Integer = 3 To 9 For d As Integer = lowestDigit(w) To 9 Dim nz As Integer = 9 Do If nz < 0 Then Exit Do Else Dim np As Long = power(w, d) * nz IF Not ( np > p10) Then Exit Do End If nz -= 1 Loop maxZeros(w, d) = If(nz > w, 0, w - nz) Next d p10 *= 10 Next w Dim numbers(100) As Long Dim nCount As Integer = 0 Dim tryCount As Integer = 0 Dim digits(9) As Integer For d As Integer = 1 To 9 digits(d) = 9 Next d For d As Integer = 0 To 8 used(d) = 0 Next d used(9) = 9 Dim width As Integer = 9 Dim last As Integer = width p10 = 100000000 Do While width > 2 tryCount += 1 Dim dps As Long = 0 check(0) = used(0) For i As Integer = 1 To 9 check(i) = used(i) If used(i) <> 0 Then dps += used(i) * power(width, i) End If Next i Dim n As Long = dps Do check(CInt(n Mod 10)) -= 1 n \= 10 Loop Until n <= 0 Dim reduceWidth As Boolean = dps <= p10 If Not reduceWidth Then Dim zCount As Integer = 0 For i As Integer = 0 To 9 If check(i) <> 0 Then Exit For zCount+= 1 Next i If zCount = 10 Then nCount += 1 numbers(nCount) = dps End If used(digits(last)) -= 1 digits(last) -= 1 If digits(last) = 0 Then If used(0) >= maxZeros(width, digits(1)) Then digits(last) = -1 End If End If If digits(last) >= 0 Then used(digits(last)) += 1 Else Dim prev As Integer = last Do prev -= 1 If prev < 1 Then Exit Do Else used(digits(prev)) -= 1 digits(prev) -= 1 IF digits(prev) >= 0 Then Exit Do End If Loop If prev > 0 Then If prev = 1 Then If digits(1) <= lowestDigit(width) Then prev = 0 End If End If If prev <> 0 Then used(digits(prev)) += 1 For i As Integer = prev + 1 To width digits(i) = digits(prev) used(digits(prev)) += 1 Next i End If End If If prev <= 0 Then reduceWidth = True End If End If End If If reduceWidth Then last -= 1 width = last If last > 0 Then For d As Integer = 1 To last digits(d) = 9 Next d For d As Integer = last + 1 To 9 digits(d) = -1 Next d For d As Integer = 0 To 8 used(d) = 0 Next d used(9) = last p10 \= 10 End If End If Loop Console.Out.WriteLine("Own digits power sums for N = 3 to 9 inclusive:") For i As Integer = nCount To 1 Step -1 Console.Out.WriteLine(numbers(i)) Next i Console.Out.WriteLine("Considered " & tryCount & " digit combinations") End Sub End Module
def isowndigitspowersum(integer): digits = [int(c) for c in str(integer)] exponent = len(digits) return sum(x ** exponent for x in digits) == integer print("Own digits power sums for N = 3 to 9 inclusive:") for i in range(100, 1000000000): if isowndigitspowersum(i): print(i)
Write a version of this VB function in Python with identical behavior.
Option Strict On Option Explicit On Imports System.IO Module KlarnerRado Private Const bitsWidth As Integer = 31 Private bitMask() As Integer = _ New Integer(){ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 _ , 2048, 4096, 8192, 16384, 32768, 65536, 131072 _ , 262144, 524288, 1048576, 2097152, 4194304, 8388608 _ , 16777216, 33554432, 67108864, 134217728, 268435456 _ , 536870912, 1073741824 _ } Private Const maxElement As Integer = 1100000000 Private Function BitSet(bit As Integer, v As Integer) As Boolean Return (v And bitMask(bit - 1)) <> 0 End Function Private Function SetBit(ByVal bit As Integer, ByVal b As Integer) As Integer Return b Or bitMask(bit - 1) End Function Public Sub Main Dim kr(maxElement \ bitsWidth) As Integer For i As Integer = 0 To kr.Count() - 1 kr(i) = 0 Next i Dim krCount As Integer = 0 Dim n21 As Integer = 3 Dim n31 As Integer = 4 Dim p10 As Integer = 1000 Dim iBit As Integer = 0 Dim iOverBw As Integer = 0 Dim p2Bit As Integer = 1 Dim p2OverBw As Integer = 0 Dim p3Bit As Integer = 1 Dim p3OverBw As Integer = 0 kr(0) = SetBit(1, kr(0)) Dim kri As Boolean = True Dim lastI As Integer = 0 For i As Integer = 1 To maxElement iBit += 1 If iBit > bitsWidth Then iBit = 1 iOverBw += 1 End If If i = n21 Then If BitSet(p2Bit, kr(p2OverBw)) Then kri = True End If p2Bit += 1 If p2Bit > bitsWidth Then p2Bit = 1 p2OverBw += 1 End If n21 += 2 End If If i = n31 Then If BitSet(p3Bit, kr(p3OverBw)) Then kri = True End If p3Bit += 1 If p3Bit > bitsWidth Then p3Bit = 1 p3OverBw += 1 End If n31 += 3 End If If kri Then lastI = i kr(iOverBw) = SetBit(iBit, kr(iOverBw)) krCount += 1 If krCount <= 100 Then Console.Out.Write(" " & i.ToString().PadLeft(3)) If krCount Mod 20 = 0 Then Console.Out.WriteLine() End If ElseIf krCount = p10 Then Console.Out.WriteLine("Element " & p10.ToString().PadLeft(10) & " is " & i.ToString().PadLeft(10)) p10 *= 10 End If kri = False End If Next i Console.Out.WriteLine("Element " & krCount.ToString().PadLeft(10) & " is " & lastI.ToString().PadLeft(10)) End Sub End Module
def KlarnerRado(N): K = [1] for i in range(N): j = K[i] firstadd, secondadd = 2 * j + 1, 3 * j + 1 if firstadd < K[-1]: for pos in range(len(K)-1, 1, -1): if K[pos] < firstadd < K[pos + 1]: K.insert(pos + 1, firstadd) break elif firstadd > K[-1]: K.append(firstadd) if secondadd < K[-1]: for pos in range(len(K)-1, 1, -1): if K[pos] < secondadd < K[pos + 1]: K.insert(pos + 1, secondadd) break elif secondadd > K[-1]: K.append(secondadd) return K kr1m = KlarnerRado(100_000) print('First 100 Klarner-Rado sequence numbers:') for idx, v in enumerate(kr1m[:100]): print(f'{v: 4}', end='\n' if (idx + 1) % 20 == 0 else '') for n in [1000, 10_000, 100_000]: print(f'The {n :,}th Klarner-Rado number is {kr1m[n-1] :,}')
Generate a Python translation of this VB snippet without changing its computational steps.
Option Strict On Option Explicit On Imports System.IO Module KlarnerRado Private Const bitsWidth As Integer = 31 Private bitMask() As Integer = _ New Integer(){ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 _ , 2048, 4096, 8192, 16384, 32768, 65536, 131072 _ , 262144, 524288, 1048576, 2097152, 4194304, 8388608 _ , 16777216, 33554432, 67108864, 134217728, 268435456 _ , 536870912, 1073741824 _ } Private Const maxElement As Integer = 1100000000 Private Function BitSet(bit As Integer, v As Integer) As Boolean Return (v And bitMask(bit - 1)) <> 0 End Function Private Function SetBit(ByVal bit As Integer, ByVal b As Integer) As Integer Return b Or bitMask(bit - 1) End Function Public Sub Main Dim kr(maxElement \ bitsWidth) As Integer For i As Integer = 0 To kr.Count() - 1 kr(i) = 0 Next i Dim krCount As Integer = 0 Dim n21 As Integer = 3 Dim n31 As Integer = 4 Dim p10 As Integer = 1000 Dim iBit As Integer = 0 Dim iOverBw As Integer = 0 Dim p2Bit As Integer = 1 Dim p2OverBw As Integer = 0 Dim p3Bit As Integer = 1 Dim p3OverBw As Integer = 0 kr(0) = SetBit(1, kr(0)) Dim kri As Boolean = True Dim lastI As Integer = 0 For i As Integer = 1 To maxElement iBit += 1 If iBit > bitsWidth Then iBit = 1 iOverBw += 1 End If If i = n21 Then If BitSet(p2Bit, kr(p2OverBw)) Then kri = True End If p2Bit += 1 If p2Bit > bitsWidth Then p2Bit = 1 p2OverBw += 1 End If n21 += 2 End If If i = n31 Then If BitSet(p3Bit, kr(p3OverBw)) Then kri = True End If p3Bit += 1 If p3Bit > bitsWidth Then p3Bit = 1 p3OverBw += 1 End If n31 += 3 End If If kri Then lastI = i kr(iOverBw) = SetBit(iBit, kr(iOverBw)) krCount += 1 If krCount <= 100 Then Console.Out.Write(" " & i.ToString().PadLeft(3)) If krCount Mod 20 = 0 Then Console.Out.WriteLine() End If ElseIf krCount = p10 Then Console.Out.WriteLine("Element " & p10.ToString().PadLeft(10) & " is " & i.ToString().PadLeft(10)) p10 *= 10 End If kri = False End If Next i Console.Out.WriteLine("Element " & krCount.ToString().PadLeft(10) & " is " & lastI.ToString().PadLeft(10)) End Sub End Module
def KlarnerRado(N): K = [1] for i in range(N): j = K[i] firstadd, secondadd = 2 * j + 1, 3 * j + 1 if firstadd < K[-1]: for pos in range(len(K)-1, 1, -1): if K[pos] < firstadd < K[pos + 1]: K.insert(pos + 1, firstadd) break elif firstadd > K[-1]: K.append(firstadd) if secondadd < K[-1]: for pos in range(len(K)-1, 1, -1): if K[pos] < secondadd < K[pos + 1]: K.insert(pos + 1, secondadd) break elif secondadd > K[-1]: K.append(secondadd) return K kr1m = KlarnerRado(100_000) print('First 100 Klarner-Rado sequence numbers:') for idx, v in enumerate(kr1m[:100]): print(f'{v: 4}', end='\n' if (idx + 1) % 20 == 0 else '') for n in [1000, 10_000, 100_000]: print(f'The {n :,}th Klarner-Rado number is {kr1m[n-1] :,}')
Port the provided VB code into Python while preserving the original functionality.
Public Sub printarray(A) For i = LBound(A) To UBound(A) Debug.Print A(i), Next Debug.Print End Sub Public Sub Flip(ByRef A, p1, p2, trace) If trace Then Debug.Print "we Cut = Int((p2 - p1 + 1) / 2) For i = 0 To Cut - 1 temp = A(i) A(i) = A(p2 - i) A(p2 - i) = temp Next End Sub Public Sub pancakesort(ByRef A(), Optional trace As Boolean = False) lb = LBound(A) ub = UBound(A) Length = ub - lb + 1 If Length <= 1 Then Exit Sub End If For i = ub To lb + 1 Step -1 P = lb Maximum = A(P) For j = lb + 1 To i If A(j) > Maximum Then P = j Maximum = A(j) End If Next j If P < i Then If P > 1 Then Flip A, lb, P, trace If trace Then printarray A End If Flip A, lb, i, trace If trace Then printarray A End If Next i End Sub Public Sub TestPancake(Optional trace As Boolean = False) Dim A() A = Array(5, 7, 8, 3, 1, 10, 9, 23, 50, 0) Debug.Print "Initial array:" printarray A pancakesort A, trace Debug.Print "Final array:" printarray A End Sub
tutor = False def pancakesort(data): if len(data) <= 1: return data if tutor: print() for size in range(len(data), 1, -1): maxindex = max(range(size), key=data.__getitem__) if maxindex+1 != size: if maxindex != 0: if tutor: print('With: %r doflip %i' % ( ' '.join(str(x) for x in data), maxindex+1 )) data[:maxindex+1] = reversed(data[:maxindex+1]) if tutor: print('With: %r doflip %i' % ( ' '.join(str(x) for x in data), size )) data[:size] = reversed(data[:size]) if tutor: print()
Change the following VB code into Python without altering its purpose.
Module Module1 Dim atomicMass As New Dictionary(Of String, Double) From { {"H", 1.008}, {"He", 4.002602}, {"Li", 6.94}, {"Be", 9.0121831}, {"B", 10.81}, {"C", 12.011}, {"N", 14.007}, {"O", 15.999}, {"F", 18.998403163}, {"Ne", 20.1797}, {"Na", 22.98976928}, {"Mg", 24.305}, {"Al", 26.9815385}, {"Si", 28.085}, {"P", 30.973761998}, {"S", 32.06}, {"Cl", 35.45}, {"Ar", 39.948}, {"K", 39.0983}, {"Ca", 40.078}, {"Sc", 44.955908}, {"Ti", 47.867}, {"V", 50.9415}, {"Cr", 51.9961}, {"Mn", 54.938044}, {"Fe", 55.845}, {"Co", 58.933194}, {"Ni", 58.6934}, {"Cu", 63.546}, {"Zn", 65.38}, {"Ga", 69.723}, {"Ge", 72.63}, {"As", 74.921595}, {"Se", 78.971}, {"Br", 79.904}, {"Kr", 83.798}, {"Rb", 85.4678}, {"Sr", 87.62}, {"Y", 88.90584}, {"Zr", 91.224}, {"Nb", 92.90637}, {"Mo", 95.95}, {"Ru", 101.07}, {"Rh", 102.9055}, {"Pd", 106.42}, {"Ag", 107.8682}, {"Cd", 112.414}, {"In", 114.818}, {"Sn", 118.71}, {"Sb", 121.76}, {"Te", 127.6}, {"I", 126.90447}, {"Xe", 131.293}, {"Cs", 132.90545196}, {"Ba", 137.327}, {"La", 138.90547}, {"Ce", 140.116}, {"Pr", 140.90766}, {"Nd", 144.242}, {"Pm", 145}, {"Sm", 150.36}, {"Eu", 151.964}, {"Gd", 157.25}, {"Tb", 158.92535}, {"Dy", 162.5}, {"Ho", 164.93033}, {"Er", 167.259}, {"Tm", 168.93422}, {"Yb", 173.054}, {"Lu", 174.9668}, {"Hf", 178.49}, {"Ta", 180.94788}, {"W", 183.84}, {"Re", 186.207}, {"Os", 190.23}, {"Ir", 192.217}, {"Pt", 195.084}, {"Au", 196.966569}, {"Hg", 200.592}, {"Tl", 204.38}, {"Pb", 207.2}, {"Bi", 208.9804}, {"Po", 209}, {"At", 210}, {"Rn", 222}, {"Fr", 223}, {"Ra", 226}, {"Ac", 227}, {"Th", 232.0377}, {"Pa", 231.03588}, {"U", 238.02891}, {"Np", 237}, {"Pu", 244}, {"Am", 243}, {"Cm", 247}, {"Bk", 247}, {"Cf", 251}, {"Es", 252}, {"Fm", 257}, {"Uue", 315}, {"Ubn", 299} } Function Evaluate(s As String) As Double s += "[" Dim sum = 0.0 Dim symbol = "" Dim number = "" For i = 1 To s.Length Dim c = s(i - 1) If "@" <= c AndAlso c <= "[" Then Dim n = 1 If number <> "" Then n = Integer.Parse(number) End If If symbol <> "" Then sum += atomicMass(symbol) * n End If If c = "[" Then Exit For End If symbol = c.ToString number = "" ElseIf "a" <= c AndAlso c <= "z" Then symbol += c ElseIf "0" <= c AndAlso c <= "9" Then number += c Else Throw New Exception(String.Format("Unexpected symbol {0} in molecule", c)) End If Next Return sum End Function Function ReplaceFirst(text As String, search As String, replace As String) As String Dim pos = text.IndexOf(search) If pos < 0 Then Return text Else Return text.Substring(0, pos) + replace + text.Substring(pos + search.Length) End If End Function Function ReplaceParens(s As String) As String Dim letter = "s"c While True Dim start = s.IndexOf("(") If start = -1 Then Exit While End If For i = start + 1 To s.Length - 1 If s(i) = ")" Then Dim expr = s.Substring(start + 1, i - start - 1) Dim symbol = String.Format("@{0}", letter) s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol) atomicMass(symbol) = Evaluate(expr) letter = Chr(Asc(letter) + 1) Exit For End If If s(i) = "(" Then start = i Continue For End If Next End While Return s End Function Sub Main() Dim molecules() As String = { "H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12", "COOH(C(CH3)2)3CH3", "C6H4O2(OH)4", "C27H46O", "Uue" } For Each molecule In molecules Dim mass = Evaluate(ReplaceParens(molecule)) Console.WriteLine("{0,17} -> {1,7:0.000}", molecule, mass) Next End Sub End Module
assert 1.008 == molar_mass('H') assert 2.016 == molar_mass('H2') assert 18.015 == molar_mass('H2O') assert 34.014 == molar_mass('H2O2') assert 34.014 == molar_mass('(HO)2') assert 142.036 == molar_mass('Na2SO4') assert 84.162 == molar_mass('C6H12') assert 186.295 == molar_mass('COOH(C(CH3)2)3CH3') assert 176.124 == molar_mass('C6H4O2(OH)4') assert 386.664 == molar_mass('C27H46O') assert 315 == molar_mass('Uue')
Generate an equivalent Python version of this VB code.
Const n = 2200 Public Sub pq() Dim s As Long, s1 As Long, s2 As Long, x As Long, x2 As Long, y As Long: s = 3 Dim l(n) As Boolean, l_add(9680000) As Boolean For x = 1 To n x2 = x * x For y = x To n l_add(x2 + y * y) = True Next y Next x For x = 1 To n s1 = s s = s + 2 s2 = s For y = x + 1 To n If l_add(s1) Then l(y) = True s1 = s1 + s2 s2 = s2 + 2 Next Next For x = 1 To n If Not l(x) Then Debug.Print x; Next Debug.Print End Sub
def quad(top=2200): r = [False] * top ab = [False] * (top * 2)**2 for a in range(1, top): for b in range(a, top): ab[a * a + b * b] = True s = 3 for c in range(1, top): s1, s, s2 = s, s + 2, s + 2 for d in range(c + 1, top): if ab[s1]: r[d] = True s1 += s2 s2 += 2 return [i for i, val in enumerate(r) if not val and i] if __name__ == '__main__': n = 2200 print(f"Those values of d in 1..{n} that can't be represented: {quad(n)}")
Convert the following code from VB to Python, ensuring the logic remains intact.
Option Explicit Randomize Timer Function pad(s,n) If n<0 Then pad= right(space(-n) & s ,-n) Else pad= left(s& space(n),n) End If End Function Sub print(s) On Error Resume Next WScript.stdout.WriteLine (s) If err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit End Sub Function Rounds(maxsecs,wiz,a) Dim mystep,maxstep,toend,j,i,x,d If IsArray(a) Then d=True: print "seconds behind pending" maxstep=100 For j=1 To maxsecs For i=1 To wiz If Int(Rnd*maxstep)<=mystep Then mystep=mystep+1 maxstep=maxstep+1 Next mystep=mystep+1 If mystep=maxstep Then Rounds=Array(j,maxstep) :Exit Function If d Then If j>=a(0) And j<=a(1) Then print pad(j,-7) & pad (mystep,-7) & pad (maxstep-mystep,-8) End If Next Rounds=Array(maxsecs,maxstep) End Function Dim n,r,a,sumt,sums,ntests,t,maxsecs ntests=10000 maxsecs=7000 t=timer a=Array(600,609) For n=1 To ntests r=Rounds(maxsecs,5,a) If r(0)<>maxsecs Then sumt=sumt+r(0) sums=sums+r(1) End if a="" Next print vbcrlf & "Done " & ntests & " tests in " & Timer-t & " seconds" print "escaped in " & sumt/ntests & " seconds with " & sums/ntests & " stairs"
from numpy import mean from random import sample def gen_long_stairs(start_step, start_length, climber_steps, add_steps): secs, behind, total = 0, start_step, start_length while True: behind += climber_steps behind += sum([behind > n for n in sample(range(total), add_steps)]) total += add_steps secs += 1 yield (secs, behind, total) ls = gen_long_stairs(1, 100, 1, 5) print("Seconds Behind Ahead\n----------------------") while True: secs, pos, len = next(ls) if 600 <= secs < 610: print(secs, " ", pos, " ", len - pos) elif secs == 610: break print("\nTen thousand trials to top:") times, heights = [], [] for trial in range(10_000): trialstairs = gen_long_stairs(1, 100, 1, 5) while True: sec, step, height = next(trialstairs) if step >= height: times.append(sec) heights.append(height) break print("Mean time:", mean(times), "secs. Mean height:", mean(heights))
Generate an equivalent Python version of this VB code.
Option Explicit Dim seed As Long Sub Main() Dim i As Integer seed = 675248 For i = 1 To 5 Debug.Print Rand Next i End Sub Function Rand() As Variant Dim s As String s = CStr(seed ^ 2) Do While Len(s) <> 12 s = "0" + s Loop seed = Val(Mid(s, 4, 6)) Rand = seed End Function
seed = 675248 def random(): global seed seed = int(str(seed ** 2).zfill(12)[3:9]) return seed for _ in range(5): print(random())
Convert the following code from VB to Python, ensuring the logic remains intact.
Option Explicit Dim seed As Long Sub Main() Dim i As Integer seed = 675248 For i = 1 To 5 Debug.Print Rand Next i End Sub Function Rand() As Variant Dim s As String s = CStr(seed ^ 2) Do While Len(s) <> 12 s = "0" + s Loop seed = Val(Mid(s, 4, 6)) Rand = seed End Function
seed = 675248 def random(): global seed seed = int(str(seed ** 2).zfill(12)[3:9]) return seed for _ in range(5): print(random())
Preserve the algorithm and functionality while converting the code from VB to Python.
Set objFSO = CreateObject("Scripting.FileSystemObject") Set objParamLookup = CreateObject("Scripting.Dictionary") With objParamLookup .Add "FAVOURITEFRUIT", "banana" .Add "NEEDSPEELING", "" .Add "SEEDSREMOVED", "" .Add "NUMBEROFBANANAS", "1024" .Add "NUMBEROFSTRAWBERRIES", "62000" End With Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\IN_config.txt",1) Output = "" Isnumberofstrawberries = False With objInFile Do Until .AtEndOfStream line = .ReadLine If Left(line,1) = "#" Or line = "" Then Output = Output & line & vbCrLf ElseIf Left(line,1) = " " And InStr(line,"#") Then Output = Output & Mid(line,InStr(1,line,"#"),1000) & vbCrLf ElseIf Replace(Replace(line,";","")," ","") <> "" Then If InStr(1,line,"FAVOURITEFRUIT",1) Then Output = Output & "FAVOURITEFRUIT" & " " & objParamLookup.Item("FAVOURITEFRUIT") & vbCrLf ElseIf InStr(1,line,"NEEDSPEELING",1) Then Output = Output & "; " & "NEEDSPEELING" & vbCrLf ElseIf InStr(1,line,"SEEDSREMOVED",1) Then Output = Output & "SEEDSREMOVED" & vbCrLf ElseIf InStr(1,line,"NUMBEROFBANANAS",1) Then Output = Output & "NUMBEROFBANANAS" & " " & objParamLookup.Item("NUMBEROFBANANAS") & vbCrLf ElseIf InStr(1,line,"NUMBEROFSTRAWBERRIES",1) Then Output = Output & "NUMBEROFSTRAWBERRIES" & " " & objParamLookup.Item("NUMBEROFSTRAWBERRIES") & vbCrLf Isnumberofstrawberries = True End If End If Loop If Isnumberofstrawberries = False Then Output = Output & "NUMBEROFSTRAWBERRIES" & " " & objParamLookup.Item("NUMBEROFSTRAWBERRIES") & vbCrLf Isnumberofstrawberries = True End If .Close End With Set objOutFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\OUT_config.txt",2,True) With objOutFile .Write Output .Close End With Set objFSO = Nothing Set objParamLookup = Nothing
import re import string DISABLED_PREFIX = ';' class Option(object): def __init__(self, name, value=None, disabled=False, disabled_prefix=DISABLED_PREFIX): self.name = str(name) self.value = value self.disabled = bool(disabled) self.disabled_prefix = disabled_prefix def __str__(self): disabled = ('', '%s ' % self.disabled_prefix)[self.disabled] value = (' %s' % self.value, '')[self.value is None] return ''.join((disabled, self.name, value)) def get(self): enabled = not bool(self.disabled) if self.value is None: value = enabled else: value = enabled and self.value return value class Config(object): reOPTION = r'^\s*(?P<disabled>%s*)\s*(?P<name>\w+)(?:\s+(?P<value>.+?))?\s*$' def __init__(self, fname=None, disabled_prefix=DISABLED_PREFIX): self.disabled_prefix = disabled_prefix self.contents = [] self.options = {} self.creOPTION = re.compile(self.reOPTION % self.disabled_prefix) if fname: self.parse_file(fname) def __str__(self): return '\n'.join(map(str, self.contents)) def parse_file(self, fname): with open(fname) as f: self.parse_lines(f) return self def parse_lines(self, lines): for line in lines: self.parse_line(line) return self def parse_line(self, line): s = ''.join(c for c in line.strip() if c in string.printable) moOPTION = self.creOPTION.match(s) if moOPTION: name = moOPTION.group('name').upper() if not name in self.options: self.add_option(name, moOPTION.group('value'), moOPTION.group('disabled')) else: if not s.startswith(self.disabled_prefix): self.contents.append(line.rstrip()) return self def add_option(self, name, value=None, disabled=False): name = name.upper() opt = Option(name, value, disabled) self.options[name] = opt self.contents.append(opt) return opt def set_option(self, name, value=None, disabled=False): name = name.upper() opt = self.options.get(name) if opt: opt.value = value opt.disabled = disabled else: opt = self.add_option(name, value, disabled) return opt def enable_option(self, name, value=None): return self.set_option(name, value, False) def disable_option(self, name, value=None): return self.set_option(name, value, True) def get_option(self, name): opt = self.options.get(name.upper()) value = opt.get() if opt else None return value if __name__ == '__main__': import sys cfg = Config(sys.argv[1] if len(sys.argv) > 1 else None) cfg.disable_option('needspeeling') cfg.enable_option('seedsremoved') cfg.enable_option('numberofbananas', 1024) cfg.enable_option('numberofstrawberries', 62000) print cfg
Generate a Python translation of this VB snippet without changing its computational steps.
Option Base 1 Public Enum attr Colour = 1 Nationality Beverage Smoke Pet End Enum Public Enum Drinks_ Beer = 1 Coffee Milk Tea Water End Enum Public Enum nations Danish = 1 English German Norwegian Swedish End Enum Public Enum colors Blue = 1 Green Red White Yellow End Enum Public Enum tobaccos Blend = 1 BlueMaster Dunhill PallMall Prince End Enum Public Enum animals Bird = 1 Cat Dog Horse Zebra End Enum Public permutation As New Collection Public perm(5) As Variant Const factorial5 = 120 Public Colours As Variant, Nationalities As Variant, Drinks As Variant, Smokes As Variant, Pets As Variant Private Sub generate(n As Integer, A As Variant) If n = 1 Then permutation.Add A Else For i = 1 To n generate n - 1, A If n Mod 2 = 0 Then tmp = A(i) A(i) = A(n) A(n) = tmp Else tmp = A(1) A(1) = A(n) A(n) = tmp End If Next i End If End Sub Function house(i As Integer, name As Variant) As Integer Dim x As Integer For x = 1 To 5 If perm(i)(x) = name Then house = x Exit For End If Next x End Function Function left_of(h1 As Integer, h2 As Integer) As Boolean left_of = (h1 - h2) = -1 End Function Function next_to(h1 As Integer, h2 As Integer) As Boolean next_to = Abs(h1 - h2) = 1 End Function Private Sub print_house(i As Integer) Debug.Print i & ": "; Colours(perm(Colour)(i)), Nationalities(perm(Nationality)(i)), _ Drinks(perm(Beverage)(i)), Smokes(perm(Smoke)(i)), Pets(perm(Pet)(i)) End Sub Public Sub Zebra_puzzle() Colours = [{"blue","green","red","white","yellow"}] Nationalities = [{"Dane","English","German","Norwegian","Swede"}] Drinks = [{"beer","coffee","milk","tea","water"}] Smokes = [{"Blend","Blue Master","Dunhill","Pall Mall","Prince"}] Pets = [{"birds","cats","dog","horse","zebra"}] Dim solperms As New Collection Dim solutions As Integer Dim b(5) As Integer, i As Integer For i = 1 To 5: b(i) = i: Next i generate 5, b For c = 1 To factorial5 perm(Colour) = permutation(c) If left_of(house(Colour, Green), house(Colour, White)) Then For n = 1 To factorial5 perm(Nationality) = permutation(n) If house(Nationality, Norwegian) = 1 _ And house(Nationality, English) = house(Colour, Red) _ And next_to(house(Nationality, Norwegian), house(Colour, Blue)) Then For d = 1 To factorial5 perm(Beverage) = permutation(d) If house(Nationality, Danish) = house(Beverage, Tea) _ And house(Beverage, Coffee) = house(Colour, Green) _ And house(Beverage, Milk) = 3 Then For s = 1 To factorial5 perm(Smoke) = permutation(s) If house(Colour, Yellow) = house(Smoke, Dunhill) _ And house(Nationality, German) = house(Smoke, Prince) _ And house(Smoke, BlueMaster) = house(Beverage, Beer) _ And next_to(house(Beverage, Water), house(Smoke, Blend)) Then For p = 1 To factorial5 perm(Pet) = permutation(p) If house(Nationality, Swedish) = house(Pet, Dog) _ And house(Smoke, PallMall) = house(Pet, Bird) _ And next_to(house(Smoke, Blend), house(Pet, Cat)) _ And next_to(house(Pet, Horse), house(Smoke, Dunhill)) Then For i = 1 To 5 print_house i Next i Debug.Print solutions = solutions + 1 solperms.Add perm End If Next p End If Next s End If Next d End If Next n End If Next c Debug.Print Format(solutions, "@"); " solution" & IIf(solutions > 1, "s", "") & " found" For i = 1 To solperms.Count For j = 1 To 5 perm(j) = solperms(i)(j) Next j Debug.Print "The " & Nationalities(perm(Nationality)(house(Pet, Zebra))) & " owns the Zebra" Next i End Sub
from logpy import * from logpy.core import lall import time def lefto(q, p, list): return membero((q,p), zip(list, list[1:])) def nexto(q, p, list): return conde([lefto(q, p, list)], [lefto(p, q, list)]) houses = var() zebraRules = lall( (eq, (var(), var(), var(), var(), var()), houses), (membero, ('Englishman', var(), var(), var(), 'red'), houses), (membero, ('Swede', var(), var(), 'dog', var()), houses), (membero, ('Dane', var(), 'tea', var(), var()), houses), (lefto, (var(), var(), var(), var(), 'green'), (var(), var(), var(), var(), 'white'), houses), (membero, (var(), var(), 'coffee', var(), 'green'), houses), (membero, (var(), 'Pall Mall', var(), 'birds', var()), houses), (membero, (var(), 'Dunhill', var(), var(), 'yellow'), houses), (eq, (var(), var(), (var(), var(), 'milk', var(), var()), var(), var()), houses), (eq, (('Norwegian', var(), var(), var(), var()), var(), var(), var(), var()), houses), (nexto, (var(), 'Blend', var(), var(), var()), (var(), var(), var(), 'cats', var()), houses), (nexto, (var(), 'Dunhill', var(), var(), var()), (var(), var(), var(), 'horse', var()), houses), (membero, (var(), 'Blue Master', 'beer', var(), var()), houses), (membero, ('German', 'Prince', var(), var(), var()), houses), (nexto, ('Norwegian', var(), var(), var(), var()), (var(), var(), var(), var(), 'blue'), houses), (nexto, (var(), 'Blend', var(), var(), var()), (var(), var(), 'water', var(), var()), houses), (membero, (var(), var(), var(), 'zebra', var()), houses) ) t0 = time.time() solutions = run(0, houses, zebraRules) t1 = time.time() dur = t1-t0 count = len(solutions) zebraOwner = [house for house in solutions[0] if 'zebra' in house][0][0] print "%i solutions in %.2f seconds" % (count, dur) print "The %s is the owner of the zebra" % zebraOwner print "Here are all the houses:" for line in solutions[0]: print str(line)
Generate an equivalent Python version of this VB code.
Set http= CreateObject("WinHttp.WinHttpRequest.5.1") Set oDic = WScript.CreateObject("scripting.dictionary") start="https://rosettacode.org" Const lang="VBScript" Dim oHF gettaskslist "about:/wiki/Category:Programming_Tasks" ,True print odic.Count gettaskslist "about:/wiki/Category:Draft_Programming_Tasks",True print "total tasks " & odic.Count gettaskslist "about:/wiki/Category:"&lang,False print "total tasks not in " & lang & " " &odic.Count & vbcrlf For Each d In odic.keys print d &vbTab & Replace(odic(d),"about:", start) next WScript.Quit(1) Sub print(s): On Error Resume Next WScript.stdout.WriteLine (s) If err= &h80070006& Then WScript.echo " Please run this script with CScript": WScript.quit End Sub Function getpage(name) Set oHF=Nothing Set oHF = CreateObject("HTMLFILE") http.open "GET",name,False http.send oHF.write "<html><body></body></html>" oHF.body.innerHTML = http.responsetext Set getpage=Nothing End Function Sub gettaskslist(b,build) nextpage=b While nextpage <>"" nextpage=Replace(nextpage,"about:", start) WScript.Echo nextpage getpage(nextpage) Set xtoc = oHF.getElementbyId("mw-pages") nextpage="" For Each ch In xtoc.children If ch.innertext= "next page" Then nextpage=ch.attributes("href").value ElseIf ch.attributes("class").value="mw-content-ltr" Then Set ytoc=ch.children(0) Exit For End If Next For Each ch1 In ytoc.children For Each ch2 In ch1.children(1).children Set ch=ch2.children(0) If build Then odic.Add ch.innertext , ch.attributes("href").value else odic.Remove ch.innertext End if Next Next Wend End Sub
from operator import attrgetter from typing import Iterator import mwclient URL = 'www.rosettacode.org' API_PATH = '/mw/' def unimplemented_tasks(language: str, *, url: str, api_path: str) -> Iterator[str]: site = mwclient.Site(url, path=api_path) all_tasks = site.categories['Programming Tasks'] language_tasks = site.categories[language] name = attrgetter('name') all_tasks_names = map(name, all_tasks) language_tasks_names = set(map(name, language_tasks)) for task in all_tasks_names: if task not in language_tasks_names: yield task if __name__ == '__main__': tasks = unimplemented_tasks('Python', url=URL, api_path=API_PATH) print(*tasks, sep='\n')
Translate this program into Python but keep the logic exactly as in VB.
Imports System, BI = System.Numerics.BigInteger, System.Console Module Module1 Function isqrt(ByVal x As BI) As BI Dim t As BI, q As BI = 1, r As BI = 0 While q <= x : q <<= 2 : End While While q > 1 : q >>= 2 : t = x - r - q : r >>= 1 If t >= 0 Then x = t : r += q End While : Return r End Function Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String digs += 1 Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1 For n As BI = 0 To dg - 1 If n > 0 Then t3 = t3 * BI.Pow(n, 6) te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6 If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z) If show AndAlso n < 10 Then WriteLine("{0,2} {1,62}", n, te * 32 / 3 / t) su += te : If te < 10 Then digs -= 1 If show Then WriteLine(vbLf & "{0} iterations required for {1} digits " & _ "after the decimal point." & vbLf, n, digs) Exit For End If For j As BI = n * 6 + 1 To n * 6 + 6 t1 = t1 * j : Next d += 2 : t2 += 126 + 532 * d Next Dim s As String = String.Format("{0}", isqrt(BI.Pow(10, dg * 2 + 3) _ / su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5))) Return s(0) & "." & s.Substring(1, digs) End Function Sub Main(ByVal args As String()) WriteLine(dump(70, true)) End Sub End Module
import mpmath as mp with mp.workdps(72): def integer_term(n): p = 532 * n * n + 126 * n + 9 return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6) def exponent_term(n): return -(mp.mpf("6.0") * n + 3) def nthterm(n): return integer_term(n) * mp.mpf("10.0")**exponent_term(n) for n in range(10): print("Term ", n, ' ', int(integer_term(n))) def almkvist_guillera(floatprecision): summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0') for n in range(100000000): nextadd = summed + nthterm(n) if abs(nextadd - summed) < 10.0**(-floatprecision): break summed = nextadd return nextadd print('\nπ to 70 digits is ', end='') mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71) print('mpmath π is ', end='') mp.nprint(mp.pi, 71)
Convert this VB block to Python, preserving its control flow and logic.
Imports System, BI = System.Numerics.BigInteger, System.Console Module Module1 Function isqrt(ByVal x As BI) As BI Dim t As BI, q As BI = 1, r As BI = 0 While q <= x : q <<= 2 : End While While q > 1 : q >>= 2 : t = x - r - q : r >>= 1 If t >= 0 Then x = t : r += q End While : Return r End Function Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String digs += 1 Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1 For n As BI = 0 To dg - 1 If n > 0 Then t3 = t3 * BI.Pow(n, 6) te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6 If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z) If show AndAlso n < 10 Then WriteLine("{0,2} {1,62}", n, te * 32 / 3 / t) su += te : If te < 10 Then digs -= 1 If show Then WriteLine(vbLf & "{0} iterations required for {1} digits " & _ "after the decimal point." & vbLf, n, digs) Exit For End If For j As BI = n * 6 + 1 To n * 6 + 6 t1 = t1 * j : Next d += 2 : t2 += 126 + 532 * d Next Dim s As String = String.Format("{0}", isqrt(BI.Pow(10, dg * 2 + 3) _ / su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5))) Return s(0) & "." & s.Substring(1, digs) End Function Sub Main(ByVal args As String()) WriteLine(dump(70, true)) End Sub End Module
import mpmath as mp with mp.workdps(72): def integer_term(n): p = 532 * n * n + 126 * n + 9 return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6) def exponent_term(n): return -(mp.mpf("6.0") * n + 3) def nthterm(n): return integer_term(n) * mp.mpf("10.0")**exponent_term(n) for n in range(10): print("Term ", n, ' ', int(integer_term(n))) def almkvist_guillera(floatprecision): summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0') for n in range(100000000): nextadd = summed + nthterm(n) if abs(nextadd - summed) < 10.0**(-floatprecision): break summed = nextadd return nextadd print('\nπ to 70 digits is ', end='') mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71) print('mpmath π is ', end='') mp.nprint(mp.pi, 71)
Ensure the translated Python code behaves exactly like the original VB snippet.
Imports System.Collections.Generic, System.Linq, System.Console Module Module1 Function soas(ByVal n As Integer, ByVal f As IEnumerable(Of Integer)) As Boolean If n <= 0 Then Return False Else If f.Contains(n) Then Return True Select Case n.CompareTo(f.Sum()) Case 1 : Return False : Case 0 : Return True Case -1 : Dim rf As List(Of Integer) = f.Reverse().ToList() : Dim D as Integer = n - rf(0) rf.RemoveAt(0) : Return soas(d, rf) OrElse soas(n, rf) End Select : Return true End Function Function ip(ByVal n As Integer) As Boolean Dim f As IEnumerable(Of Integer) = Enumerable.Range(1, n >> 1).Where(Function(d) n Mod d = 0).ToList() Return Enumerable.Range(1, n - 1).ToList().TrueForAll(Function(i) soas(i, f)) End Function Sub Main() Dim c As Integer = 0, m As Integer = 333, i As Integer = 1 : While i <= m If ip(i) OrElse i = 1 Then c += 1 : Write("{0,3} {1}", i, If(c Mod 10 = 0, vbLf, "")) i += If(i = 1, 1, 2) : End While Write(vbLf & "Found {0} practical numbers between 1 and {1} inclusive." & vbLf, c, m) Do : m = If(m < 500, m << 1, m * 10 + 6) Write(vbLf & "{0,5} is a{1}practical number.", m, If(ip(m), " ", "n im")) : Loop While m < 1e4 End Sub End Module
from itertools import chain, cycle, accumulate, combinations from typing import List, Tuple def factors5(n: int) -> List[int]: def prime_powers(n): for c in accumulate(chain([2, 1, 2], cycle([2,4]))): if c*c > n: break if n%c: continue d,p = (), c while not n%c: n,p,d = n//c, p*c, d + (p,) yield(d) if n > 1: yield((n,)) r = [1] for e in prime_powers(n): r += [a*b for a in r for b in e] return r[:-1] def powerset(s: List[int]) -> List[Tuple[int, ...]]: return chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1)) def is_practical(x: int) -> bool: if x == 1: return True if x %2: return False f = factors5(x) ps = powerset(f) found = {y for y in {sum(i) for i in ps} if 1 <= y < x} return len(found) == x - 1 if __name__ == '__main__': n = 333 p = [x for x in range(1, n + 1) if is_practical(x)] print(f"There are {len(p)} Practical numbers from 1 to {n}:") print(' ', str(p[:10])[1:-1], '...', str(p[-10:])[1:-1]) x = 666 print(f"\nSTRETCH GOAL: {x} is {'not ' if not is_practical(x) else ''}Practical.")
Translate this program into Python but keep the logic exactly as in VB.
Sub Main() Dim d As Double Dim s As Single d = -12.3456 d = 1000# d = 0.00001 d = 67# d = 8.9 d = 0.33 d = 0# d = 2# * 10 ^ 3 d = 2E+50 d = 2E-50 s = -12.3456! s = 1000! s = 0.00001! s = 67! s = 8.9! s = 0.33! s = 0! s = 2! * 10 ^ 3 End Sub
2.3 .3 .3e4 .3e+34 .3e-34 2.e34
Keep all operations the same but rewrite the snippet in Python.
Module Module1 ReadOnly Dirs As Integer(,) = { {1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1} } Const RowCount = 10 Const ColCount = 10 Const GridSize = RowCount * ColCount Const MinWords = 25 Class Grid Public cells(RowCount - 1, ColCount - 1) As Char Public solutions As New List(Of String) Public numAttempts As Integer Sub New() For i = 0 To RowCount - 1 For j = 0 To ColCount - 1 cells(i, j) = ControlChars.NullChar Next Next End Sub End Class Dim Rand As New Random() Sub Main() PrintResult(CreateWordSearch(ReadWords("unixdict.txt"))) End Sub Function ReadWords(filename As String) As List(Of String) Dim maxlen = Math.Max(RowCount, ColCount) Dim words As New List(Of String) Dim objReader As New IO.StreamReader(filename) Dim line As String Do While objReader.Peek() <> -1 line = objReader.ReadLine() If line.Length > 3 And line.Length < maxlen Then If line.All(Function(c) Char.IsLetter(c)) Then words.Add(line) End If End If Loop Return words End Function Function CreateWordSearch(words As List(Of String)) As Grid For numAttempts = 1 To 1000 Shuffle(words) Dim grid As New Grid() Dim messageLen = PlaceMessage(grid, "Rosetta Code") Dim target = GridSize - messageLen Dim cellsFilled = 0 For Each word In words cellsFilled = cellsFilled + TryPlaceWord(grid, word) If cellsFilled = target Then If grid.solutions.Count >= MinWords Then grid.numAttempts = numAttempts Return grid Else Exit For End If End If Next Next Return Nothing End Function Function PlaceMessage(grid As Grid, msg As String) As Integer msg = msg.ToUpper() msg = msg.Replace(" ", "") If msg.Length > 0 And msg.Length < GridSize Then Dim gapSize As Integer = GridSize / msg.Length Dim pos = 0 Dim lastPos = -1 For i = 0 To msg.Length - 1 If i = 0 Then pos = pos + Rand.Next(gapSize - 1) Else pos = pos + Rand.Next(2, gapSize - 1) End If Dim r As Integer = Math.Floor(pos / ColCount) Dim c = pos Mod ColCount grid.cells(r, c) = msg(i) lastPos = pos Next Return msg.Length End If Return 0 End Function Function TryPlaceWord(grid As Grid, word As String) As Integer Dim randDir = Rand.Next(Dirs.GetLength(0)) Dim randPos = Rand.Next(GridSize) For d = 0 To Dirs.GetLength(0) - 1 Dim dd = (d + randDir) Mod Dirs.GetLength(0) For p = 0 To GridSize - 1 Dim pp = (p + randPos) Mod GridSize Dim lettersPLaced = TryLocation(grid, word, dd, pp) If lettersPLaced > 0 Then Return lettersPLaced End If Next Next Return 0 End Function Function TryLocation(grid As Grid, word As String, dir As Integer, pos As Integer) As Integer Dim r As Integer = pos / ColCount Dim c = pos Mod ColCount Dim len = word.Length If (Dirs(dir, 0) = 1 And len + c >= ColCount) Or (Dirs(dir, 0) = -1 And len - 1 > c) Or (Dirs(dir, 1) = 1 And len + r >= RowCount) Or (Dirs(dir, 1) = -1 And len - 1 > r) Then Return 0 End If If r = RowCount OrElse c = ColCount Then Return 0 End If Dim rr = r Dim cc = c For i = 0 To len - 1 If grid.cells(rr, cc) <> ControlChars.NullChar AndAlso grid.cells(rr, cc) <> word(i) Then Return 0 End If cc = cc + Dirs(dir, 0) rr = rr + Dirs(dir, 1) Next Dim overlaps = 0 rr = r cc = c For i = 0 To len - 1 If grid.cells(rr, cc) = word(i) Then overlaps = overlaps + 1 Else grid.cells(rr, cc) = word(i) End If If i < len - 1 Then cc = cc + Dirs(dir, 0) rr = rr + Dirs(dir, 1) End If Next Dim lettersPlaced = len - overlaps If lettersPlaced > 0 Then grid.solutions.Add(String.Format("{0,-10} ({1},{2})({3},{4})", word, c, r, cc, rr)) End If Return lettersPlaced End Function Sub PrintResult(grid As Grid) If IsNothing(grid) OrElse grid.numAttempts = 0 Then Console.WriteLine("No grid to display") Return End If Console.WriteLine("Attempts: {0}", grid.numAttempts) Console.WriteLine("Number of words: {0}", GridSize) Console.WriteLine() Console.WriteLine(" 0 1 2 3 4 5 6 7 8 9") For r = 0 To RowCount - 1 Console.WriteLine() Console.Write("{0} ", r) For c = 0 To ColCount - 1 Console.Write(" {0} ", grid.cells(r, c)) Next Next Console.WriteLine() Console.WriteLine() For i = 0 To grid.solutions.Count - 1 If i Mod 2 = 0 Then Console.Write("{0}", grid.solutions(i)) Else Console.WriteLine(" {0}", grid.solutions(i)) End If Next Console.WriteLine() End Sub Sub Shuffle(Of T)(list As IList(Of T)) Dim r As Random = New Random() For i = 0 To list.Count - 1 Dim index As Integer = r.Next(i, list.Count) If i <> index Then Dim temp As T = list(i) list(i) = list(index) list(index) = temp End If Next End Sub End Module
import re from random import shuffle, randint dirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]] n_rows = 10 n_cols = 10 grid_size = n_rows * n_cols min_words = 25 class Grid: def __init__(self): self.num_attempts = 0 self.cells = [['' for _ in range(n_cols)] for _ in range(n_rows)] self.solutions = [] def read_words(filename): max_len = max(n_rows, n_cols) words = [] with open(filename, "r") as file: for line in file: s = line.strip().lower() if re.match(r'^[a-z]{3,' + re.escape(str(max_len)) + r'}$', s) is not None: words.append(s) return words def place_message(grid, msg): msg = re.sub(r'[^A-Z]', "", msg.upper()) message_len = len(msg) if 0 < message_len < grid_size: gap_size = grid_size // message_len for i in range(0, message_len): pos = i * gap_size + randint(0, gap_size) grid.cells[pos // n_cols][pos % n_cols] = msg[i] return message_len return 0 def try_location(grid, word, direction, pos): r = pos // n_cols c = pos % n_cols length = len(word) if (dirs[direction][0] == 1 and (length + c) > n_cols) or \ (dirs[direction][0] == -1 and (length - 1) > c) or \ (dirs[direction][1] == 1 and (length + r) > n_rows) or \ (dirs[direction][1] == -1 and (length - 1) > r): return 0 rr = r cc = c i = 0 overlaps = 0 while i < length: if grid.cells[rr][cc] != '' and grid.cells[rr][cc] != word[i]: return 0 cc += dirs[direction][0] rr += dirs[direction][1] i += 1 rr = r cc = c i = 0 while i < length: if grid.cells[rr][cc] == word[i]: overlaps += 1 else: grid.cells[rr][cc] = word[i] if i < length - 1: cc += dirs[direction][0] rr += dirs[direction][1] i += 1 letters_placed = length - overlaps if letters_placed > 0: grid.solutions.append("{0:<10} ({1},{2})({3},{4})".format(word, c, r, cc, rr)) return letters_placed def try_place_word(grid, word): rand_dir = randint(0, len(dirs)) rand_pos = randint(0, grid_size) for direction in range(0, len(dirs)): direction = (direction + rand_dir) % len(dirs) for pos in range(0, grid_size): pos = (pos + rand_pos) % grid_size letters_placed = try_location(grid, word, direction, pos) if letters_placed > 0: return letters_placed return 0 def create_word_search(words): grid = None num_attempts = 0 while num_attempts < 100: num_attempts += 1 shuffle(words) grid = Grid() message_len = place_message(grid, "Rosetta Code") target = grid_size - message_len cells_filled = 0 for word in words: cells_filled += try_place_word(grid, word) if cells_filled == target: if len(grid.solutions) >= min_words: grid.num_attempts = num_attempts return grid else: break return grid def print_result(grid): if grid is None or grid.num_attempts == 0: print("No grid to display") return size = len(grid.solutions) print("Attempts: {0}".format(grid.num_attempts)) print("Number of words: {0}".format(size)) print("\n 0 1 2 3 4 5 6 7 8 9\n") for r in range(0, n_rows): print("{0} ".format(r), end='') for c in range(0, n_cols): print(" %c " % grid.cells[r][c], end='') print() print() for i in range(0, size - 1, 2): print("{0} {1}".format(grid.solutions[i], grid.solutions[i+1])) if size % 2 == 1: print(grid.solutions[size - 1]) if __name__ == "__main__": print_result(create_word_search(read_words("unixdict.txt")))
Translate this program into Python but keep the logic exactly as in VB.
Imports System.Reflection Public Class MyClazz Private answer As Integer = 42 End Class Public Class Program Public Shared Sub Main() Dim myInstance = New MyClazz() Dim fieldInfo = GetType(MyClazz).GetField("answer", BindingFlags.NonPublic Or BindingFlags.Instance) Dim answer = fieldInfo.GetValue(myInstance) Console.WriteLine(answer) End Sub End Class
>>> class MyClassName: __private = 123 non_private = __private * 2 >>> mine = MyClassName() >>> mine.non_private 246 >>> mine.__private Traceback (most recent call last): File "<pyshell mine.__private AttributeError: 'MyClassName' object has no attribute '__private' >>> mine._MyClassName__private 123 >>>
Translate this program into Python but keep the logic exactly as in VB.
Imports System.Reflection Public Class MyClazz Private answer As Integer = 42 End Class Public Class Program Public Shared Sub Main() Dim myInstance = New MyClazz() Dim fieldInfo = GetType(MyClazz).GetField("answer", BindingFlags.NonPublic Or BindingFlags.Instance) Dim answer = fieldInfo.GetValue(myInstance) Console.WriteLine(answer) End Sub End Class
>>> class MyClassName: __private = 123 non_private = __private * 2 >>> mine = MyClassName() >>> mine.non_private 246 >>> mine.__private Traceback (most recent call last): File "<pyshell mine.__private AttributeError: 'MyClassName' object has no attribute '__private' >>> mine._MyClassName__private 123 >>>
Port the provided VB code into Python while preserving the original functionality.
Module Module1 Class Node Public Sub New(Len As Integer) Length = Len Edges = New Dictionary(Of Char, Integer) End Sub Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer) Length = len Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg) Suffix = suf End Sub Property Edges As Dictionary(Of Char, Integer) Property Length As Integer Property Suffix As Integer End Class ReadOnly EVEN_ROOT As Integer = 0 ReadOnly ODD_ROOT As Integer = 1 Function Eertree(s As String) As List(Of Node) Dim tree As New List(Of Node) From { New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT), New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT) } Dim suffix = ODD_ROOT Dim n As Integer Dim k As Integer For i = 1 To s.Length Dim c = s(i - 1) n = suffix While True k = tree(n).Length Dim b = i - k - 2 If b >= 0 AndAlso s(b) = c Then Exit While End If n = tree(n).Suffix End While If tree(n).Edges.ContainsKey(c) Then suffix = tree(n).Edges(c) Continue For End If suffix = tree.Count tree.Add(New Node(k + 2)) tree(n).Edges(c) = suffix If tree(suffix).Length = 1 Then tree(suffix).Suffix = 0 Continue For End If While True n = tree(n).Suffix Dim b = i - tree(n).Length - 2 If b >= 0 AndAlso s(b) = c Then Exit While End If End While Dim a = tree(n) Dim d = a.Edges(c) Dim e = tree(suffix) e.Suffix = d Next Return tree End Function Function SubPalindromes(tree As List(Of Node)) As List(Of String) Dim s As New List(Of String) Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String) For Each c In tree(n).Edges.Keys Dim m = tree(n).Edges(c) Dim p1 = c + p + c s.Add(p1) children(m, p1) Next End Sub children(0, "") For Each c In tree(1).Edges.Keys Dim m = tree(1).Edges(c) Dim ct = c.ToString() s.Add(ct) children(m, ct) Next Return s End Function Sub Main() Dim tree = Eertree("eertree") Dim result = SubPalindromes(tree) Dim listStr = String.Join(", ", result) Console.WriteLine("[{0}]", listStr) End Sub End Module
from __future__ import print_function class Node(object): def __init__(self): self.edges = {} self.link = None self.len = 0 class Eertree(object): def __init__(self): self.nodes = [] self.rto = Node() self.rte = Node() self.rto.link = self.rte.link = self.rto; self.rto.len = -1 self.rte.len = 0 self.S = [0] self.maxSufT = self.rte def get_max_suffix_pal(self, startNode, a): u = startNode i = len(self.S) k = u.len while id(u) != id(self.rto) and self.S[i - k - 1] != a: assert id(u) != id(u.link) u = u.link k = u.len return u def add(self, a): Q = self.get_max_suffix_pal(self.maxSufT, a) createANewNode = not a in Q.edges if createANewNode: P = Node() self.nodes.append(P) P.len = Q.len + 2 if P.len == 1: P.link = self.rte else: P.link = self.get_max_suffix_pal(Q.link, a).edges[a] Q.edges[a] = P self.maxSufT = Q.edges[a] self.S.append(a) return createANewNode def get_sub_palindromes(self, nd, nodesToHere, charsToHere, result): for lnkName in nd.edges: nd2 = nd.edges[lnkName] self.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result) if id(nd) != id(self.rto) and id(nd) != id(self.rte): tmp = "".join(charsToHere) if id(nodesToHere[0]) == id(self.rte): assembled = tmp[::-1] + tmp else: assembled = tmp[::-1] + tmp[1:] result.append(assembled) if __name__=="__main__": st = "eertree" print ("Processing string", st) eertree = Eertree() for ch in st: eertree.add(ch) print ("Number of sub-palindromes:", len(eertree.nodes)) result = [] eertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) eertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) print ("Sub-palindromes:", result)
Maintain the same structure and functionality when rewriting this code in Python.
Module Module1 Class Node Public Sub New(Len As Integer) Length = Len Edges = New Dictionary(Of Char, Integer) End Sub Public Sub New(len As Integer, edg As Dictionary(Of Char, Integer), suf As Integer) Length = len Edges = If(IsNothing(edg), New Dictionary(Of Char, Integer), edg) Suffix = suf End Sub Property Edges As Dictionary(Of Char, Integer) Property Length As Integer Property Suffix As Integer End Class ReadOnly EVEN_ROOT As Integer = 0 ReadOnly ODD_ROOT As Integer = 1 Function Eertree(s As String) As List(Of Node) Dim tree As New List(Of Node) From { New Node(0, New Dictionary(Of Char, Integer), ODD_ROOT), New Node(-1, New Dictionary(Of Char, Integer), ODD_ROOT) } Dim suffix = ODD_ROOT Dim n As Integer Dim k As Integer For i = 1 To s.Length Dim c = s(i - 1) n = suffix While True k = tree(n).Length Dim b = i - k - 2 If b >= 0 AndAlso s(b) = c Then Exit While End If n = tree(n).Suffix End While If tree(n).Edges.ContainsKey(c) Then suffix = tree(n).Edges(c) Continue For End If suffix = tree.Count tree.Add(New Node(k + 2)) tree(n).Edges(c) = suffix If tree(suffix).Length = 1 Then tree(suffix).Suffix = 0 Continue For End If While True n = tree(n).Suffix Dim b = i - tree(n).Length - 2 If b >= 0 AndAlso s(b) = c Then Exit While End If End While Dim a = tree(n) Dim d = a.Edges(c) Dim e = tree(suffix) e.Suffix = d Next Return tree End Function Function SubPalindromes(tree As List(Of Node)) As List(Of String) Dim s As New List(Of String) Dim children As Action(Of Integer, String) = Sub(n As Integer, p As String) For Each c In tree(n).Edges.Keys Dim m = tree(n).Edges(c) Dim p1 = c + p + c s.Add(p1) children(m, p1) Next End Sub children(0, "") For Each c In tree(1).Edges.Keys Dim m = tree(1).Edges(c) Dim ct = c.ToString() s.Add(ct) children(m, ct) Next Return s End Function Sub Main() Dim tree = Eertree("eertree") Dim result = SubPalindromes(tree) Dim listStr = String.Join(", ", result) Console.WriteLine("[{0}]", listStr) End Sub End Module
from __future__ import print_function class Node(object): def __init__(self): self.edges = {} self.link = None self.len = 0 class Eertree(object): def __init__(self): self.nodes = [] self.rto = Node() self.rte = Node() self.rto.link = self.rte.link = self.rto; self.rto.len = -1 self.rte.len = 0 self.S = [0] self.maxSufT = self.rte def get_max_suffix_pal(self, startNode, a): u = startNode i = len(self.S) k = u.len while id(u) != id(self.rto) and self.S[i - k - 1] != a: assert id(u) != id(u.link) u = u.link k = u.len return u def add(self, a): Q = self.get_max_suffix_pal(self.maxSufT, a) createANewNode = not a in Q.edges if createANewNode: P = Node() self.nodes.append(P) P.len = Q.len + 2 if P.len == 1: P.link = self.rte else: P.link = self.get_max_suffix_pal(Q.link, a).edges[a] Q.edges[a] = P self.maxSufT = Q.edges[a] self.S.append(a) return createANewNode def get_sub_palindromes(self, nd, nodesToHere, charsToHere, result): for lnkName in nd.edges: nd2 = nd.edges[lnkName] self.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result) if id(nd) != id(self.rto) and id(nd) != id(self.rte): tmp = "".join(charsToHere) if id(nodesToHere[0]) == id(self.rte): assembled = tmp[::-1] + tmp else: assembled = tmp[::-1] + tmp[1:] result.append(assembled) if __name__=="__main__": st = "eertree" print ("Processing string", st) eertree = Eertree() for ch in st: eertree.add(ch) print ("Number of sub-palindromes:", len(eertree.nodes)) result = [] eertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) eertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) print ("Sub-palindromes:", result)
Change the following VB code into Python without altering its purpose.
DEFINT A-Z DECLARE FUNCTION p% (Yr AS INTEGER) DECLARE FUNCTION LongYear% (Yr AS INTEGER) DIM iYi, iYf, i CLS PRINT "This program calculates which are 53-week years in a range." PRINT INPUT "Initial year"; iYi INPUT "Final year (could be the same)"; iYf IF iYf >= iYi THEN FOR i = iYi TO iYf IF LongYear(i) THEN PRINT i; " "; END IF NEXT i END IF PRINT PRINT PRINT "End of program." END FUNCTION LongYear% (Yr AS INTEGER) LongYear% = (p%(Yr) = 4) OR (p%(Yr - 1) = 3) END FUNCTION FUNCTION p% (Yr AS INTEGER) p% = (Yr + INT(Yr / 4) - INT(Yr / 100) + INT(Yr / 400)) MOD 7 END FUNCTION
from datetime import date def longYear(y): return 52 < date(y, 12, 28).isocalendar()[1] def main(): for year in [ x for x in range(2000, 1 + 2100) if longYear(x) ]: print(year) if __name__ == '__main__': main()
Port the provided VB code into Python while preserving the original functionality.
Module Module1 Function GetDivisors(n As Integer) As List(Of Integer) Dim divs As New List(Of Integer) From { 1, n } Dim i = 2 While i * i <= n If n Mod i = 0 Then Dim j = n \ i divs.Add(i) If i <> j Then divs.Add(j) End If End If i += 1 End While Return divs End Function Function IsPartSum(divs As List(Of Integer), sum As Integer) As Boolean If sum = 0 Then Return True End If Dim le = divs.Count If le = 0 Then Return False End If Dim last = divs(le - 1) Dim newDivs As New List(Of Integer) For i = 1 To le - 1 newDivs.Add(divs(i - 1)) Next If last > sum Then Return IsPartSum(newDivs, sum) End If Return IsPartSum(newDivs, sum) OrElse IsPartSum(newDivs, sum - last) End Function Function IsZumkeller(n As Integer) As Boolean Dim divs = GetDivisors(n) Dim sum = divs.Sum() REM if sum is odd can If sum Mod 2 = 1 Then Return False End If REM if n is odd use If n Mod 2 = 1 Then Dim abundance = sum - 2 * n Return abundance > 0 AndAlso abundance Mod 2 = 0 End If REM if n and sum are both even check if there Return IsPartSum(divs, sum \ 2) End Function Sub Main() Console.WriteLine("The first 220 Zumkeller numbers are:") Dim i = 2 Dim count = 0 While count < 220 If IsZumkeller(i) Then Console.Write("{0,3} ", i) count += 1 If count Mod 20 = 0 Then Console.WriteLine() End If End If i += 1 End While Console.WriteLine() Console.WriteLine("The first 40 odd Zumkeller numbers are:") i = 3 count = 0 While count < 40 If IsZumkeller(i) Then Console.Write("{0,5} ", i) count += 1 If count Mod 10 = 0 Then Console.WriteLine() End If End If i += 2 End While Console.WriteLine() Console.WriteLine("The first 40 odd Zumkeller numbers which don i = 3 count = 0 While count < 40 If i Mod 10 <> 5 AndAlso IsZumkeller(i) Then Console.Write("{0,7} ", i) count += 1 If count Mod 8 = 0 Then Console.WriteLine() End If End If i += 2 End While End Sub End Module
from sympy import divisors from sympy.combinatorics.subsets import Subset def isZumkeller(n): d = divisors(n) s = sum(d) if not s % 2 and max(d) <= s/2: for x in range(1, 2**len(d)): if sum(Subset.unrank_binary(x, d).subset) == s/2: return True return False def printZumkellers(N, oddonly=False): nprinted = 0 for n in range(1, 10**5): if (oddonly == False or n % 2) and isZumkeller(n): print(f'{n:>8}', end='') nprinted += 1 if nprinted % 10 == 0: print() if nprinted >= N: return print("220 Zumkeller numbers:") printZumkellers(220) print("\n\n40 odd Zumkeller numbers:") printZumkellers(40, True)
Generate a Python translation of this VB snippet without changing its computational steps.
Private Type Associative Key As String Value As Variant End Type Sub Main_Array_Associative() Dim BaseArray(2) As Associative, UpdateArray(2) As Associative FillArrays BaseArray, UpdateArray ReDim Result(UBound(BaseArray)) As Associative MergeArray Result, BaseArray, UpdateArray PrintOut Result End Sub Private Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative) Dim i As Long, Respons As Long Res = Base For i = LBound(Update) To UBound(Update) If Exist(Respons, Base, Update(i).Key) Then Res(Respons).Value = Update(i).Value Else ReDim Preserve Res(UBound(Res) + 1) Res(UBound(Res)).Key = Update(i).Key Res(UBound(Res)).Value = Update(i).Value End If Next End Sub Private Function Exist(R As Long, B() As Associative, K As String) As Boolean Dim i As Long Do If B(i).Key = K Then Exist = True R = i End If i = i + 1 Loop While i <= UBound(B) And Not Exist End Function Private Sub FillArrays(B() As Associative, U() As Associative) B(0).Key = "name" B(0).Value = "Rocket Skates" B(1).Key = "price" B(1).Value = 12.75 B(2).Key = "color" B(2).Value = "yellow" U(0).Key = "price" U(0).Value = 15.25 U(1).Key = "color" U(1).Value = "red" U(2).Key = "year" U(2).Value = 1974 End Sub Private Sub PrintOut(A() As Associative) Dim i As Long Debug.Print "Key", "Value" For i = LBound(A) To UBound(A) Debug.Print A(i).Key, A(i).Value Next i Debug.Print "-----------------------------" End Sub
base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"} update = {"price":15.25, "color":"red", "year":1974} result = {**base, **update} print(result)
Generate an equivalent Python version of this VB code.
Private Type Associative Key As String Value As Variant End Type Sub Main_Array_Associative() Dim BaseArray(2) As Associative, UpdateArray(2) As Associative FillArrays BaseArray, UpdateArray ReDim Result(UBound(BaseArray)) As Associative MergeArray Result, BaseArray, UpdateArray PrintOut Result End Sub Private Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative) Dim i As Long, Respons As Long Res = Base For i = LBound(Update) To UBound(Update) If Exist(Respons, Base, Update(i).Key) Then Res(Respons).Value = Update(i).Value Else ReDim Preserve Res(UBound(Res) + 1) Res(UBound(Res)).Key = Update(i).Key Res(UBound(Res)).Value = Update(i).Value End If Next End Sub Private Function Exist(R As Long, B() As Associative, K As String) As Boolean Dim i As Long Do If B(i).Key = K Then Exist = True R = i End If i = i + 1 Loop While i <= UBound(B) And Not Exist End Function Private Sub FillArrays(B() As Associative, U() As Associative) B(0).Key = "name" B(0).Value = "Rocket Skates" B(1).Key = "price" B(1).Value = 12.75 B(2).Key = "color" B(2).Value = "yellow" U(0).Key = "price" U(0).Value = 15.25 U(1).Key = "color" U(1).Value = "red" U(2).Key = "year" U(2).Value = 1974 End Sub Private Sub PrintOut(A() As Associative) Dim i As Long Debug.Print "Key", "Value" For i = LBound(A) To UBound(A) Debug.Print A(i).Key, A(i).Value Next i Debug.Print "-----------------------------" End Sub
base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"} update = {"price":15.25, "color":"red", "year":1974} result = {**base, **update} print(result)
Preserve the algorithm and functionality while converting the code from VB to Python.
Imports BI = System.Numerics.BigInteger Module Module1 Function IntSqRoot(v As BI, res As BI) As BI REM res is the initial guess Dim term As BI = 0 Dim d As BI = 0 Dim dl As BI = 1 While dl <> d term = v / res res = (res + term) >> 1 dl = d d = term - res End While Return term End Function Function DoOne(b As Integer, digs As Integer) As String REM calculates result via square root, not iterations Dim s = b * b + 4 digs += 1 Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs)) Dim bs = IntSqRoot(s * BI.Parse("1" + New String("0", digs << 1)), g) bs += b * BI.Parse("1" + New String("0", digs)) bs >>= 1 bs += 4 Dim st = bs.ToString digs -= 1 Return String.Format("{0}.{1}", st(0), st.Substring(1, digs)) End Function Function DivIt(a As BI, b As BI, digs As Integer) As String REM performs division Dim al = a.ToString.Length Dim bl = b.ToString.Length digs += 1 a *= BI.Pow(10, digs << 1) b *= BI.Pow(10, digs) Dim s = (a / b + 5).ToString digs -= 1 Return s(0) + "." + s.Substring(1, digs) End Function REM custom formatting Function Joined(x() As BI) As String Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13} Dim res = "" For i = 0 To x.Length - 1 res += String.Format("{0," + (-wids(i)).ToString + "} ", x(i)) Next Return res End Function Sub Main() REM calculates and checks each "metal" Console.WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc") Dim t = "" Dim n As BI Dim nm1 As BI Dim k As Integer Dim j As Integer For b = 0 To 9 Dim lst(14) As BI lst(0) = 1 lst(1) = 1 For i = 2 To 14 lst(i) = b * lst(i - 1) + lst(i - 2) Next REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15 n = lst(14) nm1 = lst(13) k = 0 j = 13 While k = 0 Dim lt = t t = DivIt(n, nm1, 32) If lt = t Then k = If(b = 0, 1, j) End If Dim onn = n n = b * n + nm1 nm1 = onn j += 1 End While Console.WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}" + vbNewLine + "{6,19} {7}", "Pt Au Ag CuSn Cu Ni Al Fe Sn Pb".Split(" ")(b), b, b * b + 4, k, t, t = DoOne(b, 32), "", Joined(lst)) Next REM now calculate and check big one n = 1 nm1 = 1 k = 0 j = 1 While k = 0 Dim lt = t t = DivIt(n, nm1, 256) If lt = t Then k = j End If Dim onn = n n += nm1 nm1 = onn j += 1 End While Console.WriteLine() Console.WriteLine("Au to 256 digits:") Console.WriteLine(t) Console.WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t = DoOne(1, 256)) End Sub End Module
from itertools import count, islice from _pydecimal import getcontext, Decimal def metallic_ratio(b): m, n = 1, 1 while True: yield m, n m, n = m*b + n, m def stable(b, prec): def to_decimal(b): for m,n in metallic_ratio(b): yield Decimal(m)/Decimal(n) getcontext().prec = prec last = 0 for i,x in zip(count(), to_decimal(b)): if x == last: print(f'after {i} iterations:\n\t{x}') break last = x for b in range(4): coefs = [n for _,n in islice(metallic_ratio(b), 15)] print(f'\nb = {b}: {coefs}') stable(b, 32) print(f'\nb = 1 with 256 digits:') stable(1, 256)
Produce a functionally identical Python code for the snippet given in VB.
Imports BI = System.Numerics.BigInteger Module Module1 Function IntSqRoot(v As BI, res As BI) As BI REM res is the initial guess Dim term As BI = 0 Dim d As BI = 0 Dim dl As BI = 1 While dl <> d term = v / res res = (res + term) >> 1 dl = d d = term - res End While Return term End Function Function DoOne(b As Integer, digs As Integer) As String REM calculates result via square root, not iterations Dim s = b * b + 4 digs += 1 Dim g As BI = Math.Sqrt(s * Math.Pow(10, digs)) Dim bs = IntSqRoot(s * BI.Parse("1" + New String("0", digs << 1)), g) bs += b * BI.Parse("1" + New String("0", digs)) bs >>= 1 bs += 4 Dim st = bs.ToString digs -= 1 Return String.Format("{0}.{1}", st(0), st.Substring(1, digs)) End Function Function DivIt(a As BI, b As BI, digs As Integer) As String REM performs division Dim al = a.ToString.Length Dim bl = b.ToString.Length digs += 1 a *= BI.Pow(10, digs << 1) b *= BI.Pow(10, digs) Dim s = (a / b + 5).ToString digs -= 1 Return s(0) + "." + s.Substring(1, digs) End Function REM custom formatting Function Joined(x() As BI) As String Dim wids() = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13} Dim res = "" For i = 0 To x.Length - 1 res += String.Format("{0," + (-wids(i)).ToString + "} ", x(i)) Next Return res End Function Sub Main() REM calculates and checks each "metal" Console.WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc") Dim t = "" Dim n As BI Dim nm1 As BI Dim k As Integer Dim j As Integer For b = 0 To 9 Dim lst(14) As BI lst(0) = 1 lst(1) = 1 For i = 2 To 14 lst(i) = b * lst(i - 1) + lst(i - 2) Next REM since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15 n = lst(14) nm1 = lst(13) k = 0 j = 13 While k = 0 Dim lt = t t = DivIt(n, nm1, 32) If lt = t Then k = If(b = 0, 1, j) End If Dim onn = n n = b * n + nm1 nm1 = onn j += 1 End While Console.WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}" + vbNewLine + "{6,19} {7}", "Pt Au Ag CuSn Cu Ni Al Fe Sn Pb".Split(" ")(b), b, b * b + 4, k, t, t = DoOne(b, 32), "", Joined(lst)) Next REM now calculate and check big one n = 1 nm1 = 1 k = 0 j = 1 While k = 0 Dim lt = t t = DivIt(n, nm1, 256) If lt = t Then k = j End If Dim onn = n n += nm1 nm1 = onn j += 1 End While Console.WriteLine() Console.WriteLine("Au to 256 digits:") Console.WriteLine(t) Console.WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t = DoOne(1, 256)) End Sub End Module
from itertools import count, islice from _pydecimal import getcontext, Decimal def metallic_ratio(b): m, n = 1, 1 while True: yield m, n m, n = m*b + n, m def stable(b, prec): def to_decimal(b): for m,n in metallic_ratio(b): yield Decimal(m)/Decimal(n) getcontext().prec = prec last = 0 for i,x in zip(count(), to_decimal(b)): if x == last: print(f'after {i} iterations:\n\t{x}') break last = x for b in range(4): coefs = [n for _,n in islice(metallic_ratio(b), 15)] print(f'\nb = {b}: {coefs}') stable(b, 32) print(f'\nb = 1 with 256 digits:') stable(1, 256)
Transform the following VB implementation into Python, maintaining the same output and logic.
Class Branch Public from As Node Public towards As Node Public length As Integer Public distance As Integer Public key As String Class Node Public key As String Public correspondingBranch As Branch Const INFINITY = 32767 Private Sub Dijkstra(Nodes As Collection, Branches As Collection, P As Node, Optional Q As Node) Dim a As New Collection Dim b As New Collection Dim c As New Collection Dim I As New Collection Dim II As New Collection Dim III As New Collection Dim u As Node, R_ As Node, dist As Integer For Each n In Nodes c.Add n, n.key Next n For Each e In Branches III.Add e, e.key Next e a.Add P, P.key c.Remove P.key Set u = P Do For Each r In III If r.from Is u Then Set R_ = r.towards If Belongs(R_, c) Then c.Remove R_.key b.Add R_, R_.key Set R_.correspondingBranch = r If u.correspondingBranch Is Nothing Then R_.correspondingBranch.distance = r.length Else R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length End If III.Remove r.key II.Add r, r.key Else If Belongs(R_, b) Then If R_.correspondingBranch.distance > u.correspondingBranch.distance + r.length Then II.Remove R_.correspondingBranch.key II.Add r, r.key Set R_.correspondingBranch = r R_.correspondingBranch.distance = u.correspondingBranch.distance + r.length End If End If End If End If Next r dist = INFINITY Set u = Nothing For Each n In b If dist > n.correspondingBranch.distance Then dist = n.correspondingBranch.distance Set u = n End If Next n b.Remove u.key a.Add u, u.key II.Remove u.correspondingBranch.key I.Add u.correspondingBranch, u.correspondingBranch.key Loop Until IIf(Q Is Nothing, a.Count = Nodes.Count, u Is Q) If Not Q Is Nothing Then GetPath Q End Sub Private Function Belongs(n As Node, col As Collection) As Boolean Dim obj As Node On Error GoTo err Belongs = True Set obj = col(n.key) Exit Function err: Belongs = False End Function Private Sub GetPath(Target As Node) Dim path As String If Target.correspondingBranch Is Nothing Then path = "no path" Else path = Target.key Set u = Target Do While Not u.correspondingBranch Is Nothing path = u.correspondingBranch.from.key & " " & path Set u = u.correspondingBranch.from Loop Debug.Print u.key, Target.key, Target.correspondingBranch.distance, path End If End Sub Public Sub test() Dim a As New Node, b As New Node, c As New Node, d As New Node, e As New Node, f As New Node Dim ab As New Branch, ac As New Branch, af As New Branch, bc As New Branch, bd As New Branch Dim cd As New Branch, cf As New Branch, de As New Branch, ef As New Branch Set ab.from = a: Set ab.towards = b: ab.length = 7: ab.key = "ab": ab.distance = INFINITY Set ac.from = a: Set ac.towards = c: ac.length = 9: ac.key = "ac": ac.distance = INFINITY Set af.from = a: Set af.towards = f: af.length = 14: af.key = "af": af.distance = INFINITY Set bc.from = b: Set bc.towards = c: bc.length = 10: bc.key = "bc": bc.distance = INFINITY Set bd.from = b: Set bd.towards = d: bd.length = 15: bd.key = "bd": bd.distance = INFINITY Set cd.from = c: Set cd.towards = d: cd.length = 11: cd.key = "cd": cd.distance = INFINITY Set cf.from = c: Set cf.towards = f: cf.length = 2: cf.key = "cf": cf.distance = INFINITY Set de.from = d: Set de.towards = e: de.length = 6: de.key = "de": de.distance = INFINITY Set ef.from = e: Set ef.towards = f: ef.length = 9: ef.key = "ef": ef.distance = INFINITY a.key = "a" b.key = "b" c.key = "c" d.key = "d" e.key = "e" f.key = "f" Dim testNodes As New Collection Dim testBranches As New Collection testNodes.Add a, "a" testNodes.Add b, "b" testNodes.Add c, "c" testNodes.Add d, "d" testNodes.Add e, "e" testNodes.Add f, "f" testBranches.Add ab, "ab" testBranches.Add ac, "ac" testBranches.Add af, "af" testBranches.Add bc, "bc" testBranches.Add bd, "bd" testBranches.Add cd, "cd" testBranches.Add cf, "cf" testBranches.Add de, "de" testBranches.Add ef, "ef" Debug.Print "From", "To", "Distance", "Path" Dijkstra testNodes, testBranches, a, e Dijkstra testNodes, testBranches, a GetPath f End Sub
from collections import namedtuple, deque from pprint import pprint as pp inf = float('inf') Edge = namedtuple('Edge', ['start', 'end', 'cost']) class Graph(): def __init__(self, edges): self.edges = [Edge(*edge) for edge in edges] self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges} def dijkstra(self, source, dest): assert source in self.vertices dist = {vertex: inf for vertex in self.vertices} previous = {vertex: None for vertex in self.vertices} dist[source] = 0 q = self.vertices.copy() neighbours = {vertex: set() for vertex in self.vertices} for start, end, cost in self.edges: neighbours[start].add((end, cost)) neighbours[end].add((start, cost)) while q: u = min(q, key=lambda vertex: dist[vertex]) q.remove(u) if dist[u] == inf or u == dest: break for v, cost in neighbours[u]: alt = dist[u] + cost if alt < dist[v]: dist[v] = alt previous[v] = u s, u = deque(), dest while previous[u]: s.appendleft(u) u = previous[u] s.appendleft(u) return s graph = Graph([("a", "b", 7), ("a", "c", 9), ("a", "f", 14), ("b", "c", 10), ("b", "d", 15), ("c", "d", 11), ("c", "f", 2), ("d", "e", 6), ("e", "f", 9)]) pp(graph.dijkstra("a", "e"))
Convert this VB snippet to Python and keep its semantics consistent.
Option Strict On Imports System.Text Module Module1 Structure Vector Private ReadOnly dims() As Double Public Sub New(da() As Double) dims = da End Sub Public Shared Operator -(v As Vector) As Vector Return v * -1.0 End Operator Public Shared Operator +(lhs As Vector, rhs As Vector) As Vector Dim result(31) As Double Array.Copy(lhs.dims, 0, result, 0, lhs.Length) For i = 1 To result.Length Dim i2 = i - 1 result(i2) = lhs(i2) + rhs(i2) Next Return New Vector(result) End Operator Public Shared Operator *(lhs As Vector, rhs As Vector) As Vector Dim result(31) As Double For i = 1 To lhs.Length Dim i2 = i - 1 If lhs(i2) <> 0.0 Then For j = 1 To lhs.Length Dim j2 = j - 1 If rhs(j2) <> 0.0 Then Dim s = ReorderingSign(i2, j2) * lhs(i2) * rhs(j2) Dim k = i2 Xor j2 result(k) += s End If Next End If Next Return New Vector(result) End Operator Public Shared Operator *(v As Vector, scale As Double) As Vector Dim result = CType(v.dims.Clone, Double()) For i = 1 To result.Length Dim i2 = i - 1 result(i2) *= scale Next Return New Vector(result) End Operator Default Public Property Index(key As Integer) As Double Get Return dims(key) End Get Set(value As Double) dims(key) = value End Set End Property Public ReadOnly Property Length As Integer Get Return dims.Length End Get End Property Public Function Dot(rhs As Vector) As Vector Return (Me * rhs + rhs * Me) * 0.5 End Function Private Shared Function BitCount(i As Integer) As Integer i -= ((i >> 1) And &H55555555) i = (i And &H33333333) + ((i >> 2) And &H33333333) i = (i + (i >> 4)) And &HF0F0F0F i += (i >> 8) i += (i >> 16) Return i And &H3F End Function Private Shared Function ReorderingSign(i As Integer, j As Integer) As Double Dim k = i >> 1 Dim sum = 0 While k <> 0 sum += BitCount(k And j) k >>= 1 End While Return If((sum And 1) = 0, 1.0, -1.0) End Function Public Overrides Function ToString() As String Dim it = dims.GetEnumerator Dim sb As New StringBuilder("[") If it.MoveNext() Then sb.Append(it.Current) End If While it.MoveNext sb.Append(", ") sb.Append(it.Current) End While sb.Append("]") Return sb.ToString End Function End Structure Function DoubleArray(size As Integer) As Double() Dim result(size - 1) As Double For i = 1 To size Dim i2 = i - 1 result(i2) = 0.0 Next Return result End Function Function E(n As Integer) As Vector If n > 4 Then Throw New ArgumentException("n must be less than 5") End If Dim result As New Vector(DoubleArray(32)) result(1 << n) = 1.0 Return result End Function ReadOnly r As New Random() Function RandomVector() As Vector Dim result As New Vector(DoubleArray(32)) For i = 1 To 5 Dim i2 = i - 1 Dim singleton() As Double = {r.NextDouble()} result += New Vector(singleton) * E(i2) Next Return result End Function Function RandomMultiVector() As Vector Dim result As New Vector(DoubleArray(32)) For i = 1 To result.Length Dim i2 = i - 1 result(i2) = r.NextDouble() Next Return result End Function Sub Main() For i = 1 To 5 Dim i2 = i - 1 For j = 1 To 5 Dim j2 = j - 1 If i2 < j2 Then If E(i2).Dot(E(j2))(0) <> 0.0 Then Console.Error.WriteLine("Unexpected non-null scalar product") Return End If ElseIf i2 = j2 Then If E(i2).Dot(E(j2))(0) = 0.0 Then Console.Error.WriteLine("Unexpected null scalar product") Return End If End If Next Next Dim a = RandomMultiVector() Dim b = RandomMultiVector() Dim c = RandomMultiVector() Dim x = RandomVector() Console.WriteLine((a * b) * c) Console.WriteLine(a * (b * c)) Console.WriteLine() Console.WriteLine(a * (b + c)) Console.WriteLine(a * b + a * c) Console.WriteLine() Console.WriteLine((a + b) * c) Console.WriteLine(a * c + b * c) Console.WriteLine() Console.WriteLine(x * x) End Sub End Module
import copy, random def bitcount(n): return bin(n).count("1") def reoderingSign(i, j): k = i >> 1 sum = 0 while k != 0: sum += bitcount(k & j) k = k >> 1 return 1.0 if ((sum & 1) == 0) else -1.0 class Vector: def __init__(self, da): self.dims = da def dot(self, other): return (self * other + other * self) * 0.5 def __getitem__(self, i): return self.dims[i] def __setitem__(self, i, v): self.dims[i] = v def __neg__(self): return self * -1.0 def __add__(self, other): result = copy.copy(other.dims) for i in xrange(0, len(self.dims)): result[i] += self.dims[i] return Vector(result) def __mul__(self, other): if isinstance(other, Vector): result = [0.0] * 32 for i in xrange(0, len(self.dims)): if self.dims[i] != 0.0: for j in xrange(0, len(self.dims)): if other.dims[j] != 0.0: s = reoderingSign(i, j) * self.dims[i] * other.dims[j] k = i ^ j result[k] += s return Vector(result) else: result = copy.copy(self.dims) for i in xrange(0, len(self.dims)): self.dims[i] *= other return Vector(result) def __str__(self): return str(self.dims) def e(n): assert n <= 4, "n must be less than 5" result = Vector([0.0] * 32) result[1 << n] = 1.0 return result def randomVector(): result = Vector([0.0] * 32) for i in xrange(0, 5): result += Vector([random.uniform(0, 1)]) * e(i) return result def randomMultiVector(): result = Vector([0.0] * 32) for i in xrange(0, 32): result[i] = random.uniform(0, 1) return result def main(): for i in xrange(0, 5): for j in xrange(0, 5): if i < j: if e(i).dot(e(j))[0] != 0.0: print "Unexpected non-null scalar product" return elif i == j: if e(i).dot(e(j))[0] == 0.0: print "Unexpected non-null scalar product" a = randomMultiVector() b = randomMultiVector() c = randomMultiVector() x = randomVector() print (a * b) * c print a * (b * c) print print a * (b + c) print a * b + a * c print print (a + b) * c print a * c + b * c print print x * x main()
Convert this VB block to Python, preserving its control flow and logic.
Option Explicit Sub Test() Dim h As Object, i As Long, u, v, s Set h = CreateObject("Scripting.Dictionary") h.Add "A", 1 h.Add "B", 2 h.Add "C", 3 For Each s In h.Keys Debug.Print s Next For Each s In h.Items Debug.Print s Next u = h.Keys v = h.Items For i = 0 To h.Count - 1 Debug.Print u(i), v(i) Next End Sub
myDict = { "hello": 13, "world": 31, "!" : 71 } for key, value in myDict.items(): print ("key = %s, value = %s" % (key, value)) for key in myDict: print ("key = %s" % key) for key in myDict.keys(): print ("key = %s" % key) for value in myDict.values(): print ("value = %s" % value)
Please provide an equivalent version of this VB code in Python.
Private mvarValue As Integer Public Property Let Value(ByVal vData As Integer) If (vData > 10) Or (vData < 1) Then Error 380 Else mvarValue = vData End If End Property Public Property Get Value() As Integer Value = mvarValue End Property Private Sub Class_Initialize() mvarValue = 1 End Sub
>>> class num(int): def __init__(self, b): if 1 <= b <= 10: return int.__init__(self+0) else: raise ValueError,"Value %s should be >=0 and <= 10" % b >>> x = num(3) >>> x = num(11) Traceback (most recent call last): File "<pyshell x = num(11) File "<pyshell raise ValueError,"Value %s should be >=0 and <= 10" % b ValueError: Value 11 should be >=0 and <= 10 >>> x 3 >>> type(x) <class '__main__.num'> >>>
Change the programming language of this snippet from VB to Python without modifying what it does.
Dim t_age(4,1) t_age(0,0) = 27 : t_age(0,1) = "Jonah" t_age(1,0) = 18 : t_age(1,1) = "Alan" t_age(2,0) = 28 : t_age(2,1) = "Glory" t_age(3,0) = 18 : t_age(3,1) = "Popeye" t_age(4,0) = 28 : t_age(4,1) = "Alan" Dim t_nemesis(4,1) t_nemesis(0,0) = "Jonah" : t_nemesis(0,1) = "Whales" t_nemesis(1,0) = "Jonah" : t_nemesis(1,1) = "Spiders" t_nemesis(2,0) = "Alan" : t_nemesis(2,1) = "Ghosts" t_nemesis(3,0) = "Alan" : t_nemesis(3,1) = "Zombies" t_nemesis(4,0) = "Glory" : t_nemesis(4,1) = "Buffy" Call hash_join(t_age,1,t_nemesis,0) Sub hash_join(table_1,index_1,table_2,index_2) Set hash = CreateObject("Scripting.Dictionary") For i = 0 To UBound(table_1) hash.Add i,Array(table_1(i,0),table_1(i,1)) Next For j = 0 To UBound(table_2) For Each key In hash.Keys If hash(key)(index_1) = table_2(j,index_2) Then WScript.StdOut.WriteLine hash(key)(0) & "," & hash(key)(1) &_ " = " & table_2(j,0) & "," & table_2(j,1) End If Next Next End Sub
from collections import defaultdict def hashJoin(table1, index1, table2, index2): h = defaultdict(list) for s in table1: h[s[index1]].append(s) return [(s, r) for r in table2 for s in h[r[index2]]] table1 = [(27, "Jonah"), (18, "Alan"), (28, "Glory"), (18, "Popeye"), (28, "Alan")] table2 = [("Jonah", "Whales"), ("Jonah", "Spiders"), ("Alan", "Ghosts"), ("Alan", "Zombies"), ("Glory", "Buffy")] for row in hashJoin(table1, 1, table2, 0): print(row)
Rewrite the snippet below in Python so it works the same as the original VB code.
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 const raiz2=1.4142135623730950488016887242097 sub media_sierp (niv,sz) if niv=0 then x.fw sz: exit sub media_sierp niv-1,sz x.lt 1 x.fw sz*raiz2 x.lt 1 media_sierp niv-1,sz x.rt 2 x.fw sz x.rt 2 media_sierp niv-1,sz x.lt 1 x.fw sz*raiz2 x.lt 1 media_sierp niv-1,sz end sub sub sierp(niv,sz) media_sierp niv,sz x.rt 2 x.fw sz x.rt 2 media_sierp niv,sz x.rt 2 x.fw sz x.rt 2 end sub dim x set x=new turtle x.iangle=45 x.orient=0 x.incr=1 x.x=100:x.y=270 sierp 5,4 set x=nothing
import matplotlib.pyplot as plt import math def nextPoint(x, y, angle): a = math.pi * angle / 180 x2 = (int)(round(x + (1 * math.cos(a)))) y2 = (int)(round(y + (1 * math.sin(a)))) return x2, y2 def expand(axiom, rules, level): for l in range(0, level): a2 = "" for c in axiom: if c in rules: a2 += rules[c] else: a2 += c axiom = a2 return axiom def draw_lsystem(axiom, rules, angle, iterations): xp = [1] yp = [1] direction = 0 for c in expand(axiom, rules, iterations): if c == "F": xn, yn = nextPoint(xp[-1], yp[-1], direction) xp.append(xn) yp.append(yn) elif c == "-": direction = direction - angle if direction < 0: direction = 360 + direction elif c == "+": direction = (direction + angle) % 360 plt.plot(xp, yp) plt.show() if __name__ == '__main__': s_axiom = "F+XF+F+XF" s_rules = {"X": "XF-F+F-XF+F+XF-F+F-X"} s_angle = 90 draw_lsystem(s_axiom, s_rules, s_angle, 3)
Write a version of this VB function in Python with identical behavior.
with createobject("ADODB.Stream") .charset ="UTF-8" .open .loadfromfile("unixdict.txt") s=.readtext end with a=split (s,vblf) set d= createobject("Scripting.Dictionary") for each aa in a x=trim(aa) l=len(x) if l>5 then d.removeall for i=1 to 3 m=mid(x,i,1) if not d.exists(m) then d.add m,null next res=true for i=l-2 to l m=mid(x,i,1) if not d.exists(m) then res=false:exit for else d.remove(m) end if next if res then wscript.stdout.write left(x & space(15),15) if left(x,3)=right(x,3) then wscript.stdout.write "*" wscript.stdout.writeline end if end if next
import urllib.request 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() for word in wordList: if len(word)>5 and word[:3].lower()==word[-3:].lower(): print(word)
Port the provided VB code into Python while preserving the original functionality.
Module Module1 Structure Node Private ReadOnly m_val As String Private ReadOnly m_parsed As List(Of String) Sub New(initial As String) m_val = initial m_parsed = New List(Of String) End Sub Sub New(s As String, p As List(Of String)) m_val = s m_parsed = p End Sub Public Function Value() As String Return m_val End Function Public Function Parsed() As List(Of String) Return m_parsed End Function End Structure Function WordBreak(s As String, dictionary As List(Of String)) As List(Of List(Of String)) Dim matches As New List(Of List(Of String)) Dim q As New Queue(Of Node) q.Enqueue(New Node(s)) While q.Count > 0 Dim node = q.Dequeue() REM check if fully parsed If node.Value.Length = 0 Then matches.Add(node.Parsed) Else For Each word In dictionary REM check for match If node.Value.StartsWith(word) Then Dim valNew = node.Value.Substring(word.Length, node.Value.Length - word.Length) Dim parsedNew As New List(Of String) parsedNew.AddRange(node.Parsed) parsedNew.Add(word) q.Enqueue(New Node(valNew, parsedNew)) End If Next End If End While Return matches End Function Sub Main() Dim dict As New List(Of String) From {"a", "aa", "b", "ab", "aab"} For Each testString In {"aab", "aa b"} Dim matches = WordBreak(testString, dict) Console.WriteLine("String = {0}, Dictionary = {1}. Solutions = {2}", testString, dict, matches.Count) For Each match In matches Console.WriteLine(" Word Break = [{0}]", String.Join(", ", match)) Next Console.WriteLine() Next dict = New List(Of String) From {"abc", "a", "ac", "b", "c", "cb", "d"} For Each testString In {"abcd", "abbc", "abcbcd", "acdbc", "abcdd"} Dim matches = WordBreak(testString, dict) Console.WriteLine("String = {0}, Dictionary = {1}. Solutions = {2}", testString, dict, matches.Count) For Each match In matches Console.WriteLine(" Word Break = [{0}]", String.Join(", ", match)) Next Console.WriteLine() Next End Sub End Module
from itertools import (chain) def stringParse(lexicon): return lambda s: Node(s)( tokenTrees(lexicon)(s) ) def tokenTrees(wds): def go(s): return [Node(s)([])] if s in wds else ( concatMap(nxt(s))(wds) ) def nxt(s): return lambda w: parse( w, go(s[len(w):]) ) if s.startswith(w) else [] def parse(w, xs): return [Node(w)(xs)] if xs else xs return lambda s: go(s) def showParse(tree): def showTokens(x): xs = x['nest'] return ' ' + x['root'] + (showTokens(xs[0]) if xs else '') parses = tree['nest'] return tree['root'] + ':\n' + ( '\n'.join( map(showTokens, parses) ) if parses else ' ( Not parseable in terms of these words )' ) def main(): lexicon = 'a bc abc cd b'.split() testSamples = 'abcd abbc abcbcd acdbc abcdd'.split() print(unlines( map( showParse, map( stringParse(lexicon), testSamples ) ) )) def Node(v): return lambda xs: {'type': 'Node', 'root': v, 'nest': xs} def concatMap(f): return lambda xs: list( chain.from_iterable(map(f, xs)) ) def unlines(xs): return '\n'.join(xs) if __name__ == '__main__': main()
Convert this VB snippet to Python and keep its semantics consistent.
Option Strict On Imports Matrix = System.Collections.Generic.List(Of System.Collections.Generic.List(Of Integer)) Module Module1 Sub Swap(Of T)(ByRef a As T, ByRef b As T) Dim u = a a = b b = u End Sub Sub PrintSquare(latin As Matrix) For Each row In latin Dim it = row.GetEnumerator Console.Write("[") If it.MoveNext Then Console.Write(it.Current) End If While it.MoveNext Console.Write(", ") Console.Write(it.Current) End While Console.WriteLine("]") Next Console.WriteLine() End Sub Function DList(n As Integer, start As Integer) As Matrix start -= 1 REM use 0 based indexes Dim a = Enumerable.Range(0, n).ToArray a(start) = a(0) a(0) = start Array.Sort(a, 1, a.Length - 1) Dim first = a(1) REM recursive closure permutes a[1:] Dim r As New Matrix Dim Recurse As Action(Of Integer) = Sub(last As Integer) If last = first Then REM bottom of recursion. you get here once for each permutation REM test if permutation is deranged. For j = 1 To a.Length - 1 Dim v = a(j) If j = v Then Return REM no, ignore it End If Next REM yes, save a copy with 1 based indexing Dim b = a.Select(Function(v) v + 1).ToArray r.Add(b.ToList) Return End If For i = last To 1 Step -1 Swap(a(i), a(last)) Recurse(last - 1) Swap(a(i), a(last)) Next End Sub Recurse(n - 1) Return r End Function Function ReducedLatinSquares(n As Integer, echo As Boolean) As ULong If n <= 0 Then If echo Then Console.WriteLine("[]") Console.WriteLine() End If Return 0 End If If n = 1 Then If echo Then Console.WriteLine("[1]") Console.WriteLine() End If Return 1 End If Dim rlatin As New Matrix For i = 0 To n - 1 rlatin.Add(New List(Of Integer)) For j = 0 To n - 1 rlatin(i).Add(0) Next Next REM first row For j = 0 To n - 1 rlatin(0)(j) = j + 1 Next Dim count As ULong = 0 Dim Recurse As Action(Of Integer) = Sub(i As Integer) Dim rows = DList(n, i) For r = 0 To rows.Count - 1 rlatin(i - 1) = rows(r) For k = 0 To i - 2 For j = 1 To n - 1 If rlatin(k)(j) = rlatin(i - 1)(j) Then If r < rows.Count - 1 Then GoTo outer End If If i > 2 Then Return End If End If Next Next If i < n Then Recurse(i + 1) Else count += 1UL If echo Then PrintSquare(rlatin) End If End If outer: While False REM empty End While Next End Sub REM remiain rows Recurse(2) Return count End Function Function Factorial(n As ULong) As ULong If n <= 0 Then Return 1 End If Dim prod = 1UL For i = 2UL To n prod *= i Next Return prod End Function Sub Main() Console.WriteLine("The four reduced latin squares of order 4 are:") Console.WriteLine() ReducedLatinSquares(4, True) Console.WriteLine("The size of the set of reduced latin squares for the following orders") Console.WriteLine("and hence the total number of latin squares of these orders are:") Console.WriteLine() For n = 1 To 6 Dim nu As ULong = CULng(n) Dim size = ReducedLatinSquares(n, False) Dim f = Factorial(nu - 1UL) f *= f * nu * size Console.WriteLine("Order {0}: Size {1} x {2}! x {3}! => Total {4}", n, size, n, n - 1, f) Next End Sub End Module
def dList(n, start): start -= 1 a = range(n) a[start] = a[0] a[0] = start a[1:] = sorted(a[1:]) first = a[1] r = [] def recurse(last): if (last == first): for j,v in enumerate(a[1:]): if j + 1 == v: return b = [x + 1 for x in a] r.append(b) return for i in xrange(last, 0, -1): a[i], a[last] = a[last], a[i] recurse(last - 1) a[i], a[last] = a[last], a[i] recurse(n - 1) return r def printSquare(latin,n): for row in latin: print row print def reducedLatinSquares(n,echo): if n <= 0: if echo: print [] return 0 elif n == 1: if echo: print [1] return 1 rlatin = [None] * n for i in xrange(n): rlatin[i] = [None] * n for j in xrange(0, n): rlatin[0][j] = j + 1 class OuterScope: count = 0 def recurse(i): rows = dList(n, i) for r in xrange(len(rows)): rlatin[i - 1] = rows[r] justContinue = False k = 0 while not justContinue and k < i - 1: for j in xrange(1, n): if rlatin[k][j] == rlatin[i - 1][j]: if r < len(rows) - 1: justContinue = True break if i > 2: return k += 1 if not justContinue: if i < n: recurse(i + 1) else: OuterScope.count += 1 if echo: printSquare(rlatin, n) recurse(2) return OuterScope.count def factorial(n): if n == 0: return 1 prod = 1 for i in xrange(2, n + 1): prod *= i return prod print "The four reduced latin squares of order 4 are:\n" reducedLatinSquares(4,True) print "The size of the set of reduced latin squares for the following orders" print "and hence the total number of latin squares of these orders are:\n" for n in xrange(1, 7): size = reducedLatinSquares(n, False) f = factorial(n - 1) f *= f * n * size print "Order %d: Size %-4d x %d! x %d! => Total %d" % (n, size, n, n - 1, f)
Produce a language-to-language conversion: from VB to Python, same semantics.
Option Explicit Const m_limit ="# #" Const m_middle=" # # " Dim a,bnum,i,check,odic a=array(" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",_ " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",_ " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",_ " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",_ " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",_ " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",_ " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",_ " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",_ " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",_ " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ") bnum=Array("0001101","0011001","0010011","0111101","0100011"," 0110001","0101111","0111011","0110111","0001011") Set oDic = WScript.CreateObject("scripting.dictionary") For i=0 To 9: odic.Add bin2dec(bnum(i),Asc("1")),i+1 odic.Add bin2dec(bnum(i),Asc("0")),-i-1 Next For i=0 To UBound(a) : print pad(i+1,-2) & ": "& upc(a(i)) :Next WScript.Quit(1) Function bin2dec(ByVal B,a) Dim n While len(b) n =n *2 - (asc(b)=a) b=mid(b,2) Wend bin2dec= n And 127 End Function Sub print(s): On Error Resume Next WScript.stdout.WriteLine (s) If err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit End Sub function pad(s,n) if n<0 then pad= right(space(-n) & s ,-n) else pad= left(s& space(n),n) end if :end function Function iif(t,a,b) If t Then iif=a Else iif=b End If :End Function Function getnum(s,r) Dim n,s1,r1 s1=Left(s,7) s=Mid(s,8) r1=r Do If r Then s1=StrReverse(s1) n=bin2dec(s1,asc("#")) If odic.exists(n) Then getnum=odic(n) Exit Function Else If r1<>r Then getnum=0:Exit Function r=Not r End If Loop End Function Function getmarker(s,m) getmarker= (InStr(s,m)= 1) s=Mid(s,Len(m)+1) End Function Function checksum(ByVal s) Dim n,i : n=0 do n=n+(Asc(s)-48)*3 s=Mid(s,2) n=n+(Asc(s)-48)*1 s=Mid(s,2) Loop until Len(s)=0 checksum= ((n mod 10)=0) End function Function upc(ByVal s1) Dim i,n,s,out,rev,j s=Trim(s1) If getmarker(s,m_limit)=False Then upc= "bad start marker ":Exit function rev=False out="" For j= 0 To 1 For i=0 To 5 n=getnum(s,rev) If n=0 Then upc= pad(out,16) & pad ("bad code",-10) & pad("pos "& i+j*6+1,-11): Exit Function out=out & Abs(n)-1 Next If j=0 Then If getmarker(s,m_middle)=False Then upc= "bad middle marker " & out :Exit Function Next If getmarker(s,m_limit)=False Then upc= "bad end marker " :Exit function If rev Then out=strreverse(out) upc= pad(out,16) & pad(iif (checksum(out),"valid","not valid"),-10)& pad(iif(rev,"reversed",""),-11) End Function
import itertools import re RE_BARCODE = re.compile( r"^(?P<s_quiet> +)" r"(?P<s_guard> r"(?P<left>[ r"(?P<m_guard> r"(?P<right>[ r"(?P<e_guard> r"(?P<e_quiet> +)$" ) LEFT_DIGITS = { (0, 0, 0, 1, 1, 0, 1): 0, (0, 0, 1, 1, 0, 0, 1): 1, (0, 0, 1, 0, 0, 1, 1): 2, (0, 1, 1, 1, 1, 0, 1): 3, (0, 1, 0, 0, 0, 1, 1): 4, (0, 1, 1, 0, 0, 0, 1): 5, (0, 1, 0, 1, 1, 1, 1): 6, (0, 1, 1, 1, 0, 1, 1): 7, (0, 1, 1, 0, 1, 1, 1): 8, (0, 0, 0, 1, 0, 1, 1): 9, } RIGHT_DIGITS = { (1, 1, 1, 0, 0, 1, 0): 0, (1, 1, 0, 0, 1, 1, 0): 1, (1, 1, 0, 1, 1, 0, 0): 2, (1, 0, 0, 0, 0, 1, 0): 3, (1, 0, 1, 1, 1, 0, 0): 4, (1, 0, 0, 1, 1, 1, 0): 5, (1, 0, 1, 0, 0, 0, 0): 6, (1, 0, 0, 0, 1, 0, 0): 7, (1, 0, 0, 1, 0, 0, 0): 8, (1, 1, 1, 0, 1, 0, 0): 9, } MODULES = { " ": 0, " } DIGITS_PER_SIDE = 6 MODULES_PER_DIGIT = 7 class ParityError(Exception): class ChecksumError(Exception): def group(iterable, n): args = [iter(iterable)] * n return tuple(itertools.zip_longest(*args)) def parse(barcode): match = RE_BARCODE.match(barcode) left = group((MODULES[c] for c in match.group("left")), MODULES_PER_DIGIT) right = group((MODULES[c] for c in match.group("right")), MODULES_PER_DIGIT) left, right = check_parity(left, right) return tuple( itertools.chain( (LEFT_DIGITS[d] for d in left), (RIGHT_DIGITS[d] for d in right), ) ) def check_parity(left, right): left_parity = sum(sum(d) % 2 for d in left) right_parity = sum(sum(d) % 2 for d in right) if left_parity == 0 and right_parity == DIGITS_PER_SIDE: _left = tuple(tuple(reversed(d)) for d in reversed(right)) right = tuple(tuple(reversed(d)) for d in reversed(left)) left = _left elif left_parity != DIGITS_PER_SIDE or right_parity != 0: error = tuple( itertools.chain( (LEFT_DIGITS.get(d, "_") for d in left), (RIGHT_DIGITS.get(d, "_") for d in right), ) ) raise ParityError(" ".join(str(d) for d in error)) return left, right def checksum(digits): odds = (digits[i] for i in range(0, 11, 2)) evens = (digits[i] for i in range(1, 10, 2)) check_digit = (sum(odds) * 3 + sum(evens)) % 10 if check_digit != 0: check_digit = 10 - check_digit if digits[-1] != check_digit: raise ChecksumError(str(check_digit)) return check_digit def main(): barcodes = [ " " " " " " " " " " " ] for barcode in barcodes: try: digits = parse(barcode) except ParityError as err: print(f"{err} parity error!") continue try: check_digit = checksum(digits) except ChecksumError as err: print(f"{' '.join(str(d) for d in digits)} checksum error! ({err})") continue print(f"{' '.join(str(d) for d in digits)}") if __name__ == "__main__": main()
Generate an equivalent Python version of this VB code.
Option Explicit Private Type Adress Row As Integer Column As Integer End Type Private myTable() As String Sub Main() Dim keyw As String, boolQ As Boolean, text As String, test As Long Dim res As String keyw = InputBox("Enter your keyword : ", "KeyWord", "Playfair example") If keyw = "" Then GoTo ErrorHand Debug.Print "Enter your keyword : " & keyw boolQ = MsgBox("Ignore Q when buiding table y/n : ", vbYesNo) = vbYes Debug.Print "Ignore Q when buiding table y/n : " & IIf(boolQ, "Y", "N") Debug.Print "" Debug.Print "Table : " myTable = CreateTable(keyw, boolQ) On Error GoTo ErrorHand test = UBound(myTable) On Error GoTo 0 text = InputBox("Enter your text", "Encode", "hide the gold in the TRRE stump") If text = "" Then GoTo ErrorHand Debug.Print "" Debug.Print "Text to encode : " & text Debug.Print "-------------------------------------------------" res = Encode(text) Debug.Print "Encoded text is : " & res res = Decode(res) Debug.Print "Decoded text is : " & res text = InputBox("Enter your text", "Encode", "hide the gold in the TREE stump") If text = "" Then GoTo ErrorHand Debug.Print "" Debug.Print "Text to encode : " & text Debug.Print "-------------------------------------------------" res = Encode(text) Debug.Print "Encoded text is : " & res res = Decode(res) Debug.Print "Decoded text is : " & res Exit Sub ErrorHand: Debug.Print "error" End Sub Private Function CreateTable(strKeyword As String, Q As Boolean) As String() Dim r As Integer, c As Integer, temp(1 To 5, 1 To 5) As String, t, cpt As Integer Dim strT As String, coll As New Collection Dim s As String strKeyword = UCase(Replace(strKeyword, " ", "")) If Q Then If InStr(strKeyword, "J") > 0 Then Debug.Print "Your keyword isn Exit Function End If Else If InStr(strKeyword, "Q") > 0 Then Debug.Print "Your keyword isn Exit Function End If End If strT = IIf(Not Q, "ABCDEFGHIKLMNOPQRSTUVWXYZ", "ABCDEFGHIJKLMNOPRSTUVWXYZ") t = Split(StrConv(strKeyword, vbUnicode), Chr(0)) For c = LBound(t) To UBound(t) - 1 strT = Replace(strT, t(c), "") On Error Resume Next coll.Add t(c), t(c) On Error GoTo 0 Next strKeyword = vbNullString For c = 1 To coll.Count strKeyword = strKeyword & coll(c) Next t = Split(StrConv(strKeyword & strT, vbUnicode), Chr(0)) c = 1: r = 1 For cpt = LBound(t) To UBound(t) - 1 temp(r, c) = t(cpt) s = s & " " & t(cpt) c = c + 1 If c = 6 Then c = 1: r = r + 1: Debug.Print " " & s: s = "" Next CreateTable = temp End Function Private Function Encode(s As String) As String Dim i&, t() As String, cpt& s = UCase(Replace(s, " ", "")) For i = 1 To Len(s) - 1 If Mid(s, i, 1) = Mid(s, i + 1, 1) Then s = Left(s, i) & "X" & Right(s, Len(s) - i) Next For i = 1 To Len(s) Step 2 ReDim Preserve t(cpt) t(cpt) = Mid(s, i, 2) cpt = cpt + 1 Next i If Len(t(UBound(t))) = 1 Then t(UBound(t)) = t(UBound(t)) & "X" Debug.Print "[the pairs : " & Join(t, " ") & "]" For i = LBound(t) To UBound(t) t(i) = SwapPairsEncoding(t(i)) Next Encode = Join(t, " ") End Function Private Function SwapPairsEncoding(s As String) As String Dim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean Dim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress d1 = Left(s, 1): d2 = Right(s, 1) For r = 1 To 5 For c = 1 To 5 If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For Next If Flag Then Exit For Next Select Case True Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column resD1.Column = IIf(addD1.Column + 1 = 6, 1, addD1.Column + 1) resD2.Column = IIf(addD2.Column + 1 = 6, 1, addD2.Column + 1) SwapPairsEncoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column) Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column resD1.Row = IIf(addD1.Row + 1 = 6, 1, addD1.Row + 1) resD2.Row = IIf(addD2.Row + 1 = 6, 1, addD2.Row + 1) SwapPairsEncoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column) Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column resD1.Row = addD1.Row resD2.Row = addD2.Row resD1.Column = addD2.Column resD2.Column = addD1.Column SwapPairsEncoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column) End Select End Function Private Function Decode(s As String) As String Dim t, i&, j&, e& t = Split(s, " ") e = UBound(t) - 1 For i = LBound(t) To UBound(t) t(i) = SwapPairsDecoding(CStr(t(i))) Next For i = LBound(t) To e If Right(t(i), 1) = "X" And Left(t(i), 1) = Left(t(i + 1), 1) Then t(i) = Left(t(i), 1) & Left(t(i + 1), 1) For j = i + 1 To UBound(t) - 1 t(j) = Right(t(j), 1) & Left(t(j + 1), 1) Next j If Right(t(j), 1) = "X" Then ReDim Preserve t(j - 1) Else t(j) = Right(t(j), 1) & "X" End If ElseIf Left(t(i + 1), 1) = "X" And Right(t(i), 1) = Right(t(i + 1), 1) Then For j = i + 1 To UBound(t) - 1 t(j) = Right(t(j), 1) & Left(t(j + 1), 1) Next j If Right(t(j), 1) = "X" Then ReDim Preserve t(j - 1) Else t(j) = Right(t(j), 1) & "X" End If End If Next Decode = Join(t, " ") End Function Private Function SwapPairsDecoding(s As String) As String Dim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean Dim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress d1 = Left(s, 1): d2 = Right(s, 1) For r = 1 To 5 For c = 1 To 5 If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For Next If Flag Then Exit For Next Select Case True Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column resD1.Column = IIf(addD1.Column - 1 = 0, 5, addD1.Column - 1) resD2.Column = IIf(addD2.Column - 1 = 0, 5, addD2.Column - 1) SwapPairsDecoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column) Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column resD1.Row = IIf(addD1.Row - 1 = 0, 5, addD1.Row - 1) resD2.Row = IIf(addD2.Row - 1 = 0, 5, addD2.Row - 1) SwapPairsDecoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column) Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column resD1.Row = addD1.Row resD2.Row = addD2.Row resD1.Column = addD2.Column resD2.Column = addD1.Column SwapPairsDecoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column) End Select End Function
from string import ascii_uppercase from itertools import product from re import findall def uniq(seq): seen = {} return [seen.setdefault(x, x) for x in seq if x not in seen] def partition(seq, n): return [seq[i : i + n] for i in xrange(0, len(seq), n)] def playfair(key, from_ = 'J', to = None): if to is None: to = 'I' if from_ == 'J' else '' def canonicalize(s): return filter(str.isupper, s.upper()).replace(from_, to) m = partition(uniq(canonicalize(key + ascii_uppercase)), 5) enc = {} for row in m: for i, j in product(xrange(5), repeat=2): if i != j: enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5] for c in zip(*m): for i, j in product(xrange(5), repeat=2): if i != j: enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5] for i1, j1, i2, j2 in product(xrange(5), repeat=4): if i1 != i2 and j1 != j2: enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1] dec = dict((v, k) for k, v in enc.iteritems()) def sub_enc(txt): lst = findall(r"(.)(?:(?!\1)(.))?", canonicalize(txt)) return " ".join(enc[a + (b if b else 'X')] for a, b in lst) def sub_dec(encoded): return " ".join(dec[p] for p in partition(canonicalize(encoded), 2)) return sub_enc, sub_dec (encode, decode) = playfair("Playfair example") orig = "Hide the gold in...the TREESTUMP!!!" print "Original:", orig enc = encode(orig) print "Encoded:", enc print "Decoded:", decode(enc)
Translate the given VB code snippet into Python without altering its behavior.
Option Explicit Private Type Adress Row As Integer Column As Integer End Type Private myTable() As String Sub Main() Dim keyw As String, boolQ As Boolean, text As String, test As Long Dim res As String keyw = InputBox("Enter your keyword : ", "KeyWord", "Playfair example") If keyw = "" Then GoTo ErrorHand Debug.Print "Enter your keyword : " & keyw boolQ = MsgBox("Ignore Q when buiding table y/n : ", vbYesNo) = vbYes Debug.Print "Ignore Q when buiding table y/n : " & IIf(boolQ, "Y", "N") Debug.Print "" Debug.Print "Table : " myTable = CreateTable(keyw, boolQ) On Error GoTo ErrorHand test = UBound(myTable) On Error GoTo 0 text = InputBox("Enter your text", "Encode", "hide the gold in the TRRE stump") If text = "" Then GoTo ErrorHand Debug.Print "" Debug.Print "Text to encode : " & text Debug.Print "-------------------------------------------------" res = Encode(text) Debug.Print "Encoded text is : " & res res = Decode(res) Debug.Print "Decoded text is : " & res text = InputBox("Enter your text", "Encode", "hide the gold in the TREE stump") If text = "" Then GoTo ErrorHand Debug.Print "" Debug.Print "Text to encode : " & text Debug.Print "-------------------------------------------------" res = Encode(text) Debug.Print "Encoded text is : " & res res = Decode(res) Debug.Print "Decoded text is : " & res Exit Sub ErrorHand: Debug.Print "error" End Sub Private Function CreateTable(strKeyword As String, Q As Boolean) As String() Dim r As Integer, c As Integer, temp(1 To 5, 1 To 5) As String, t, cpt As Integer Dim strT As String, coll As New Collection Dim s As String strKeyword = UCase(Replace(strKeyword, " ", "")) If Q Then If InStr(strKeyword, "J") > 0 Then Debug.Print "Your keyword isn Exit Function End If Else If InStr(strKeyword, "Q") > 0 Then Debug.Print "Your keyword isn Exit Function End If End If strT = IIf(Not Q, "ABCDEFGHIKLMNOPQRSTUVWXYZ", "ABCDEFGHIJKLMNOPRSTUVWXYZ") t = Split(StrConv(strKeyword, vbUnicode), Chr(0)) For c = LBound(t) To UBound(t) - 1 strT = Replace(strT, t(c), "") On Error Resume Next coll.Add t(c), t(c) On Error GoTo 0 Next strKeyword = vbNullString For c = 1 To coll.Count strKeyword = strKeyword & coll(c) Next t = Split(StrConv(strKeyword & strT, vbUnicode), Chr(0)) c = 1: r = 1 For cpt = LBound(t) To UBound(t) - 1 temp(r, c) = t(cpt) s = s & " " & t(cpt) c = c + 1 If c = 6 Then c = 1: r = r + 1: Debug.Print " " & s: s = "" Next CreateTable = temp End Function Private Function Encode(s As String) As String Dim i&, t() As String, cpt& s = UCase(Replace(s, " ", "")) For i = 1 To Len(s) - 1 If Mid(s, i, 1) = Mid(s, i + 1, 1) Then s = Left(s, i) & "X" & Right(s, Len(s) - i) Next For i = 1 To Len(s) Step 2 ReDim Preserve t(cpt) t(cpt) = Mid(s, i, 2) cpt = cpt + 1 Next i If Len(t(UBound(t))) = 1 Then t(UBound(t)) = t(UBound(t)) & "X" Debug.Print "[the pairs : " & Join(t, " ") & "]" For i = LBound(t) To UBound(t) t(i) = SwapPairsEncoding(t(i)) Next Encode = Join(t, " ") End Function Private Function SwapPairsEncoding(s As String) As String Dim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean Dim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress d1 = Left(s, 1): d2 = Right(s, 1) For r = 1 To 5 For c = 1 To 5 If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For Next If Flag Then Exit For Next Select Case True Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column resD1.Column = IIf(addD1.Column + 1 = 6, 1, addD1.Column + 1) resD2.Column = IIf(addD2.Column + 1 = 6, 1, addD2.Column + 1) SwapPairsEncoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column) Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column resD1.Row = IIf(addD1.Row + 1 = 6, 1, addD1.Row + 1) resD2.Row = IIf(addD2.Row + 1 = 6, 1, addD2.Row + 1) SwapPairsEncoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column) Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column resD1.Row = addD1.Row resD2.Row = addD2.Row resD1.Column = addD2.Column resD2.Column = addD1.Column SwapPairsEncoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column) End Select End Function Private Function Decode(s As String) As String Dim t, i&, j&, e& t = Split(s, " ") e = UBound(t) - 1 For i = LBound(t) To UBound(t) t(i) = SwapPairsDecoding(CStr(t(i))) Next For i = LBound(t) To e If Right(t(i), 1) = "X" And Left(t(i), 1) = Left(t(i + 1), 1) Then t(i) = Left(t(i), 1) & Left(t(i + 1), 1) For j = i + 1 To UBound(t) - 1 t(j) = Right(t(j), 1) & Left(t(j + 1), 1) Next j If Right(t(j), 1) = "X" Then ReDim Preserve t(j - 1) Else t(j) = Right(t(j), 1) & "X" End If ElseIf Left(t(i + 1), 1) = "X" And Right(t(i), 1) = Right(t(i + 1), 1) Then For j = i + 1 To UBound(t) - 1 t(j) = Right(t(j), 1) & Left(t(j + 1), 1) Next j If Right(t(j), 1) = "X" Then ReDim Preserve t(j - 1) Else t(j) = Right(t(j), 1) & "X" End If End If Next Decode = Join(t, " ") End Function Private Function SwapPairsDecoding(s As String) As String Dim r As Integer, c As Integer, d1 As String, d2 As String, Flag As Boolean Dim addD1 As Adress, addD2 As Adress, resD1 As Adress, resD2 As Adress d1 = Left(s, 1): d2 = Right(s, 1) For r = 1 To 5 For c = 1 To 5 If d1 = myTable(r, c) Then addD1.Row = r: addD1.Column = c If d2 = myTable(r, c) Then addD2.Row = r: addD2.Column = c If addD1.Row <> 0 And addD2.Row <> 0 Then Flag = True: Exit For Next If Flag Then Exit For Next Select Case True Case addD1.Row = addD2.Row And addD1.Column <> addD2.Column resD1.Column = IIf(addD1.Column - 1 = 0, 5, addD1.Column - 1) resD2.Column = IIf(addD2.Column - 1 = 0, 5, addD2.Column - 1) SwapPairsDecoding = myTable(addD1.Row, resD1.Column) & myTable(addD2.Row, resD2.Column) Case addD1.Row <> addD2.Row And addD1.Column = addD2.Column resD1.Row = IIf(addD1.Row - 1 = 0, 5, addD1.Row - 1) resD2.Row = IIf(addD2.Row - 1 = 0, 5, addD2.Row - 1) SwapPairsDecoding = myTable(resD1.Row, addD1.Column) & myTable(resD2.Row, addD2.Column) Case addD1.Row <> addD2.Row And addD1.Column <> addD2.Column resD1.Row = addD1.Row resD2.Row = addD2.Row resD1.Column = addD2.Column resD2.Column = addD1.Column SwapPairsDecoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column) End Select End Function
from string import ascii_uppercase from itertools import product from re import findall def uniq(seq): seen = {} return [seen.setdefault(x, x) for x in seq if x not in seen] def partition(seq, n): return [seq[i : i + n] for i in xrange(0, len(seq), n)] def playfair(key, from_ = 'J', to = None): if to is None: to = 'I' if from_ == 'J' else '' def canonicalize(s): return filter(str.isupper, s.upper()).replace(from_, to) m = partition(uniq(canonicalize(key + ascii_uppercase)), 5) enc = {} for row in m: for i, j in product(xrange(5), repeat=2): if i != j: enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5] for c in zip(*m): for i, j in product(xrange(5), repeat=2): if i != j: enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5] for i1, j1, i2, j2 in product(xrange(5), repeat=4): if i1 != i2 and j1 != j2: enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1] dec = dict((v, k) for k, v in enc.iteritems()) def sub_enc(txt): lst = findall(r"(.)(?:(?!\1)(.))?", canonicalize(txt)) return " ".join(enc[a + (b if b else 'X')] for a, b in lst) def sub_dec(encoded): return " ".join(dec[p] for p in partition(canonicalize(encoded), 2)) return sub_enc, sub_dec (encode, decode) = playfair("Playfair example") orig = "Hide the gold in...the TREESTUMP!!!" print "Original:", orig enc = encode(orig) print "Encoded:", enc print "Decoded:", decode(enc)
Please provide an equivalent version of this VB code in Python.
Option Explicit Private Type MyPoint X As Single Y As Single End Type Private Type MyPair p1 As MyPoint p2 As MyPoint End Type Sub Main() Dim points() As MyPoint, i As Long, BF As MyPair, d As Single, Nb As Long Dim T# Randomize Timer Nb = 10 Do ReDim points(1 To Nb) For i = 1 To Nb points(i).X = Rnd * Nb points(i).Y = Rnd * Nb Next d = 1000000000000# T = Timer BF = BruteForce(points, d) Debug.Print "For " & Nb & " points, runtime : " & Timer - T & " sec." Debug.Print "point 1 : X:" & BF.p1.X & " Y:" & BF.p1.Y Debug.Print "point 2 : X:" & BF.p2.X & " Y:" & BF.p2.Y Debug.Print "dist : " & d Debug.Print "--------------------------------------------------" Nb = Nb * 10 Loop While Nb <= 10000 End Sub Private Function BruteForce(p() As MyPoint, mindist As Single) As MyPair Dim i As Long, j As Long, d As Single, ClosestPair As MyPair For i = 1 To UBound(p) - 1 For j = i + 1 To UBound(p) d = Dist(p(i), p(j)) If d < mindist Then mindist = d ClosestPair.p1 = p(i) ClosestPair.p2 = p(j) End If Next Next BruteForce = ClosestPair End Function Private Function Dist(p1 As MyPoint, p2 As MyPoint) As Single Dist = Sqr((p1.X - p2.X) ^ 2 + (p1.Y - p2.Y) ^ 2) End Function
from random import randint, randrange from operator import itemgetter, attrgetter infinity = float('inf') def bruteForceClosestPair(point): numPoints = len(point) if numPoints < 2: return infinity, (None, None) return min( ((abs(point[i] - point[j]), (point[i], point[j])) for i in range(numPoints-1) for j in range(i+1,numPoints)), key=itemgetter(0)) def closestPair(point): xP = sorted(point, key= attrgetter('real')) yP = sorted(point, key= attrgetter('imag')) return _closestPair(xP, yP) def _closestPair(xP, yP): numPoints = len(xP) if numPoints <= 3: return bruteForceClosestPair(xP) Pl = xP[:numPoints/2] Pr = xP[numPoints/2:] Yl, Yr = [], [] xDivider = Pl[-1].real for p in yP: if p.real <= xDivider: Yl.append(p) else: Yr.append(p) dl, pairl = _closestPair(Pl, Yl) dr, pairr = _closestPair(Pr, Yr) dm, pairm = (dl, pairl) if dl < dr else (dr, pairr) closeY = [p for p in yP if abs(p.real - xDivider) < dm] numCloseY = len(closeY) if numCloseY > 1: closestY = min( ((abs(closeY[i] - closeY[j]), (closeY[i], closeY[j])) for i in range(numCloseY-1) for j in range(i+1,min(i+8, numCloseY))), key=itemgetter(0)) return (dm, pairm) if dm <= closestY[0] else closestY else: return dm, pairm def times(): import timeit functions = [bruteForceClosestPair, closestPair] for f in functions: print 'Time for', f.__name__, timeit.Timer( '%s(pointList)' % f.__name__, 'from closestpair import %s, pointList' % f.__name__).timeit(number=1) pointList = [randint(0,1000)+1j*randint(0,1000) for i in range(2000)] if __name__ == '__main__': pointList = [(5+9j), (9+3j), (2+0j), (8+4j), (7+4j), (9+10j), (1+9j), (8+2j), 10j, (9+6j)] print pointList print ' bruteForceClosestPair:', bruteForceClosestPair(pointList) print ' closestPair:', closestPair(pointList) for i in range(10): pointList = [randrange(11)+1j*randrange(11) for i in range(10)] print '\n', pointList print ' bruteForceClosestPair:', bruteForceClosestPair(pointList) print ' closestPair:', closestPair(pointList) print '\n' times() times() times()
Change the following VB code into Python without altering its purpose.
Option Explicit Private Type MyPoint X As Single Y As Single End Type Private Type MyPair p1 As MyPoint p2 As MyPoint End Type Sub Main() Dim points() As MyPoint, i As Long, BF As MyPair, d As Single, Nb As Long Dim T# Randomize Timer Nb = 10 Do ReDim points(1 To Nb) For i = 1 To Nb points(i).X = Rnd * Nb points(i).Y = Rnd * Nb Next d = 1000000000000# T = Timer BF = BruteForce(points, d) Debug.Print "For " & Nb & " points, runtime : " & Timer - T & " sec." Debug.Print "point 1 : X:" & BF.p1.X & " Y:" & BF.p1.Y Debug.Print "point 2 : X:" & BF.p2.X & " Y:" & BF.p2.Y Debug.Print "dist : " & d Debug.Print "--------------------------------------------------" Nb = Nb * 10 Loop While Nb <= 10000 End Sub Private Function BruteForce(p() As MyPoint, mindist As Single) As MyPair Dim i As Long, j As Long, d As Single, ClosestPair As MyPair For i = 1 To UBound(p) - 1 For j = i + 1 To UBound(p) d = Dist(p(i), p(j)) If d < mindist Then mindist = d ClosestPair.p1 = p(i) ClosestPair.p2 = p(j) End If Next Next BruteForce = ClosestPair End Function Private Function Dist(p1 As MyPoint, p2 As MyPoint) As Single Dist = Sqr((p1.X - p2.X) ^ 2 + (p1.Y - p2.Y) ^ 2) End Function
from random import randint, randrange from operator import itemgetter, attrgetter infinity = float('inf') def bruteForceClosestPair(point): numPoints = len(point) if numPoints < 2: return infinity, (None, None) return min( ((abs(point[i] - point[j]), (point[i], point[j])) for i in range(numPoints-1) for j in range(i+1,numPoints)), key=itemgetter(0)) def closestPair(point): xP = sorted(point, key= attrgetter('real')) yP = sorted(point, key= attrgetter('imag')) return _closestPair(xP, yP) def _closestPair(xP, yP): numPoints = len(xP) if numPoints <= 3: return bruteForceClosestPair(xP) Pl = xP[:numPoints/2] Pr = xP[numPoints/2:] Yl, Yr = [], [] xDivider = Pl[-1].real for p in yP: if p.real <= xDivider: Yl.append(p) else: Yr.append(p) dl, pairl = _closestPair(Pl, Yl) dr, pairr = _closestPair(Pr, Yr) dm, pairm = (dl, pairl) if dl < dr else (dr, pairr) closeY = [p for p in yP if abs(p.real - xDivider) < dm] numCloseY = len(closeY) if numCloseY > 1: closestY = min( ((abs(closeY[i] - closeY[j]), (closeY[i], closeY[j])) for i in range(numCloseY-1) for j in range(i+1,min(i+8, numCloseY))), key=itemgetter(0)) return (dm, pairm) if dm <= closestY[0] else closestY else: return dm, pairm def times(): import timeit functions = [bruteForceClosestPair, closestPair] for f in functions: print 'Time for', f.__name__, timeit.Timer( '%s(pointList)' % f.__name__, 'from closestpair import %s, pointList' % f.__name__).timeit(number=1) pointList = [randint(0,1000)+1j*randint(0,1000) for i in range(2000)] if __name__ == '__main__': pointList = [(5+9j), (9+3j), (2+0j), (8+4j), (7+4j), (9+10j), (1+9j), (8+2j), 10j, (9+6j)] print pointList print ' bruteForceClosestPair:', bruteForceClosestPair(pointList) print ' closestPair:', closestPair(pointList) for i in range(10): pointList = [randrange(11)+1j*randrange(11) for i in range(10)] print '\n', pointList print ' bruteForceClosestPair:', bruteForceClosestPair(pointList) print ' closestPair:', closestPair(pointList) print '\n' times() times() times()
Maintain the same structure and functionality when rewriting this code in Python.
Dim TheAddress as long Dim SecVar as byte Dim MyVar as byte MyVar = 10 TheAddress = varptr(MyVar) MEMSET(TheAddress, 102, SizeOf(byte)) showmessage "MyVar = " + str$(MyVar) MEMCPY(VarPtr(SecVar), TheAddress, SizeOf(byte)) showmessage "SecVar = " + str$(SecVar)
var num = 12 var pointer = ptr(num) print pointer @unsafe pointer.addr = 0xFFFE
Change the programming language of this snippet from VB to Python without modifying what it does.
Class Animal End Class Class Dog Inherits Animal End Class Class Lab Inherits Dog End Class Class Collie Inherits Dog End Class Class Cat Inherits Animal End Class
class Animal: pass class Dog(Animal): pass class Cat(Animal): pass class Lab(Dog): pass class Collie(Dog): pass
Port the following code from VB to Python with equivalent syntax and logic.
Option Explicit Sub Test() Dim h As Object Set h = CreateObject("Scripting.Dictionary") h.Add "A", 1 h.Add "B", 2 h.Add "C", 3 Debug.Print h.Item("A") h.Item("C") = 4 h.Key("C") = "D" Debug.Print h.exists("C") h.Remove "B" Debug.Print h.Count h.RemoveAll Debug.Print h.Count End Sub
hash = dict() hash = dict(red="FF0000", green="00FF00", blue="0000FF") hash = { 'key1':1, 'key2':2, } value = hash[key]
Port the provided VB code into Python while preserving the original functionality.
Option explicit Class ImgClass Private ImgL,ImgH,ImgDepth,bkclr,loc,tt private xmini,xmaxi,ymini,ymaxi,dirx,diry public ImgArray() private filename private Palette,szpal public property get xmin():xmin=xmini:end property public property get ymin():ymin=ymini:end property public property get xmax():xmax=xmaxi:end property public property get ymax():ymax=ymaxi:end property public property let depth(x) if x<>8 and x<>32 then err.raise 9 Imgdepth=x end property public sub set0 (x0,y0) if x0<0 or x0>=imgl or y0<0 or y0>imgh then err.raise 9 xmini=-x0 ymini=-y0 xmaxi=xmini+imgl-1 ymaxi=ymini+imgh-1 end sub Public Default Function Init(name,w,h,orient,dep,bkg,mipal) dim i,j ImgL=w ImgH=h tt=timer loc=getlocale set0 0,0 redim imgArray(ImgL-1,ImgH-1) bkclr=bkg if bkg<>0 then for i=0 to ImgL-1 for j=0 to ImgH-1 imgarray(i,j)=bkg next next end if Select Case orient Case 1: dirx=1 : diry=1 Case 2: dirx=-1 : diry=1 Case 3: dirx=-1 : diry=-1 Case 4: dirx=1 : diry=-1 End select filename=name ImgDepth =dep if imgdepth=8 then loadpal(mipal) end if set init=me end function private sub loadpal(mipale) if isarray(mipale) Then palette=mipale szpal=UBound(mipale)+1 Else szpal=256 , not relevant End if End Sub Private Sub Class_Terminate if err<>0 then wscript.echo "Error " & err.number wscript.echo "copying image to bmp file" savebmp wscript.echo "opening " & filename & " with your default bmp viewer" CreateObject("Shell.Application").ShellExecute filename wscript.echo timer-tt & " iseconds" End Sub function long2wstr( x) dim k1,k2,x1 k1= (x and &hffff&) k2=((X And &h7fffffff&) \ &h10000&) Or (&H8000& And (x<0)) long2wstr=chrw(k1) & chrw(k2) end function function int2wstr(x) int2wstr=ChrW((x and &h7fff) or (&H8000 And (X<0))) End Function Public Sub SaveBMP Dim s,ostream, x,y,loc const hdrs=54 dim bms:bms=ImgH* 4*(((ImgL*imgdepth\8)+3)\4) dim palsize:if (imgdepth=8) then palsize=szpal*4 else palsize=0 with CreateObject("ADODB.Stream") .Charset = "UTF-16LE" .Type = 2 .open .writetext ChrW(&h4d42) .writetext long2wstr(hdrs+palsize+bms) .writetext long2wstr(0) .writetext long2wstr (hdrs+palsize) .writetext long2wstr(40) .writetext long2wstr(Imgl) .writetext long2wstr(imgh) .writetext int2wstr(1) .writetext int2wstr(imgdepth) .writetext long2wstr(&H0) .writetext long2wstr(bms) .writetext long2wstr(&Hc4e) .writetext long2wstr(&hc43) .writetext long2wstr(szpal) .writetext long2wstr(&H0) Dim x1,x2,y1,y2 If dirx=-1 Then x1=ImgL-1 :x2=0 Else x1=0:x2=ImgL-1 If diry=-1 Then y1=ImgH-1 :y2=0 Else y1=0:y2=ImgH-1 Select Case imgdepth Case 32 For y=y1 To y2 step diry For x=x1 To x2 Step dirx .writetext long2wstr(Imgarray(x,y)) Next Next Case 8 For x=0 to szpal-1 .writetext long2wstr(palette(x)) Next dim pad:pad=ImgL mod 4 For y=y1 to y2 step diry For x=x1 To x2 step dirx*2 .writetext chrw((ImgArray(x,y) and 255)+ &h100& *(ImgArray(x+dirx,y) and 255)) Next if pad and 1 then .writetext chrw(ImgArray(x2,y)) if pad >1 then .writetext chrw(0) Next Case Else WScript.Echo "ColorDepth not supported : " & ImgDepth & " bits" End Select Dim outf:Set outf= CreateObject("ADODB.Stream") outf.Type = 1 outf.Open .position=2 .CopyTo outf .close outf.savetofile filename,2 outf.close end with End Sub end class function hsv2rgb( Hue, Sat, Value) dim Angle, Radius,Ur,Vr,Wr,Rdim dim r,g,b, rgb Angle = (Hue-150) *0.01745329251994329576923690768489 Ur = Value * 2.55 Radius = Ur * tan(Sat *0.01183199) Vr = Radius * cos(Angle) *0.70710678 Wr = Radius * sin(Angle) *0.40824829 r = (Ur - Vr - Wr) g = (Ur + Vr - Wr) b = (Ur + Wr + Wr) if r >255 then Rdim = (Ur - 255) / (Vr + Wr) r = 255 g = Ur + (Vr - Wr) * Rdim b = Ur + 2 * Wr * Rdim elseif r < 0 then Rdim = Ur / (Vr + Wr) r = 0 g = Ur + (Vr - Wr) * Rdim b = Ur + 2 * Wr * Rdim end if if g >255 then Rdim = (255 - Ur) / (Vr - Wr) r = Ur - (Vr + Wr) * Rdim g = 255 b = Ur + 2 * Wr * Rdim elseif g<0 then Rdim = -Ur / (Vr - Wr) r = Ur - (Vr + Wr) * Rdim g = 0 b = Ur + 2 * Wr * Rdim end if if b>255 then Rdim = (255 - Ur) / (Wr + Wr) r = Ur - (Vr + Wr) * Rdim g = Ur + (Vr - Wr) * Rdim b = 255 elseif b<0 then Rdim = -Ur / (Wr + Wr) r = Ur - (Vr + Wr) * Rdim g = Ur + (Vr - Wr) * Rdim b = 0 end If hsv2rgb= ((b and &hff)+256*((g and &hff)+256*(r and &hff))and &hffffff) end function function ang(col,row) if col =0 then if row<0 then ang=90 else ang=270 end if else if col>0 then ang=atn(-row/col)*57.2957795130 else ang=(atn(row/-col)*57.2957795130)+180 end if end if ang=(ang+360) mod 360 end function Dim X,row,col,fn,tt,hr,sat,row2 const h=160 const w=160 const rad=159 const r2=25500 tt=timer fn=CreateObject("Scripting.FileSystemObject").GetSpecialFolder(2)& "\testwchr.bmp" Set X = (New ImgClass)(fn,w*2,h*2,1,32,0,0) x.set0 w,h for row=x.xmin+1 to x.xmax row2=row*row hr=int(Sqr(r2-row2)) For col=hr To 159 Dim a:a=((col\16 +row\16) And 1)* &hffffff x.imgArray(col+160,row+160)=a x.imgArray(-col+160,row+160)=a next for col=-hr to hr sat=100-sqr(row2+col*col)/rad *50 x.imgArray(col+160,row+160)=hsv2rgb(ang(row,col)+90,100,sat) next next Set X = Nothing
size(300, 300) background(0) radius = min(width, height) / 2.0 cx, cy = width / 2, width / 2 for x in range(width): for y in range(height): rx = x - cx ry = y - cy s = sqrt(rx ** 2 + ry ** 2) / radius if s <= 1.0: h = ((atan2(ry, rx) / PI) + 1.0) / 2.0 colorMode(HSB) c = color(int(h * 255), int(s * 255), 255) set(x, y, c)
Convert the following code from VB to Python, ensuring the logic remains intact.
Imports System.Console Imports DT = System.DateTime Imports Lsb = System.Collections.Generic.List(Of SByte) Imports Lst = System.Collections.Generic.List(Of System.Collections.Generic.List(Of SByte)) Imports UI = System.UInt64 Module Module1 Const MxD As SByte = 15 Public Structure term Public coeff As UI : Public a, b As SByte Public Sub New(ByVal c As UI, ByVal a_ As Integer, ByVal b_ As Integer) coeff = c : a = CSByte(a_) : b = CSByte(b_) End Sub End Structure Dim nd, nd2, count As Integer, digs, cnd, di As Integer() Dim res As List(Of UI), st As DT, tLst As List(Of List(Of term)) Dim lists As List(Of Lst), fml, dmd As Dictionary(Of Integer, Lst) Dim dl, zl, el, ol, il As Lsb, odd As Boolean, ixs, dis As Lst, Dif As UI Function ToDif() As UI Dim r As UI = 0 : For i As Integer = 0 To digs.Length - 1 : r = r * 10 + digs(i) Next : Return r End Function Function ToSum() As UI Dim r As UI = 0 : For i As Integer = digs.Length - 1 To 0 Step -1 : r = r * 10 + digs(i) Next : Return Dif + (r << 1) End Function Function IsSquare(nmbr As UI) As Boolean If (&H202021202030213 And (1UL << (nmbr And 63))) <> 0 Then _ Dim r As UI = Math.Sqrt(nmbr) : Return r * r = nmbr Else Return False End Function Function Seq(from As SByte, upto As Integer, Optional stp As SByte = 1) As Lsb Dim res As Lsb = New Lsb() For item As SByte = from To upto Step stp : res.Add(item) : Next : Return res End Function Sub Fnpr(ByVal lev As Integer) If lev = dis.Count Then digs(ixs(0)(0)) = fml(cnd(0))(di(0))(0) : digs(ixs(0)(1)) = fml(cnd(0))(di(0))(1) Dim le As Integer = di.Length, i As Integer = 1 If odd Then le -= 1 : digs(nd >> 1) = di(le) For Each d As SByte In di.Skip(1).Take(le - 1) digs(ixs(i)(0)) = dmd(cnd(i))(d)(0) digs(ixs(i)(1)) = dmd(cnd(i))(d)(1) : i += 1 : Next If Not IsSquare(ToSum()) Then Return res.Add(ToDif()) : count += 1 WriteLine("{0,16:n0}{1,4} ({2:n0})", (DT.Now - st).TotalMilliseconds, count, res.Last()) Else For Each n In dis(lev) : di(lev) = n : Fnpr(lev + 1) : Next End If End Sub Sub Fnmr(ByVal list As Lst, ByVal lev As Integer) If lev = list.Count Then Dif = 0 : Dim i As SByte = 0 : For Each t In tLst(nd2) If cnd(i) < 0 Then Dif -= t.coeff * CULng(-cnd(i)) _ Else Dif += t.coeff * CULng(cnd(i)) i += 1 : Next If Dif <= 0 OrElse Not IsSquare(Dif) Then Return dis = New Lst From {Seq(0, fml(cnd(0)).Count - 1)} For Each i In cnd.Skip(1) : dis.Add(Seq(0, dmd(i).Count - 1)) : Next If odd Then dis.Add(il) di = New Integer(dis.Count - 1) {} : Fnpr(0) Else For Each n As SByte In list(lev) : cnd(lev) = n : Fnmr(list, lev + 1) : Next End If End Sub Sub init() Dim pow As UI = 1 tLst = New List(Of List(Of term))() : For Each r As Integer In Seq(2, MxD) Dim terms As List(Of term) = New List(Of term)() pow *= 10 : Dim p1 As UI = pow, p2 As UI = 1 Dim i1 As Integer = 0, i2 As Integer = r - 1 While i1 < i2 : terms.Add(New term(p1 - p2, i1, i2)) p1 = p1 / 10 : p2 = p2 * 10 : i1 += 1 : i2 -= 1 : End While tLst.Add(terms) : Next fml = New Dictionary(Of Integer, Lst)() From { {0, New Lst() From {New Lsb() From {2, 2}, New Lsb() From {8, 8}}}, {1, New Lst() From {New Lsb() From {6, 5}, New Lsb() From {8, 7}}}, {4, New Lst() From {New Lsb() From {4, 0}}}, {6, New Lst() From {New Lsb() From {6, 0}, New Lsb() From {8, 2}}}} dmd = New Dictionary(Of Integer, Lst)() For i As SByte = 0 To 10 - 1 : Dim j As SByte = 0, d As SByte = i While j < 10 : If dmd.ContainsKey(d) Then dmd(d).Add(New Lsb From {i, j}) _ Else dmd(d) = New Lst From {New Lsb From {i, j}} j += 1 : d -= 1 : End While : Next dl = Seq(-9, 9) zl = Seq(0, 0) el = Seq(-8, 8, 2) ol = Seq(-9, 9, 2) il = Seq(0, 9) lists = New List(Of Lst)() For Each f As SByte In fml.Keys : lists.Add(New Lst From {New Lsb From {f}}) : Next End Sub Sub Main(ByVal args As String()) init() : res = New List(Of UI)() : st = DT.Now : count = 0 WriteLine("{0,5}{1,12}{2,4}{3,14}", "digs", "elapsed(ms)", "R/N", "Rare Numbers") nd = 2 : nd2 = 0 : odd = False : While nd <= MxD digs = New Integer(nd - 1) {} : If nd = 4 Then lists(0).Add(zl) : lists(1).Add(ol) : lists(2).Add(el) : lists(3).Add(ol) ElseIf tLst(nd2).Count > lists(0).Count Then For Each list As Lst In lists : list.Add(dl) : Next : End If ixs = New Lst() : For Each t As term In tLst(nd2) : ixs.Add(New Lsb From {t.a, t.b}) : Next For Each list As Lst In lists : cnd = New Integer(list.Count - 1) {} : Fnmr(list, 0) : Next WriteLine(" {0,2} {1,10:n0}", nd, (DT.Now - st).TotalMilliseconds) nd += 1 : nd2 += 1 : odd = Not odd : End While res.Sort() : WriteLine(vbLf & "The {0} rare numbers with up to {1} digits are:", res.Count, MxD) count = 0 : For Each rare In res : count += 1 : WriteLine("{0,2}:{1,27:n0}", count, rare) : Next If System.Diagnostics.Debugger.IsAttached Then ReadKey() End Sub End Module
from math import floor, sqrt from datetime import datetime def main(): start = datetime.now() for i in xrange(1, 10 ** 11): if rare(i): print "found a rare:", i end = datetime.now() print "time elapsed:", end - start def is_square(n): s = floor(sqrt(n + 0.5)) return s * s == n def reverse(n): return int(str(n)[::-1]) def is_palindrome(n): return n == reverse(n) def rare(n): r = reverse(n) return ( not is_palindrome(n) and n > r and is_square(n+r) and is_square(n-r) ) if __name__ == '__main__': main()
Produce a language-to-language conversion: from VB to Python, same semantics.
with createobject("ADODB.Stream") .charset ="UTF-8" .open .loadfromfile("unixdict.txt") s=.readtext end with a=split (s,vblf) dim b(25) dim c(128) with new regexp .pattern="([^aeiou])" .global=true for each i in a if len(trim(i))>10 then set matches= .execute(i) rep=false for each m in matches x=asc(m) c(x)=c(x)+1 if c(x)>1 then rep=true :exit for next erase c if not rep then x1=matches.count b(x1)=b(x1)&" "&i end if end if next end with for i=25 to 0 step -1 if b(i)<>"" then wscript.echo i & " "& b(i) & vbcrlf next
print('\n'.join((f'{x[0]}: {" ".join(sorted(x[1]))}' if len(x[1]) < 30 else f'{x[0]}: {len(x[1])} words' for x in (x for x in ((n, [x[1] for x in l if x[0] == n]) for n in range(maxlen, -1, -1)) if x[1]))) if (maxlen := max(l := [(len(c), w) for w in [l for l in [l.rstrip() for l in open('unixdict.txt')] if len(l) > 10 and all(c >= 'a' and c <= 'z' for c in l)] if sorted(c := w.replace('a', '').replace('e', '').replace('i', '').replace('o', '').replace('u', '')) == sorted(set(c))])[0]) else None)
Convert this VB block to Python, preserving its control flow and logic.
with createobject("ADODB.Stream") .charset ="UTF-8" .open .loadfromfile("unixdict.txt") s=.readtext end with a=split (s,vblf) dim b(25) dim c(128) with new regexp .pattern="([^aeiou])" .global=true for each i in a if len(trim(i))>10 then set matches= .execute(i) rep=false for each m in matches x=asc(m) c(x)=c(x)+1 if c(x)>1 then rep=true :exit for next erase c if not rep then x1=matches.count b(x1)=b(x1)&" "&i end if end if next end with for i=25 to 0 step -1 if b(i)<>"" then wscript.echo i & " "& b(i) & vbcrlf next
print('\n'.join((f'{x[0]}: {" ".join(sorted(x[1]))}' if len(x[1]) < 30 else f'{x[0]}: {len(x[1])} words' for x in (x for x in ((n, [x[1] for x in l if x[0] == n]) for n in range(maxlen, -1, -1)) if x[1]))) if (maxlen := max(l := [(len(c), w) for w in [l for l in [l.rstrip() for l in open('unixdict.txt')] if len(l) > 10 and all(c >= 'a' and c <= 'z' for c in l)] if sorted(c := w.replace('a', '').replace('e', '').replace('i', '').replace('o', '').replace('u', '')) == sorted(set(c))])[0]) else None)
Rewrite the snippet below in Python so it works the same as the original VB code.
Option Explicit Public vTime As Single Public PlaysCount As Long Sub Main_MineSweeper() Dim Userf As New cMinesweeper Userf.Show 0, True End Sub
gridsize = (6, 4) minerange = (0.2, 0.6) try: raw_input except: raw_input = input import random from itertools import product from pprint import pprint as pp def gridandmines(gridsize=gridsize, minerange=minerange): xgrid, ygrid = gridsize minmines, maxmines = minerange minecount = xgrid * ygrid minecount = random.randint(int(minecount*minmines), int(minecount*maxmines)) grid = set(product(range(xgrid), range(ygrid))) mines = set(random.sample(grid, minecount)) show = {xy:'.' for xy in grid} return grid, mines, show def printgrid(show, gridsize=gridsize): xgrid, ygrid = gridsize grid = '\n'.join(''.join(show[(x,y)] for x in range(xgrid)) for y in range(ygrid)) print( grid ) def resign(showgrid, mines, markedmines): for m in mines: showgrid[m] = 'Y' if m in markedmines else 'N' def clear(x,y, showgrid, grid, mines, markedmines): if showgrid[(x, y)] == '.': xychar = str(sum(1 for xx in (x-1, x, x+1) for yy in (y-1, y, y+1) if (xx, yy) in mines )) if xychar == '0': xychar = '.' showgrid[(x,y)] = xychar for xx in (x-1, x, x+1): for yy in (y-1, y, y+1): xxyy = (xx, yy) if ( xxyy != (x, y) and xxyy in grid and xxyy not in mines | markedmines ): clear(xx, yy, showgrid, grid, mines, markedmines) if __name__ == '__main__': grid, mines, showgrid = gridandmines() markedmines = set([]) print( __doc__ ) print( '\nThere are %i true mines of fixed position in the grid\n' % len(mines) ) printgrid(showgrid) while markedmines != mines: inp = raw_input('m x y/c x y/p/r: ').strip().split() if inp: if inp[0] == 'm': x, y = [int(i)-1 for i in inp[1:3]] if (x,y) in markedmines: markedmines.remove((x,y)) showgrid[(x,y)] = '.' else: markedmines.add((x,y)) showgrid[(x,y)] = '?' elif inp[0] == 'p': printgrid(showgrid) elif inp[0] == 'c': x, y = [int(i)-1 for i in inp[1:3]] if (x,y) in mines | markedmines: print( '\nKLABOOM!! You hit a mine.\n' ) resign(showgrid, mines, markedmines) printgrid(showgrid) break clear(x,y, showgrid, grid, mines, markedmines) printgrid(showgrid) elif inp[0] == 'r': print( '\nResigning!\n' ) resign(showgrid, mines, markedmines) printgrid(showgrid) break print( '\nYou got %i and missed %i of the %i mines' % (len(mines.intersection(markedmines)), len(markedmines.difference(mines)), len(mines)) )
Translate the given VB code snippet into Python without altering its behavior.
Imports System.Linq Imports System.Collections.Generic Imports System.Console Imports System.Math Module Module1 Dim ba As Integer Dim chars As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" Iterator Function Primes(ByVal lim As Integer) As IEnumerable(Of Integer) Dim flags(lim) As Boolean, j As Integer : Yield 2 For j = 4 To lim Step 2 : flags(j) = True : Next : j = 3 Dim d As Integer = 8, sq As Integer = 9 While sq <= lim If Not flags(j) Then Yield j : Dim i As Integer = j << 1 For k As Integer = sq To lim step i : flags(k) = True : Next End If j += 2 : d += 8 : sq += d : End While While j <= lim If Not flags(j) Then Yield j j += 2 : End While End Function Function from10(ByVal b As Integer) As String Dim res As String = "", re As Integer While b > 0 : b = DivRem(b, ba, re) : res = chars(CByte(re)) & res : End While : Return res End Function Function to10(ByVal s As String) As Integer Dim res As Integer = 0 For Each i As Char In s : res = res * ba + chars.IndexOf(i) : Next : Return res End Function Function nd(ByVal s As String) As Boolean If s.Length < 2 Then Return True Dim l As Char = s(0) For i As Integer = 1 To s.Length - 1 If chars.IndexOf(l) > chars.IndexOf(s(i)) Then Return False Else l = s(i) Next : Return True End Function Sub Main(ByVal args As String()) Dim c As Integer, lim As Integer = 1000, s As String For Each b As Integer In New List(Of Integer) From { 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 } ba = b : c = 0 : For Each a As Integer In Primes(lim) s = from10(a) : If nd(s) Then c += 1 : Write("{0,4} {1}", s, If(c Mod 20 = 0, vbLf, "")) Next WriteLine(vbLf & "Base {0}: found {1} non-decreasing primes under {2:n0}" & vbLf, b, c, from10(lim)) Next End Sub End Module
from operator import le from itertools import takewhile def monotonicDigits(base): def go(n): return monotonic(le)( showIntAtBase(base)(digitFromInt)(n)('') ) return go def monotonic(op): def go(xs): return all(map(op, xs, xs[1:])) return go def main(): xs = [ str(n) for n in takewhile( lambda n: 1000 > n, filter(monotonicDigits(10), primes()) ) ] w = len(xs[-1]) print(f'{len(xs)} matches for base 10:\n') print('\n'.join( ' '.join(row) for row in chunksOf(10)([ x.rjust(w, ' ') for x in xs ]) )) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go def digitFromInt(n): return '0123456789abcdefghijklmnopqrstuvwxyz'[n] if ( 0 <= n < 36 ) else '?' def primes(): n = 2 dct = {} while True: if n in dct: for p in dct[n]: dct.setdefault(n + p, []).append(p) del dct[n] else: yield n dct[n * n] = [n] n = 1 + n def showIntAtBase(base): def wrap(toChr, n, rs): def go(nd, r): n, d = nd r_ = toChr(d) + r return go(divmod(n, base), r_) if 0 != n else r_ return 'unsupported base' if 1 >= base else ( 'negative number' if 0 > n else ( go(divmod(n, base), rs)) ) return lambda toChr: lambda n: lambda rs: ( wrap(toChr, n, rs) ) if __name__ == '__main__': main()
Ensure the translated Python code behaves exactly like the original VB snippet.
Imports System.Linq Imports System.Collections.Generic Imports System.Console Imports System.Math Module Module1 Dim ba As Integer Dim chars As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" Iterator Function Primes(ByVal lim As Integer) As IEnumerable(Of Integer) Dim flags(lim) As Boolean, j As Integer : Yield 2 For j = 4 To lim Step 2 : flags(j) = True : Next : j = 3 Dim d As Integer = 8, sq As Integer = 9 While sq <= lim If Not flags(j) Then Yield j : Dim i As Integer = j << 1 For k As Integer = sq To lim step i : flags(k) = True : Next End If j += 2 : d += 8 : sq += d : End While While j <= lim If Not flags(j) Then Yield j j += 2 : End While End Function Function from10(ByVal b As Integer) As String Dim res As String = "", re As Integer While b > 0 : b = DivRem(b, ba, re) : res = chars(CByte(re)) & res : End While : Return res End Function Function to10(ByVal s As String) As Integer Dim res As Integer = 0 For Each i As Char In s : res = res * ba + chars.IndexOf(i) : Next : Return res End Function Function nd(ByVal s As String) As Boolean If s.Length < 2 Then Return True Dim l As Char = s(0) For i As Integer = 1 To s.Length - 1 If chars.IndexOf(l) > chars.IndexOf(s(i)) Then Return False Else l = s(i) Next : Return True End Function Sub Main(ByVal args As String()) Dim c As Integer, lim As Integer = 1000, s As String For Each b As Integer In New List(Of Integer) From { 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 } ba = b : c = 0 : For Each a As Integer In Primes(lim) s = from10(a) : If nd(s) Then c += 1 : Write("{0,4} {1}", s, If(c Mod 20 = 0, vbLf, "")) Next WriteLine(vbLf & "Base {0}: found {1} non-decreasing primes under {2:n0}" & vbLf, b, c, from10(lim)) Next End Sub End Module
from operator import le from itertools import takewhile def monotonicDigits(base): def go(n): return monotonic(le)( showIntAtBase(base)(digitFromInt)(n)('') ) return go def monotonic(op): def go(xs): return all(map(op, xs, xs[1:])) return go def main(): xs = [ str(n) for n in takewhile( lambda n: 1000 > n, filter(monotonicDigits(10), primes()) ) ] w = len(xs[-1]) print(f'{len(xs)} matches for base 10:\n') print('\n'.join( ' '.join(row) for row in chunksOf(10)([ x.rjust(w, ' ') for x in xs ]) )) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go def digitFromInt(n): return '0123456789abcdefghijklmnopqrstuvwxyz'[n] if ( 0 <= n < 36 ) else '?' def primes(): n = 2 dct = {} while True: if n in dct: for p in dct[n]: dct.setdefault(n + p, []).append(p) del dct[n] else: yield n dct[n * n] = [n] n = 1 + n def showIntAtBase(base): def wrap(toChr, n, rs): def go(nd, r): n, d = nd r_ = toChr(d) + r return go(divmod(n, base), r_) if 0 != n else r_ return 'unsupported base' if 1 >= base else ( 'negative number' if 0 > n else ( go(divmod(n, base), rs)) ) return lambda toChr: lambda n: lambda rs: ( wrap(toChr, n, rs) ) if __name__ == '__main__': main()
Port the following code from VB to Python with equivalent syntax and logic.
Imports System.Reflection Module Module1 Class TestClass Private privateField = 7 Public ReadOnly Property PublicNumber = 4 Private ReadOnly Property PrivateNumber = 2 End Class Function GetPropertyValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable Return From p In obj.GetType().GetProperties(flags) Where p.GetIndexParameters().Length = 0 Select New With {p.Name, Key .Value = p.GetValue(obj, Nothing)} End Function Function GetFieldValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable Return obj.GetType().GetFields(flags).Select(Function(f) New With {f.Name, Key .Value = f.GetValue(obj)}) End Function Sub Main() Dim t As New TestClass() Dim flags = BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance For Each prop In GetPropertyValues(t, flags) Console.WriteLine(prop) Next For Each field In GetFieldValues(t, flags) Console.WriteLine(field) Next End Sub End Module
class Parent(object): __priv = 'private' def __init__(self, name): self.name = name def __repr__(self): return '%s(%s)' % (type(self).__name__, self.name) def doNothing(self): pass import re class Child(Parent): __rePrivate = re.compile('^_(Child|Parent)__') __reBleh = re.compile('\Wbleh$') @property def reBleh(self): return self.__reBleh def __init__(self, name, *args): super(Child, self).__init__(name) self.args = args def __dir__(self): myDir = filter( lambda p: not self.__rePrivate.match(p), list(set( \ sum([dir(base) for base in type(self).__bases__], []) \ + type(self).__dict__.keys() \ + self.__dict__.keys() \ ))) return myDir + map( lambda p: p + '_bleh', filter( lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)), myDir)) def __getattr__(self, name): if name[-5:] == '_bleh': return str(getattr(self, name[:-5])) + ' bleh' if hasattr(super(Child, chld), '__getattr__'): return super(Child, self).__getattr__(name) raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name)) def __setattr__(self, name, value): if name[-5:] == '_bleh': if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))): setattr(self, name[:-5], self.reBleh.sub('', value)) elif hasattr(super(Child, self), '__setattr__'): super(Child, self).__setattr__(name, value) elif hasattr(self, '__dict__'): self.__dict__[name] = value def __repr__(self): return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()')) def doStuff(self): return (1+1.0/1e6) ** 1e6 par = Parent('par') par.parent = True dir(par) inspect.getmembers(par) chld = Child('chld', 0, 'I', 'two') chld.own = "chld's own" dir(chld) inspect.getmembers(chld)
Write the same code in Python as shown below in VB.
Dim MText as QMemorystream MText.WriteLine "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" MText.WriteLine "are$delineated$by$a$single$ MText.WriteLine "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" MText.WriteLine "column$are$separated$by$at$least$one$space." MText.WriteLine "Further,$allow$for$each$word$in$a$column$to$be$either$left$" MText.WriteLine "justified,$right$justified,$or$center$justified$within$its$column." DefStr TextLeft, TextRight, TextCenter DefStr MLine, LWord, Newline = chr$(13)+chr$(10) DefInt ColWidth(100), ColCount DefSng NrSpaces MText.position = 0 for x = 0 to MText.linecount -1 MLine = MText.ReadLine for y = 0 to Tally(MLine, "$") LWord = Field$(MLine, "$", y+1) ColWidth(y) = iif (ColWidth(y) < len(LWord), len(LWord), ColWidth(y)) next next MText.position = 0 for x = 0 to MText.linecount -1 MLine = MText.ReadLine for y = 0 to Tally(MLine, "$") LWord = Field$(MLine, "$", y+1) NrSpaces = ColWidth(y) - len(LWord) TextLeft = TextLeft + LWord + Space$(NrSpaces+1) TextRight = TextRight + Space$(NrSpaces+1) + LWord TextCenter = TextCenter + Space$(floor((NrSpaces)/2)+1) + LWord + Space$(Ceil((NrSpaces)/2)) next TextLeft = TextLeft + Newline TextRight = TextRight + Newline TextCenter = TextCenter + Newline next
from itertools import zip_longest txt = parts = [line.rstrip("$").split("$") for line in txt.splitlines()] widths = [max(len(word) for word in col) for col in zip_longest(*parts, fillvalue='')] for justify in "<_Left ^_Center >_Right".split(): j, jtext = justify.split('_') print(f"{jtext} column-aligned output:\n") for line in parts: print(' '.join(f"{wrd:{j}{wdth}}" for wdth, wrd in zip(widths, line))) print("- " * 52)
Convert this VB snippet to Python and keep its semantics consistent.
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Convert this VB snippet to Python and keep its semantics consistent.
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Change the following VB code into Python without altering its purpose.
Function parse_url(url) parse_url = "URL: " & url If InStr(url,"//") Then scheme = Split(url,"//") parse_url = parse_url & vbcrlf & "Scheme: " & Mid(scheme(0),1,Len(scheme(0))-1) domain = Split(scheme(1),"/") If InStr(domain(0),"@") Then cred = Split(domain(0),"@") If InStr(cred(0),".") Then username = Mid(cred(0),1,InStr(1,cred(0),".")-1) password = Mid(cred(0),InStr(1,cred(0),".")+1,Len(cred(0))-InStr(1,cred(0),".")) ElseIf InStr(cred(0),":") Then username = Mid(cred(0),1,InStr(1,cred(0),":")-1) password = Mid(cred(0),InStr(1,cred(0),":")+1,Len(cred(0))-InStr(1,cred(0),":")) End If parse_url = parse_url & vbcrlf & "Username: " & username & vbCrLf &_ "Password: " & password If InStr(cred(1),":") Then host = Mid(cred(1),1,InStr(1,cred(1),":")-1) port = Mid(cred(1),InStr(1,cred(1),":")+1,Len(cred(1))-InStr(1,cred(1),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & cred(1) End If ElseIf InStr(domain(0),":") And Instr(domain(0),"[") = False And Instr(domain(0),"]") = False Then host = Mid(domain(0),1,InStr(1,domain(0),":")-1) port = Mid(domain(0),InStr(1,domain(0),":")+1,Len(domain(0))-InStr(1,domain(0),":")) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port ElseIf Instr(domain(0),"[") And Instr(domain(0),"]:") Then host = Mid(domain(0),1,InStr(1,domain(0),"]")) port = Mid(domain(0),InStr(1,domain(0),"]")+2,Len(domain(0))-(InStr(1,domain(0),"]")+1)) parse_url = parse_url & vbCrLf & "Domain: " & host & vbCrLf & "Port: " & port Else parse_url = parse_url & vbCrLf & "Domain: " & domain(0) End If If UBound(domain) > 0 Then For i = 1 To UBound(domain) If i < UBound(domain) Then path = path & domain(i) & "/" ElseIf InStr(domain(i),"?") Then path = path & Mid(domain(i),1,InStr(1,domain(i),"?")-1) If InStr(domain(i),"#") Then query = Mid(domain(i),InStr(1,domain(i),"?")+1,InStr(1,domain(i),"#")-InStr(1,domain(i),"?")-1) fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & vbcrlf & "Query: " & query & vbCrLf & "Fragment: " & fragment Else query = Mid(domain(i),InStr(1,domain(i),"?")+1,Len(domain(i))-InStr(1,domain(i),"?")) path = path & vbcrlf & "Query: " & query End If ElseIf InStr(domain(i),"#") Then fragment = Mid(domain(i),InStr(1,domain(i),"#")+1,Len(domain(i))-InStr(1,domain(i),"#")) path = path & Mid(domain(i),1,InStr(1,domain(i),"#")-1) & vbCrLf &_ "Fragment: " & fragment Else path = path & domain(i) End If Next parse_url = parse_url & vbCrLf & "Path: " & path End If ElseIf InStr(url,":") Then scheme = Mid(url,1,InStr(1,url,":")-1) path = Mid(url,InStr(1,url,":")+1,Len(url)-InStr(1,url,":")) parse_url = parse_url & vbcrlf & "Scheme: " & scheme & vbCrLf & "Path: " & path Else parse_url = parse_url & vbcrlf & "Invalid!!!" End If End Function WScript.StdOut.WriteLine parse_url("foo://example.com:8042/over/there?name=ferret#nose") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ftp://ftp.is.co.za/rfc/rfc1808.txt") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("http://www.ietf.org/rfc/rfc2396.txt#header1") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("mailto:John.Doe@example.com") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("news:comp.infosystems.www.servers.unix") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("tel:+1-816-555-1212") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("telnet://192.0.2.16:80/") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2") WScript.StdOut.WriteLine "-------------------------------" WScript.StdOut.WriteLine parse_url("this code is messy, long, and needs a makeover!!!")
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Preserve the algorithm and functionality while converting the code from VB to Python.
Imports System.Numerics Imports System.Text Module Module1 ReadOnly ALPHABET As String = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" ReadOnly HEX As String = "0123456789ABCDEF" Function ToBigInteger(value As String, base As Integer) As BigInteger If base < 1 OrElse base > HEX.Length Then Throw New ArgumentException("Base is out of range.") End If Dim bi = BigInteger.Zero For Each c In value Dim c2 = Char.ToUpper(c) Dim idx = HEX.IndexOf(c2) If idx = -1 OrElse idx >= base Then Throw New ArgumentException("Illegal character encountered.") End If bi = bi * base + idx Next Return bi End Function Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String Dim x As BigInteger If base = 16 AndAlso hash.Substring(0, 2) = "0x" Then x = ToBigInteger(hash.Substring(2), base) Else x = ToBigInteger(hash, base) End If Dim sb As New StringBuilder While x > 0 Dim r = x Mod 58 sb.Append(ALPHABET(r)) x = x / 58 End While Dim ca = sb.ToString().ToCharArray() Array.Reverse(ca) Return New String(ca) End Function Sub Main() Dim s = "25420294593250030202636073700053352635053786165627414518" Dim b = ConvertToBase58(s, 10) Console.WriteLine("{0} -> {1}", s, b) Dim hashes = {"0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e"} For Each hash In hashes Dim b58 = ConvertToBase58(hash) Console.WriteLine("{0,-56} -> {1}", hash, b58) Next End Sub End Module
ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" def convertToBase58(num): sb = '' while (num > 0): r = num % 58 sb = sb + ALPHABET[r] num = num // 58; return sb[::-1] s = 25420294593250030202636073700053352635053786165627414518 b = convertToBase58(s) print("%-56d -> %s" % (s, b)) hash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e] for num in hash_arr: b = convertToBase58(num) print("0x%-54x -> %s" % (num, b))
Write the same code in Python as shown below in VB.
Imports System.Numerics Imports System.Text Module Module1 ReadOnly ALPHABET As String = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" ReadOnly HEX As String = "0123456789ABCDEF" Function ToBigInteger(value As String, base As Integer) As BigInteger If base < 1 OrElse base > HEX.Length Then Throw New ArgumentException("Base is out of range.") End If Dim bi = BigInteger.Zero For Each c In value Dim c2 = Char.ToUpper(c) Dim idx = HEX.IndexOf(c2) If idx = -1 OrElse idx >= base Then Throw New ArgumentException("Illegal character encountered.") End If bi = bi * base + idx Next Return bi End Function Function ConvertToBase58(hash As String, Optional base As Integer = 16) As String Dim x As BigInteger If base = 16 AndAlso hash.Substring(0, 2) = "0x" Then x = ToBigInteger(hash.Substring(2), base) Else x = ToBigInteger(hash, base) End If Dim sb As New StringBuilder While x > 0 Dim r = x Mod 58 sb.Append(ALPHABET(r)) x = x / 58 End While Dim ca = sb.ToString().ToCharArray() Array.Reverse(ca) Return New String(ca) End Function Sub Main() Dim s = "25420294593250030202636073700053352635053786165627414518" Dim b = ConvertToBase58(s, 10) Console.WriteLine("{0} -> {1}", s, b) Dim hashes = {"0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e"} For Each hash In hashes Dim b58 = ConvertToBase58(hash) Console.WriteLine("{0,-56} -> {1}", hash, b58) Next End Sub End Module
ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" def convertToBase58(num): sb = '' while (num > 0): r = num % 58 sb = sb + ALPHABET[r] num = num // 58; return sb[::-1] s = 25420294593250030202636073700053352635053786165627414518 b = convertToBase58(s) print("%-56d -> %s" % (s, b)) hash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e] for num in hash_arr: b = convertToBase58(num) print("0x%-54x -> %s" % (num, b))
Change the programming language of this snippet from VB to Python without modifying what it does.
Public Sub commatize(s As String, Optional sep As String = ",", Optional start As Integer = 1, Optional step As Integer = 3) Dim l As Integer: l = Len(s) For i = start To l If Asc(Mid(s, i, 1)) >= Asc("1") And Asc(Mid(s, i, 1)) <= Asc("9") Then For j = i + 1 To l + 1 If j > l Then For k = j - 1 - step To i Step -step s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1) l = Len(s) Next k Exit For Else If (Asc(Mid(s, j, 1)) < Asc("0") Or Asc(Mid(s, j, 1)) > Asc("9")) Then For k = j - 1 - step To i Step -step s = Mid(s, 1, k) & sep & Mid(s, k + 1, l - k + 1) l = Len(s) Next k Exit For End If End If Next j Exit For End If Next i Debug.Print s End Sub Public Sub main() commatize "pi=3.14159265358979323846264338327950288419716939937510582097494459231", " ", 6, 5 commatize "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", "." commatize """-in Aus$+1411.8millions""" commatize "===US$0017440 millions=== (in 2000 dollars)" commatize "123.e8000 is pretty big." commatize "The land area of the earth is 57268900(29% of the surface) square miles." commatize "Ain commatize "James was never known as 0000000007" commatize "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe." commatize " $-140000±100 millions." commatize "6/9/1946 was a good year for some." End Sub
import re as RegEx def Commatize( _string, _startPos=0, _periodLen=3, _separator="," ): outString = "" strPos = 0 matches = RegEx.findall( "[0-9]*", _string ) for match in matches[:-1]: if not match: outString += _string[ strPos ] strPos += 1 else: if len(match) > _periodLen: leadIn = match[:_startPos] periods = [ match [ i:i + _periodLen ] for i in range ( _startPos, len ( match ), _periodLen ) ] outString += leadIn + _separator.join( periods ) else: outString += match strPos += len( match ) return outString print ( Commatize( "pi=3.14159265358979323846264338327950288419716939937510582097494459231", 0, 5, " " ) ) print ( Commatize( "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", 0, 3, "." )) print ( Commatize( "\"-in Aus$+1411.8millions\"" )) print ( Commatize( "===US$0017440 millions=== (in 2000 dollars)" )) print ( Commatize( "123.e8000 is pretty big." )) print ( Commatize( "The land area of the earth is 57268900(29% of the surface) square miles." )) print ( Commatize( "Ain't no numbers in this here words, nohow, no way, Jose." )) print ( Commatize( "James was never known as 0000000007" )) print ( Commatize( "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe." )) print ( Commatize( "␢␢␢$-140000±100 millions." )) print ( Commatize( "6/9/1946 was a good year for some." ))
Can you help me rewrite this code in Python instead of VB, keeping it the same logically?
Imports System.Numerics Imports System.Text Imports Freq = System.Collections.Generic.Dictionary(Of Char, Long) Imports Triple = System.Tuple(Of System.Numerics.BigInteger, Integer, System.Collections.Generic.Dictionary(Of Char, Long)) Module Module1 Function CumulativeFreq(freq As Freq) As Freq Dim total As Long = 0 Dim cf As New Freq For i = 0 To 255 Dim c = Chr(i) If freq.ContainsKey(c) Then Dim v = freq(c) cf(c) = total total += v End If Next Return cf End Function Function ArithmeticCoding(str As String, radix As Long) As Triple Dim freq As New Freq For Each c In str If freq.ContainsKey(c) Then freq(c) += 1 Else freq(c) = 1 End If Next Dim cf = CumulativeFreq(freq) Dim base As BigInteger = str.Length Dim lower As BigInteger = 0 Dim pf As BigInteger = 1 For Each c In str Dim x = cf(c) lower = lower * base + x * pf pf = pf * freq(c) Next Dim upper = lower + pf Dim powr = 0 Dim bigRadix As BigInteger = radix While True pf = pf / bigRadix If pf = 0 Then Exit While End If powr = powr + 1 End While Dim diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr)) Return New Triple(diff, powr, freq) End Function Function ArithmeticDecoding(num As BigInteger, radix As Long, pwr As Integer, freq As Freq) As String Dim powr As BigInteger = radix Dim enc = num * BigInteger.Pow(powr, pwr) Dim base = freq.Values.Sum() Dim cf = CumulativeFreq(freq) Dim dict As New Dictionary(Of Long, Char) For Each key In cf.Keys Dim value = cf(key) dict(value) = key Next Dim lchar As Long = -1 For i As Long = 0 To base - 1 If dict.ContainsKey(i) Then lchar = AscW(dict(i)) Else dict(i) = ChrW(lchar) End If Next Dim decoded As New StringBuilder Dim bigBase As BigInteger = base For i As Long = base - 1 To 0 Step -1 Dim pow = BigInteger.Pow(bigBase, i) Dim div = enc / pow Dim c = dict(div) Dim fv = freq(c) Dim cv = cf(c) Dim diff = enc - pow * cv enc = diff / fv decoded.Append(c) Next Return decoded.ToString() End Function Sub Main() Dim radix As Long = 10 Dim strings = {"DABDDB", "DABDDBBDDBA", "ABRACADABRA", "TOBEORNOTTOBEORTOBEORNOT"} For Each St In strings Dim encoded = ArithmeticCoding(St, radix) Dim dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3) Console.WriteLine("{0,-25}=> {1,19} * {2}^{3}", St, encoded.Item1, radix, encoded.Item2) If St <> dec Then Throw New Exception(vbTab + "However that is incorrect!") End If Next End Sub End Module
from collections import Counter def cumulative_freq(freq): cf = {} total = 0 for b in range(256): if b in freq: cf[b] = total total += freq[b] return cf def arithmethic_coding(bytes, radix): freq = Counter(bytes) cf = cumulative_freq(freq) base = len(bytes) lower = 0 pf = 1 for b in bytes: lower = lower*base + cf[b]*pf pf *= freq[b] upper = lower+pf pow = 0 while True: pf //= radix if pf==0: break pow += 1 enc = (upper-1) // radix**pow return enc, pow, freq def arithmethic_decoding(enc, radix, pow, freq): enc *= radix**pow; base = sum(freq.values()) cf = cumulative_freq(freq) dict = {} for k,v in cf.items(): dict[v] = k lchar = None for i in range(base): if i in dict: lchar = dict[i] elif lchar is not None: dict[i] = lchar decoded = bytearray() for i in range(base-1, -1, -1): pow = base**i div = enc//pow c = dict[div] fv = freq[c] cv = cf[c] rem = (enc - pow*cv) // fv enc = rem decoded.append(c) return bytes(decoded) radix = 10 for str in b'DABDDB DABDDBBDDBA ABRACADABRA TOBEORNOTTOBEORTOBEORNOT'.split(): enc, pow, freq = arithmethic_coding(str, radix) dec = arithmethic_decoding(enc, radix, pow, freq) print("%-25s=> %19s * %d^%s" % (str, enc, radix, pow)) if str != dec: raise Exception("\tHowever that is incorrect!")
Translate the given VB code snippet into Python without altering its behavior.
Module Module1 Function Kosaraju(g As List(Of List(Of Integer))) As List(Of Integer) Dim size = g.Count Dim vis(size - 1) As Boolean Dim l(size - 1) As Integer Dim x = size Dim t As New List(Of List(Of Integer)) For i = 1 To size t.Add(New List(Of Integer)) Next Dim visit As Action(Of Integer) = Sub(u As Integer) If Not vis(u) Then vis(u) = True For Each v In g(u) visit(v) t(v).Add(u) Next x -= 1 l(x) = u End If End Sub For i = 1 To size visit(i - 1) Next Dim c(size - 1) As Integer Dim assign As Action(Of Integer, Integer) = Sub(u As Integer, root As Integer) If vis(u) Then vis(u) = False c(u) = root For Each v In t(u) assign(v, root) Next End If End Sub For Each u In l assign(u, u) Next Return c.ToList End Function Sub Main() Dim g = New List(Of List(Of Integer)) From { New List(Of Integer) From {1}, New List(Of Integer) From {2}, New List(Of Integer) From {0}, New List(Of Integer) From {1, 2, 4}, New List(Of Integer) From {3, 5}, New List(Of Integer) From {2, 6}, New List(Of Integer) From {5}, New List(Of Integer) From {4, 6, 7} } Dim output = Kosaraju(g) Console.WriteLine("[{0}]", String.Join(", ", output)) End Sub End Module
def kosaraju(g): class nonlocal: pass size = len(g) vis = [False]*size l = [0]*size nonlocal.x = size t = [[]]*size def visit(u): if not vis[u]: vis[u] = True for v in g[u]: visit(v) t[v] = t[v] + [u] nonlocal.x = nonlocal.x - 1 l[nonlocal.x] = u for u in range(len(g)): visit(u) c = [0]*size def assign(u, root): if vis[u]: vis[u] = False c[u] = root for v in t[u]: assign(v, root) for u in l: assign(u, u) return c g = [[1], [2], [0], [1,2,4], [3,5], [2,6], [5], [4,6,7]] print kosaraju(g)
Convert this VB snippet to Python and keep its semantics consistent.
Module Module1 Dim symbols As Char() = "XYPFTVNLUZWI█".ToCharArray(), nRows As Integer = 8, nCols As Integer = 8, target As Integer = 12, blank As Integer = 12, grid As Integer()() = New Integer(nRows - 1)() {}, placed As Boolean() = New Boolean(target - 1) {}, pens As List(Of List(Of Integer())), rand As Random, seeds As Integer() = {291, 292, 293, 295, 297, 329, 330, 332, 333, 335, 378, 586} Sub Main() Unpack(seeds) : rand = New Random() : ShuffleShapes(2) For r As Integer = 0 To nRows - 1 grid(r) = Enumerable.Repeat(-1, nCols).ToArray() : Next For i As Integer = 0 To 3 Dim rRow, rCol As Integer : Do : rRow = rand.Next(nRows) : rCol = rand.Next(nCols) Loop While grid(rRow)(rCol) = blank : grid(rRow)(rCol) = blank Next If Solve(0, 0) Then PrintResult() Else Console.WriteLine("no solution for this configuration:") : PrintResult() End If If System.Diagnostics.Debugger.IsAttached Then Console.ReadKey() End Sub Sub ShuffleShapes(count As Integer) For i As Integer = 0 To count : For j = 0 To pens.Count - 1 Dim r As Integer : Do : r = rand.Next(pens.Count) : Loop Until r <> j Dim tmp As List(Of Integer()) = pens(r) : pens(r) = pens(j) : pens(j) = tmp Dim ch As Char = symbols(r) : symbols(r) = symbols(j) : symbols(j) = ch Next : Next End Sub Sub PrintResult() For Each r As Integer() In grid : For Each i As Integer In r Console.Write("{0} ", If(i < 0, ".", symbols(i))) Next : Console.WriteLine() : Next End Sub Function Solve(ByVal pos As Integer, ByVal numPlaced As Integer) As Boolean If numPlaced = target Then Return True Dim row As Integer = pos \ nCols, col As Integer = pos Mod nCols If grid(row)(col) <> -1 Then Return Solve(pos + 1, numPlaced) For i As Integer = 0 To pens.Count - 1 : If Not placed(i) Then For Each orientation As Integer() In pens(i) If Not TPO(orientation, row, col, i) Then Continue For placed(i) = True : If Solve(pos + 1, numPlaced + 1) Then Return True RmvO(orientation, row, col) : placed(i) = False Next : End If : Next : Return False End Function Sub RmvO(ByVal ori As Integer(), ByVal row As Integer, ByVal col As Integer) grid(row)(col) = -1 : For i As Integer = 0 To ori.Length - 1 Step 2 grid(row + ori(i))(col + ori(i + 1)) = -1 : Next End Sub Function TPO(ByVal ori As Integer(), ByVal row As Integer, ByVal col As Integer, ByVal sIdx As Integer) As Boolean For i As Integer = 0 To ori.Length - 1 Step 2 Dim x As Integer = col + ori(i + 1), y As Integer = row + ori(i) If x < 0 OrElse x >= nCols OrElse y < 0 OrElse y >= nRows OrElse grid(y)(x) <> -1 Then Return False Next : grid(row)(col) = sIdx For i As Integer = 0 To ori.Length - 1 Step 2 grid(row + ori(i))(col + ori(i + 1)) = sIdx Next : Return True End Function Sub Unpack(sv As Integer()) pens = New List(Of List(Of Integer())) : For Each item In sv Dim Gen As New List(Of Integer()), exi As List(Of Integer) = Expand(item), fx As Integer() = ToP(exi) : Gen.Add(fx) : For i As Integer = 1 To 7 If i = 4 Then Mir(exi) Else Rot(exi) fx = ToP(exi) : If Not Gen.Exists(Function(Red) TheSame(Red, fx)) Then Gen.Add(ToP(exi)) Next : pens.Add(Gen) : Next End Sub Function Expand(i As Integer) As List(Of Integer) Expand = {0}.ToList() : For j As Integer = 0 To 3 : Expand.Insert(1, i And 15) : i >>= 4 : Next End Function Function ToP(p As List(Of Integer)) As Integer() Dim tmp As List(Of Integer) = {0}.ToList() : For Each item As Integer In p.Skip(1) tmp.Add(tmp.Item(item >> 2) + {1, 8, -1, -8}(item And 3)) : Next tmp.Sort() : For i As Integer = tmp.Count - 1 To 0 Step -1 : tmp.Item(i) -= tmp.Item(0) : Next Dim res As New List(Of Integer) : For Each item In tmp.Skip(1) Dim adj = If((item And 7) > 4, 8, 0) res.Add((adj + item) \ 8) : res.Add((item And 7) - adj) Next : Return res.ToArray() End Function Function TheSame(a As Integer(), b As Integer()) As Boolean For i As Integer = 0 To a.Count - 1 : If a(i) <> b(i) Then Return False Next : Return True End Function Sub Rot(ByRef p As List(Of Integer)) For i As Integer = 0 To p.Count - 1 : p(i) = (p(i) And -4) Or ((p(i) + 1) And 3) : Next End Sub Sub Mir(ByRef p As List(Of Integer)) For i As Integer = 0 To p.Count - 1 : p(i) = (p(i) And -4) Or (((p(i) Xor 1) + 1) And 3) : Next End Sub End Module
from itertools import product minos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)), ((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)), ((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)), ((131843, 7, 6), (1798, 6, 7), (775, 6, 7), (1795, 6, 7), (1543, 6, 7), (197377, 7, 6), (197378, 7, 6), (66307, 7, 6)), ((132865, 6, 6), (131846, 6, 6), (198146, 6, 6), (132611, 6, 6), (393986, 6, 6), (263938, 6, 6), (67330, 6, 6), (132868, 6, 6)), ((1039, 5, 7), (33751554, 7, 5), (16843521, 7, 5), (16974081, 7, 5), (33686274, 7, 5), (3842, 5, 7), (3844, 5, 7), (527, 5, 7)), ((1804, 5, 7), (33751297, 7, 5), (33686273, 7, 5), (16974338, 7, 5), (16843522, 7, 5), (782, 5, 7), (3079, 5, 7), (3587, 5, 7)), ((263683, 6, 6), (198148, 6, 6), (66310, 6, 6), (393985, 6, 6)), ((67329, 6, 6), (131591, 6, 6), (459266, 6, 6), (263940, 6, 6)), ((459780, 6, 6), (459009, 6, 6), (263175, 6, 6), (65799, 6, 6)), ((4311810305, 8, 4), (31, 4, 8)), ((132866, 6, 6),)) boxchar_double_width = ' ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋' boxchar_single_width = [c + ' ─━'[i%3] for i, c in enumerate(boxchar_double_width)] patterns = boxchar_single_width tiles = [] for row in reversed(minos): tiles.append([]) for n, x, y in row: for shift in (b*8 + a for a, b in product(range(x), range(y))): tiles[-1].append(n << shift) def img(seq): b = [[0]*10 for _ in range(10)] for i, s in enumerate(seq): for j, k in product(range(8), range(8)): if s & (1<<(j*8 + k)): b[j + 1][k + 1] = i + 1 idices = [[0]*9 for _ in range(9)] for i, j in product(range(9), range(9)): n = (b[i+1][j+1], b[i][j+1], b[i][j], b[i+1][j], b[i+1][j+1]) idices[i][j] = sum((a != b)*(1 + (not a or not b))*3**i for i, (a,b) in enumerate(zip(n, n[1:]))) return '\n'.join(''.join(patterns[i] for i in row) for row in idices) def tile(board=0, seq=tuple(), tiles=tiles): if not tiles: yield img(seq) return for c in tiles[0]: b = board | c tnext = [] for t in tiles[1:]: tnext.append(tuple(n for n in t if not n&b)) if not tnext[-1]: break else: yield from tile(b, seq + (c,), tnext) for x in tile(): print(x)
Rewrite this program in Python while keeping its functionality equivalent to the VB version.
Dim variable As datatype Dim var1,var2,... As datatype
example1 = 3 example2 = 3.0 example3 = True example4 = "hello" example1 = "goodbye"
Convert the following code from VB to Python, ensuring the logic remains intact.
Public Sub backup(filename As String) If Len(Dir(filename)) > 0 Then On Error Resume Next Name filename As filename & ".bak" Else If Len(Dir(filename & ".lnk")) > 0 Then On Error Resume Next With CreateObject("Wscript.Shell").CreateShortcut(filename & ".lnk") link = .TargetPath .Close End With Name link As link & ".bak" End If End If End Sub Public Sub main() backup "D:\test.txt" End Sub
import os targetfile = "pycon-china" os.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+".bak") f = open(os.path.realpath(targetfile), "w") f.write("this task was solved during a talk about rosettacode at the PyCon China in 2011") f.close()
Generate an equivalent Python version of this VB code.
Public Sub backup(filename As String) If Len(Dir(filename)) > 0 Then On Error Resume Next Name filename As filename & ".bak" Else If Len(Dir(filename & ".lnk")) > 0 Then On Error Resume Next With CreateObject("Wscript.Shell").CreateShortcut(filename & ".lnk") link = .TargetPath .Close End With Name link As link & ".bak" End If End If End Sub Public Sub main() backup "D:\test.txt" End Sub
import os targetfile = "pycon-china" os.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+".bak") f = open(os.path.realpath(targetfile), "w") f.write("this task was solved during a talk about rosettacode at the PyCon China in 2011") f.close()
Write the same code in Python as shown below in VB.
Imports System.Numerics Public Class BigRat Implements IComparable Public nu, de As BigInteger Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One), One = New BigRat(BigInteger.One, BigInteger.One) Sub New(bRat As BigRat) nu = bRat.nu : de = bRat.de End Sub Sub New(n As BigInteger, d As BigInteger) If d = BigInteger.Zero Then _ Throw (New Exception(String.Format("tried to set a BigRat with ({0}/{1})", n, d))) Dim bi As BigInteger = BigInteger.GreatestCommonDivisor(n, d) If bi > BigInteger.One Then n /= bi : d /= bi If d < BigInteger.Zero Then n = -n : d = -d nu = n : de = d End Sub Shared Operator -(x As BigRat) As BigRat Return New BigRat(-x.nu, x.de) End Operator Shared Operator +(x As BigRat, y As BigRat) Return New BigRat(x.nu * y.de + x.de * y.nu, x.de * y.de) End Operator Shared Operator -(x As BigRat, y As BigRat) As BigRat Return x + (-y) End Operator Shared Operator *(x As BigRat, y As BigRat) As BigRat Return New BigRat(x.nu * y.nu, x.de * y.de) End Operator Shared Operator /(x As BigRat, y As BigRat) As BigRat Return New BigRat(x.nu * y.de, x.de * y.nu) End Operator Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo Dim dif As BigRat = New BigRat(nu, de) - obj If dif.nu < BigInteger.Zero Then Return -1 If dif.nu > BigInteger.Zero Then Return 1 Return 0 End Function Shared Operator =(x As BigRat, y As BigRat) As Boolean Return x.CompareTo(y) = 0 End Operator Shared Operator <>(x As BigRat, y As BigRat) As Boolean Return x.CompareTo(y) <> 0 End Operator Overrides Function ToString() As String If de = BigInteger.One Then Return nu.ToString Return String.Format("({0}/{1})", nu, de) End Function Shared Function Combine(a As BigRat, b As BigRat) As BigRat Return (a + b) / (BigRat.One - (a * b)) End Function End Class Public Structure Term Dim c As Integer, br As BigRat Sub New(cc As Integer, bigr As BigRat) c = cc : br = bigr End Sub End Structure Module Module1 Function Eval(c As Integer, x As BigRat) As BigRat If c = 1 Then Return x Else If c < 0 Then Return Eval(-c, -x) Dim hc As Integer = c \ 2 Return BigRat.Combine(Eval(hc, x), Eval(c - hc, x)) End Function Function Sum(terms As List(Of Term)) As BigRat If terms.Count = 1 Then Return Eval(terms(0).c, terms(0).br) Dim htc As Integer = terms.Count / 2 Return BigRat.Combine(Sum(terms.Take(htc).ToList), Sum(terms.Skip(htc).ToList)) End Function Function ParseLine(ByVal s As String) As List(Of Term) ParseLine = New List(Of Term) : Dim t As String = s.ToLower, p As Integer, x As New Term(1, BigRat.Zero) While t.Contains(" ") : t = t.Replace(" ", "") : End While p = t.IndexOf("pi/4=") : If p < 0 Then _ Console.WriteLine("warning: tan(left side of equation) <> 1") : ParseLine.Add(x) : Exit Function t = t.Substring(p + 5) For Each item As String In t.Split(")") If item.Length > 5 Then If (Not item.Contains("tan") OrElse item.IndexOf("a") < 0 OrElse item.IndexOf("a") > item.IndexOf("tan")) AndAlso Not item.Contains("atn") Then Console.WriteLine("warning: a term is mising a valid arctangent identifier on the right side of the equation: [{0})]", item) ParseLine = New List(Of Term) : ParseLine.Add(New Term(1, BigRat.Zero)) : Exit Function End If x.c = 1 : x.br = New BigRat(BigRat.One) p = item.IndexOf("/") : If p > 0 Then x.br.de = UInt64.Parse(item.Substring(p + 1)) item = item.Substring(0, p) p = item.IndexOf("(") : If p > 0 Then x.br.nu = UInt64.Parse(item.Substring(p + 1)) p = item.IndexOf("a") : If p > 0 Then Integer.TryParse(item.Substring(0, p).Replace("*", ""), x.c) If x.c = 0 Then x.c = 1 If item.Contains("-") AndAlso x.c > 0 Then x.c = -x.c End If ParseLine.Add(x) End If End If End If Next End Function Sub Main(ByVal args As String()) Dim nl As String = vbLf For Each item In ("pi/4 = ATan(1 / 2) + ATan(1/3)" & nl & "pi/4 = 2Atan(1/3) + ATan(1/7)" & nl & "pi/4 = 4ArcTan(1/5) - ATan(1 / 239)" & nl & "pi/4 = 5arctan(1/7) + 2 * atan(3/79)" & nl & "Pi/4 = 5ATan(29/278) + 7*ATan(3/79)" & nl & "pi/4 = atn(1/2) + ATan(1/5) + ATan(1/8)" & nl & "PI/4 = 4ATan(1/5) - Atan(1/70) + ATan(1/99)" & nl & "pi /4 = 5*ATan(1/7) + 4 ATan(1/53) + 2ATan(1/4443)" & nl & "pi / 4 = 6ATan(1/8) + 2arctangent(1/57) + ATan(1/239)" & nl & "pi/ 4 = 8ATan(1/10) - ATan(1/239) - 4ATan(1/515)" & nl & "pi/4 = 12ATan(1/18) + 8ATan(1/57) - 5ATan(1/239)" & nl & "pi/4 = 16 * ATan(1/21) + 3ATan(1/239) + 4ATan(3/1042)" & nl & "pi/4 = 22ATan(1/28) + 2ATan(1/443) - 5ATan(1/1393) - 10 ATan( 1 / 11018 )" & nl & "pi/4 = 22ATan(1/38) + 17ATan(7/601) + 10ATan(7 / 8149)" & nl & "pi/4 = 44ATan(1/57) + 7ATan(1/239) - 12ATan(1/682) + 24ATan(1/12943)" & nl & "pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12943)" & nl & "pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12944)").Split(nl) Console.WriteLine("{0}: {1}", If(Sum(ParseLine(item)) = BigRat.One, "Pass", "Fail"), item) Next End Sub End Module
import re from fractions import Fraction from pprint import pprint as pp equationtext = def parse_eqn(equationtext=equationtext): eqn_re = re.compile(r) found = eqn_re.findall(equationtext) machins, part = [], [] for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext): if lhs and part: machins.append(part) part = [] part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1), Fraction(int(numer), (int(denom) if denom else 1)) ) ) machins.append(part) return machins def tans(xs): xslen = len(xs) if xslen == 1: return tanEval(*xs[0]) aa, bb = xs[:xslen//2], xs[xslen//2:] a, b = tans(aa), tans(bb) return (a + b) / (1 - a * b) def tanEval(coef, f): if coef == 1: return f if coef < 0: return -tanEval(-coef, f) ca = coef // 2 cb = coef - ca a, b = tanEval(ca, f), tanEval(cb, f) return (a + b) / (1 - a * b) if __name__ == '__main__': machins = parse_eqn() for machin, eqn in zip(machins, equationtext.split('\n')): ans = tans(machin) print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))
Preserve the algorithm and functionality while converting the code from VB to Python.
Imports System.Numerics Public Class BigRat Implements IComparable Public nu, de As BigInteger Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One), One = New BigRat(BigInteger.One, BigInteger.One) Sub New(bRat As BigRat) nu = bRat.nu : de = bRat.de End Sub Sub New(n As BigInteger, d As BigInteger) If d = BigInteger.Zero Then _ Throw (New Exception(String.Format("tried to set a BigRat with ({0}/{1})", n, d))) Dim bi As BigInteger = BigInteger.GreatestCommonDivisor(n, d) If bi > BigInteger.One Then n /= bi : d /= bi If d < BigInteger.Zero Then n = -n : d = -d nu = n : de = d End Sub Shared Operator -(x As BigRat) As BigRat Return New BigRat(-x.nu, x.de) End Operator Shared Operator +(x As BigRat, y As BigRat) Return New BigRat(x.nu * y.de + x.de * y.nu, x.de * y.de) End Operator Shared Operator -(x As BigRat, y As BigRat) As BigRat Return x + (-y) End Operator Shared Operator *(x As BigRat, y As BigRat) As BigRat Return New BigRat(x.nu * y.nu, x.de * y.de) End Operator Shared Operator /(x As BigRat, y As BigRat) As BigRat Return New BigRat(x.nu * y.de, x.de * y.nu) End Operator Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo Dim dif As BigRat = New BigRat(nu, de) - obj If dif.nu < BigInteger.Zero Then Return -1 If dif.nu > BigInteger.Zero Then Return 1 Return 0 End Function Shared Operator =(x As BigRat, y As BigRat) As Boolean Return x.CompareTo(y) = 0 End Operator Shared Operator <>(x As BigRat, y As BigRat) As Boolean Return x.CompareTo(y) <> 0 End Operator Overrides Function ToString() As String If de = BigInteger.One Then Return nu.ToString Return String.Format("({0}/{1})", nu, de) End Function Shared Function Combine(a As BigRat, b As BigRat) As BigRat Return (a + b) / (BigRat.One - (a * b)) End Function End Class Public Structure Term Dim c As Integer, br As BigRat Sub New(cc As Integer, bigr As BigRat) c = cc : br = bigr End Sub End Structure Module Module1 Function Eval(c As Integer, x As BigRat) As BigRat If c = 1 Then Return x Else If c < 0 Then Return Eval(-c, -x) Dim hc As Integer = c \ 2 Return BigRat.Combine(Eval(hc, x), Eval(c - hc, x)) End Function Function Sum(terms As List(Of Term)) As BigRat If terms.Count = 1 Then Return Eval(terms(0).c, terms(0).br) Dim htc As Integer = terms.Count / 2 Return BigRat.Combine(Sum(terms.Take(htc).ToList), Sum(terms.Skip(htc).ToList)) End Function Function ParseLine(ByVal s As String) As List(Of Term) ParseLine = New List(Of Term) : Dim t As String = s.ToLower, p As Integer, x As New Term(1, BigRat.Zero) While t.Contains(" ") : t = t.Replace(" ", "") : End While p = t.IndexOf("pi/4=") : If p < 0 Then _ Console.WriteLine("warning: tan(left side of equation) <> 1") : ParseLine.Add(x) : Exit Function t = t.Substring(p + 5) For Each item As String In t.Split(")") If item.Length > 5 Then If (Not item.Contains("tan") OrElse item.IndexOf("a") < 0 OrElse item.IndexOf("a") > item.IndexOf("tan")) AndAlso Not item.Contains("atn") Then Console.WriteLine("warning: a term is mising a valid arctangent identifier on the right side of the equation: [{0})]", item) ParseLine = New List(Of Term) : ParseLine.Add(New Term(1, BigRat.Zero)) : Exit Function End If x.c = 1 : x.br = New BigRat(BigRat.One) p = item.IndexOf("/") : If p > 0 Then x.br.de = UInt64.Parse(item.Substring(p + 1)) item = item.Substring(0, p) p = item.IndexOf("(") : If p > 0 Then x.br.nu = UInt64.Parse(item.Substring(p + 1)) p = item.IndexOf("a") : If p > 0 Then Integer.TryParse(item.Substring(0, p).Replace("*", ""), x.c) If x.c = 0 Then x.c = 1 If item.Contains("-") AndAlso x.c > 0 Then x.c = -x.c End If ParseLine.Add(x) End If End If End If Next End Function Sub Main(ByVal args As String()) Dim nl As String = vbLf For Each item In ("pi/4 = ATan(1 / 2) + ATan(1/3)" & nl & "pi/4 = 2Atan(1/3) + ATan(1/7)" & nl & "pi/4 = 4ArcTan(1/5) - ATan(1 / 239)" & nl & "pi/4 = 5arctan(1/7) + 2 * atan(3/79)" & nl & "Pi/4 = 5ATan(29/278) + 7*ATan(3/79)" & nl & "pi/4 = atn(1/2) + ATan(1/5) + ATan(1/8)" & nl & "PI/4 = 4ATan(1/5) - Atan(1/70) + ATan(1/99)" & nl & "pi /4 = 5*ATan(1/7) + 4 ATan(1/53) + 2ATan(1/4443)" & nl & "pi / 4 = 6ATan(1/8) + 2arctangent(1/57) + ATan(1/239)" & nl & "pi/ 4 = 8ATan(1/10) - ATan(1/239) - 4ATan(1/515)" & nl & "pi/4 = 12ATan(1/18) + 8ATan(1/57) - 5ATan(1/239)" & nl & "pi/4 = 16 * ATan(1/21) + 3ATan(1/239) + 4ATan(3/1042)" & nl & "pi/4 = 22ATan(1/28) + 2ATan(1/443) - 5ATan(1/1393) - 10 ATan( 1 / 11018 )" & nl & "pi/4 = 22ATan(1/38) + 17ATan(7/601) + 10ATan(7 / 8149)" & nl & "pi/4 = 44ATan(1/57) + 7ATan(1/239) - 12ATan(1/682) + 24ATan(1/12943)" & nl & "pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12943)" & nl & "pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12944)").Split(nl) Console.WriteLine("{0}: {1}", If(Sum(ParseLine(item)) = BigRat.One, "Pass", "Fail"), item) Next End Sub End Module
import re from fractions import Fraction from pprint import pprint as pp equationtext = def parse_eqn(equationtext=equationtext): eqn_re = re.compile(r) found = eqn_re.findall(equationtext) machins, part = [], [] for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext): if lhs and part: machins.append(part) part = [] part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1), Fraction(int(numer), (int(denom) if denom else 1)) ) ) machins.append(part) return machins def tans(xs): xslen = len(xs) if xslen == 1: return tanEval(*xs[0]) aa, bb = xs[:xslen//2], xs[xslen//2:] a, b = tans(aa), tans(bb) return (a + b) / (1 - a * b) def tanEval(coef, f): if coef == 1: return f if coef < 0: return -tanEval(-coef, f) ca = coef // 2 cb = coef - ca a, b = tanEval(ca, f), tanEval(cb, f) return (a + b) / (1 - a * b) if __name__ == '__main__': machins = parse_eqn() for machin, eqn in zip(machins, equationtext.split('\n')): ans = tans(machin) print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))
Write a version of this VB function in Python with identical behavior.
Imports System, Microsoft.VisualBasic.DateAndTime Public Module Module1 Const n As Integer = 5 Dim Board As String Dim Starting As Integer = 1 Dim Target As Integer = 13 Dim Moves As Integer() Dim bi() As Integer Dim ib() As Integer Dim nl As Char = Convert.ToChar(10) Public Function Dou(s As String) As String Dou = "" : Dim b As Boolean = True For Each ch As Char In s If b Then b = ch <> " " If b Then Dou &= ch & " " Else Dou = " " & Dou Next : Dou = Dou.TrimEnd() End Function Public Function Fmt(s As String) As String If s.Length < Board.Length Then Return s Fmt = "" : For i As Integer = 1 To n : Fmt &= Dou(s.Substring(i * n - n, n)) & If(i = n, s.Substring(Board.Length), "") & nl Next End Function Public Function Triangle(n As Integer) As Integer Return (n * (n + 1)) / 2 End Function Public Function Init(s As String, pos As Integer) As String Init = s : Mid(Init, pos, 1) = "0" End Function Public Sub InitIndex() ReDim bi(Triangle(n)), ib(n * n) : Dim j As Integer = 0 For i As Integer = 0 To ib.Length - 1 If i = 0 Then ib(i) = 0 : bi(j) = 0 : j += 1 Else If Board(i - 1) = "1" Then ib(i) = j : bi(j) = i : j += 1 End If Next End Sub Public Function solve(brd As String, pegsLeft As Integer) As String If pegsLeft = 1 Then If Target = 0 Then Return "Completed" If brd(bi(Target) - 1) = "1" Then Return "Completed" Else Return "fail" End If For i = 1 To Board.Length If brd(i - 1) = "1" Then For Each mj In Moves Dim over As Integer = i + mj Dim land As Integer = i + 2 * mj If land >= 1 AndAlso land <= brd.Length _ AndAlso brd(land - 1) = "0" _ AndAlso brd(over - 1) = "1" Then setPegs(brd, "001", i, over, land) Dim Res As String = solve(brd.Substring(0, Board.Length), pegsLeft - 1) If Res.Length <> 4 Then _ Return brd & info(i, over, land) & nl & Res setPegs(brd, "110", i, over, land) End If Next End If Next Return "fail" End Function Function info(frm As Integer, over As Integer, dest As Integer) As String Return " Peg from " & ib(frm).ToString() & " goes to " & ib(dest).ToString() & ", removing peg at " & ib(over).ToString() End Function Sub setPegs(ByRef board As String, pat As String, a As Integer, b As Integer, c As Integer) Mid(board, a, 1) = pat(0) : Mid(board, b, 1) = pat(1) : Mid(board, c, 1) = pat(2) End Sub Sub LimitIt(ByRef x As Integer, lo As Integer, hi As Integer) x = Math.Max(Math.Min(x, hi), lo) End Sub Public Sub Main() Dim t As Integer = Triangle(n) LimitIt(Starting, 1, t) LimitIt(Target, 0, t) Dim stime As Date = Now() Moves = {-n - 1, -n, -1, 1, n, n + 1} Board = New String("1", n * n) For i As Integer = 0 To n - 2 Mid(Board, i * (n + 1) + 2, n - 1 - i) = New String(" ", n - 1 - i) Next InitIndex() Dim B As String = Init(Board, bi(Starting)) Console.WriteLine(Fmt(B & " Starting with peg removed from " & Starting.ToString())) Dim res As String() = solve(B.Substring(0, B.Length), t - 1).Split(nl) Dim ts As String = (Now() - stime).TotalMilliseconds.ToString() & " ms." If res(0).Length = 4 Then If Target = 0 Then Console.WriteLine("Unable to find a solution with last peg left anywhere.") Else Console.WriteLine("Unable to find a solution with last peg left at " & Target.ToString() & ".") End If Console.WriteLine("Computation time: " & ts) Else For Each Sol As String In res : Console.WriteLine(Fmt(Sol)) : Next Console.WriteLine("Computation time to first found solution: " & ts) End If If Diagnostics.Debugger.IsAttached Then Console.ReadLine() End Sub End Module
def DrawBoard(board): peg = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] for n in xrange(1,16): peg[n] = '.' if n in board: peg[n] = "%X" % n print " %s" % peg[1] print " %s %s" % (peg[2],peg[3]) print " %s %s %s" % (peg[4],peg[5],peg[6]) print " %s %s %s %s" % (peg[7],peg[8],peg[9],peg[10]) print " %s %s %s %s %s" % (peg[11],peg[12],peg[13],peg[14],peg[15]) def RemovePeg(board,n): board.remove(n) def AddPeg(board,n): board.append(n) def IsPeg(board,n): return n in board JumpMoves = { 1: [ (2,4),(3,6) ], 2: [ (4,7),(5,9) ], 3: [ (5,8),(6,10) ], 4: [ (2,1),(5,6),(7,11),(8,13) ], 5: [ (8,12),(9,14) ], 6: [ (3,1),(5,4),(9,13),(10,15) ], 7: [ (4,2),(8,9) ], 8: [ (5,3),(9,10) ], 9: [ (5,2),(8,7) ], 10: [ (9,8) ], 11: [ (12,13) ], 12: [ (8,5),(13,14) ], 13: [ (8,4),(9,6),(12,11),(14,15) ], 14: [ (9,5),(13,12) ], 15: [ (10,6),(14,13) ] } Solution = [] def Solve(board): if len(board) == 1: return board for peg in xrange(1,16): if IsPeg(board,peg): movelist = JumpMoves[peg] for over,land in movelist: if IsPeg(board,over) and not IsPeg(board,land): saveboard = board[:] RemovePeg(board,peg) RemovePeg(board,over) AddPeg(board,land) Solution.append((peg,over,land)) board = Solve(board) if len(board) == 1: return board board = saveboard[:] del Solution[-1] return board def InitSolve(empty): board = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] RemovePeg(board,empty_start) Solve(board) empty_start = 1 InitSolve(empty_start) board = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] RemovePeg(board,empty_start) for peg,over,land in Solution: RemovePeg(board,peg) RemovePeg(board,over) AddPeg(board,land) DrawBoard(board) print "Peg %X jumped over %X to land on %X\n" % (peg,over,land)
Port the following code from VB to Python with equivalent syntax and logic.
Public s As String Public t As Integer Function s1() s1 = Len(s) = 12 End Function Function s2() t = 0 For i = 7 To 12 t = t - (Mid(s, i, 1) = "1") Next i s2 = t = 3 End Function Function s3() t = 0 For i = 2 To 12 Step 2 t = t - (Mid(s, i, 1) = "1") Next i s3 = t = 2 End Function Function s4() s4 = Mid(s, 5, 1) = "0" Or ((Mid(s, 6, 1) = "1" And Mid(s, 7, 1) = "1")) End Function Function s5() s5 = Mid(s, 2, 1) = "0" And Mid(s, 3, 1) = "0" And Mid(s, 4, 1) = "0" End Function Function s6() t = 0 For i = 1 To 12 Step 2 t = t - (Mid(s, i, 1) = "1") Next i s6 = t = 4 End Function Function s7() s7 = Mid(s, 2, 1) <> Mid(s, 3, 1) End Function Function s8() s8 = Mid(s, 7, 1) = "0" Or (Mid(s, 5, 1) = "1" And Mid(s, 6, 1) = "1") End Function Function s9() t = 0 For i = 1 To 6 t = t - (Mid(s, i, 1) = "1") Next i s9 = t = 3 End Function Function s10() s10 = Mid(s, 11, 1) = "1" And Mid(s, 12, 1) = "1" End Function Function s11() t = 0 For i = 7 To 9 t = t - (Mid(s, i, 1) = "1") Next i s11 = t = 1 End Function Function s12() t = 0 For i = 1 To 11 t = t - (Mid(s, i, 1) = "1") Next i s12 = t = 4 End Function Public Sub twelve_statements() For i = 0 To 2 ^ 12 - 1 s = Right(CStr(WorksheetFunction.Dec2Bin(64 + i \ 128)), 5) _ & Right(CStr(WorksheetFunction.Dec2Bin(256 + i Mod 128)), 7) For b = 1 To 12 Select Case b Case 1: If s1 <> (Mid(s, b, 1) = "1") Then Exit For Case 2: If s2 <> (Mid(s, b, 1) = "1") Then Exit For Case 3: If s3 <> (Mid(s, b, 1) = "1") Then Exit For Case 4: If s4 <> (Mid(s, b, 1) = "1") Then Exit For Case 5: If s5 <> (Mid(s, b, 1) = "1") Then Exit For Case 6: If s6 <> (Mid(s, b, 1) = "1") Then Exit For Case 7: If s7 <> (Mid(s, b, 1) = "1") Then Exit For Case 8: If s8 <> (Mid(s, b, 1) = "1") Then Exit For Case 9: If s9 <> (Mid(s, b, 1) = "1") Then Exit For Case 10: If s10 <> (Mid(s, b, 1) = "1") Then Exit For Case 11: If s11 <> (Mid(s, b, 1) = "1") Then Exit For Case 12: If s12 <> (Mid(s, b, 1) = "1") Then Exit For End Select If b = 12 Then Debug.Print s Next Next End Sub
from itertools import product constraintinfo = ( (lambda st: len(st) == 12 ,(1, 'This is a numbered list of twelve statements')), (lambda st: sum(st[-6:]) == 3 ,(2, 'Exactly 3 of the last 6 statements are true')), (lambda st: sum(st[1::2]) == 2 ,(3, 'Exactly 2 of the even-numbered statements are true')), (lambda st: (st[5]&st[6]) if st[4] else 1 ,(4, 'If statement 5 is true, then statements 6 and 7 are both true')), (lambda st: sum(st[1:4]) == 0 ,(5, 'The 3 preceding statements are all false')), (lambda st: sum(st[0::2]) == 4 ,(6, 'Exactly 4 of the odd-numbered statements are true')), (lambda st: sum(st[1:3]) == 1 ,(7, 'Either statement 2 or 3 is true, but not both')), (lambda st: (st[4]&st[5]) if st[6] else 1 ,(8, 'If statement 7 is true, then 5 and 6 are both true')), (lambda st: sum(st[:6]) == 3 ,(9, 'Exactly 3 of the first 6 statements are true')), (lambda st: (st[10]&st[11]) ,(10, 'The next two statements are both true')), (lambda st: sum(st[6:9]) == 1 ,(11, 'Exactly 1 of statements 7, 8 and 9 are true')), (lambda st: sum(st[0:11]) == 4 ,(12, 'Exactly 4 of the preceding statements are true')), ) def printer(st, matches): if False in matches: print('Missed by one statement: %i, %s' % docs[matches.index(False)]) else: print('Full match:') print(' ' + ', '.join('%i:%s' % (i, 'T' if t else 'F') for i, t in enumerate(st, 1))) funcs, docs = zip(*constraintinfo) full, partial = [], [] for st in product( *([(False, True)] * 12) ): truths = [bool(func(st)) for func in funcs] matches = [s == t for s,t in zip(st, truths)] mcount = sum(matches) if mcount == 12: full.append((st, matches)) elif mcount == 11: partial.append((st, matches)) for stm in full + partial: printer(*stm)
Convert this VB snippet to Python and keep its semantics consistent.
Private Function suffize(number As String, Optional sfractiondigits As String, Optional base As String) As String Dim suffix As String, parts() As String, exponent As String Dim fractiondigits As Integer, nsuffix As Integer, flag As Boolean flag = False fractiondigits = Val(sfractiondigits) suffixes = " KMGTPEZYXWVU" number = Replace(number, ",", "", 1) Dim c As Currency Dim sign As Integer If Left(number, 1) = "-" Then number = Right(number, Len(number) - 1) outstring = "-" End If If Left(number, 1) = "+" Then number = Right(number, Len(number) - 1) outstring = "+" End If parts = Split(number, "e") number = parts(0) If UBound(parts) > 0 Then exponent = parts(1) parts = Split(number, ".") number = parts(0) If UBound(parts) > 0 Then frac = parts(1) If base = "2" Then Dim cnumber As Currency cnumber = Val(number) nsuffix = 0 Dim dnumber As Double If cnumber > 1023 Then cnumber = cnumber / 1024@ nsuffix = nsuffix + 1 dnumber = cnumber Do While dnumber > 1023 dnumber = dnumber / 1024@ nsuffix = nsuffix + 1 Loop number = CStr(dnumber) Else number = CStr(cnumber) End If leadingstring = Int(number) number = Replace(number, ",", "") leading = Len(leadingstring) suffix = Mid(suffixes, nsuffix + 1, 1) Else nsuffix = (Len(number) + Val(exponent) - 1) \ 3 If nsuffix < 13 Then suffix = Mid(suffixes, nsuffix + 1, 1) leading = (Len(number) - 1) Mod 3 + 1 leadingstring = Left(number, leading) Else flag = True If nsuffix > 32 Then suffix = "googol" leading = Len(number) + Val(exponent) - 99 leadingstring = number & frac & String$(Val(exponent) - 100 - Len(frac), "0") Else suffix = "U" leading = Len(number) + Val(exponent) - 35 If Val(exponent) > 36 Then leadingstring = number & String$(Val(exponent) - 36, "0") Else leadingstring = Left(number, (Len(number) - 36 + Val(exponent))) End If End If End If End If If fractiondigits > 0 Then If Val(Mid(number, leading + fractiondigits + 1, 1)) >= 5 Then fraction = Mid(number, leading + 1, fractiondigits - 1) & _ CStr(Val(Mid(number, leading + fractiondigits, 1)) + 1) Else fraction = Mid(number, leading + 1, fractiondigits) End If Else If Val(Mid(number, leading + 1, 1)) >= 5 And sfractiondigits <> "" And sfractiondigits <> "," Then leadingstring = Mid(number, 1, leading - 1) & _ CStr(Val(Mid(number, leading, 1)) + 1) End If End If If flag Then If sfractiondigits = "" Or sfractiondigits = "," Then fraction = "" End If Else If sfractiondigits = "" Or sfractiondigits = "," Then fraction = Right(number, Len(number) - leading) End If End If outstring = outstring & leadingstring If Len(fraction) > 0 Then outstring = outstring & "." & fraction End If If base = "2" Then outstring = outstring & suffix & "i" Else outstring = outstring & suffix End If suffize = outstring End Function Sub program() Dim s(10) As String, t As String, f As String, r As String Dim tt() As String, temp As String s(0) = " 87,654,321" s(1) = " -998,877,665,544,332,211,000 3" s(2) = " +112,233 0" s(3) = " 16,777,216 1" s(4) = " 456,789,100,000,000 2" s(5) = " 456,789,100,000,000 2 10" s(6) = " 456,789,100,000,000 5 2" s(7) = " 456,789,100,000.000e+00 0 10" s(8) = " +16777216 , 2" s(9) = " 1.2e101" For i = 0 To 9 ReDim tt(0) t = Trim(s(i)) Do temp = t t = Replace(t, " ", " ") Loop Until temp = t tt = Split(t, " ") If UBound(tt) > 0 Then f = tt(1) Else f = "" If UBound(tt) > 1 Then r = tt(2) Else r = "" Debug.Print String$(48, "-") Debug.Print " input number = "; tt(0) Debug.Print " fraction digs = "; f Debug.Print " specified radix = "; r Debug.Print " new number = "; suffize(tt(0), f, r) Next i End Sub
import math import os def suffize(num, digits=None, base=10): suffixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'X', 'W', 'V', 'U', 'googol'] exponent_distance = 10 if base == 2 else 3 num = num.strip().replace(',', '') num_sign = num[0] if num[0] in '+-' else '' num = abs(float(num)) if base == 10 and num >= 1e100: suffix_index = 13 num /= 1e100 elif num > 1: magnitude = math.floor(math.log(num, base)) suffix_index = min(math.floor(magnitude / exponent_distance), 12) num /= base ** (exponent_distance * suffix_index) else: suffix_index = 0 if digits is not None: num_str = f'{num:.{digits}f}' else: num_str = f'{num:.3f}'.strip('0').strip('.') return num_sign + num_str + suffixes[suffix_index] + ('i' if base == 2 else '') tests = [('87,654,321',), ('-998,877,665,544,332,211,000', 3), ('+112,233', 0), ('16,777,216', 1), ('456,789,100,000,000', 2), ('456,789,100,000,000', 2, 10), ('456,789,100,000,000', 5, 2), ('456,789,100,000.000e+00', 0, 10), ('+16777216', None, 2), ('1.2e101',)] for test in tests: print(' '.join(str(i) for i in test) + ' : ' + suffize(*test))
Generate an equivalent Python version of this VB code.
Private Function suffize(number As String, Optional sfractiondigits As String, Optional base As String) As String Dim suffix As String, parts() As String, exponent As String Dim fractiondigits As Integer, nsuffix As Integer, flag As Boolean flag = False fractiondigits = Val(sfractiondigits) suffixes = " KMGTPEZYXWVU" number = Replace(number, ",", "", 1) Dim c As Currency Dim sign As Integer If Left(number, 1) = "-" Then number = Right(number, Len(number) - 1) outstring = "-" End If If Left(number, 1) = "+" Then number = Right(number, Len(number) - 1) outstring = "+" End If parts = Split(number, "e") number = parts(0) If UBound(parts) > 0 Then exponent = parts(1) parts = Split(number, ".") number = parts(0) If UBound(parts) > 0 Then frac = parts(1) If base = "2" Then Dim cnumber As Currency cnumber = Val(number) nsuffix = 0 Dim dnumber As Double If cnumber > 1023 Then cnumber = cnumber / 1024@ nsuffix = nsuffix + 1 dnumber = cnumber Do While dnumber > 1023 dnumber = dnumber / 1024@ nsuffix = nsuffix + 1 Loop number = CStr(dnumber) Else number = CStr(cnumber) End If leadingstring = Int(number) number = Replace(number, ",", "") leading = Len(leadingstring) suffix = Mid(suffixes, nsuffix + 1, 1) Else nsuffix = (Len(number) + Val(exponent) - 1) \ 3 If nsuffix < 13 Then suffix = Mid(suffixes, nsuffix + 1, 1) leading = (Len(number) - 1) Mod 3 + 1 leadingstring = Left(number, leading) Else flag = True If nsuffix > 32 Then suffix = "googol" leading = Len(number) + Val(exponent) - 99 leadingstring = number & frac & String$(Val(exponent) - 100 - Len(frac), "0") Else suffix = "U" leading = Len(number) + Val(exponent) - 35 If Val(exponent) > 36 Then leadingstring = number & String$(Val(exponent) - 36, "0") Else leadingstring = Left(number, (Len(number) - 36 + Val(exponent))) End If End If End If End If If fractiondigits > 0 Then If Val(Mid(number, leading + fractiondigits + 1, 1)) >= 5 Then fraction = Mid(number, leading + 1, fractiondigits - 1) & _ CStr(Val(Mid(number, leading + fractiondigits, 1)) + 1) Else fraction = Mid(number, leading + 1, fractiondigits) End If Else If Val(Mid(number, leading + 1, 1)) >= 5 And sfractiondigits <> "" And sfractiondigits <> "," Then leadingstring = Mid(number, 1, leading - 1) & _ CStr(Val(Mid(number, leading, 1)) + 1) End If End If If flag Then If sfractiondigits = "" Or sfractiondigits = "," Then fraction = "" End If Else If sfractiondigits = "" Or sfractiondigits = "," Then fraction = Right(number, Len(number) - leading) End If End If outstring = outstring & leadingstring If Len(fraction) > 0 Then outstring = outstring & "." & fraction End If If base = "2" Then outstring = outstring & suffix & "i" Else outstring = outstring & suffix End If suffize = outstring End Function Sub program() Dim s(10) As String, t As String, f As String, r As String Dim tt() As String, temp As String s(0) = " 87,654,321" s(1) = " -998,877,665,544,332,211,000 3" s(2) = " +112,233 0" s(3) = " 16,777,216 1" s(4) = " 456,789,100,000,000 2" s(5) = " 456,789,100,000,000 2 10" s(6) = " 456,789,100,000,000 5 2" s(7) = " 456,789,100,000.000e+00 0 10" s(8) = " +16777216 , 2" s(9) = " 1.2e101" For i = 0 To 9 ReDim tt(0) t = Trim(s(i)) Do temp = t t = Replace(t, " ", " ") Loop Until temp = t tt = Split(t, " ") If UBound(tt) > 0 Then f = tt(1) Else f = "" If UBound(tt) > 1 Then r = tt(2) Else r = "" Debug.Print String$(48, "-") Debug.Print " input number = "; tt(0) Debug.Print " fraction digs = "; f Debug.Print " specified radix = "; r Debug.Print " new number = "; suffize(tt(0), f, r) Next i End Sub
import math import os def suffize(num, digits=None, base=10): suffixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'X', 'W', 'V', 'U', 'googol'] exponent_distance = 10 if base == 2 else 3 num = num.strip().replace(',', '') num_sign = num[0] if num[0] in '+-' else '' num = abs(float(num)) if base == 10 and num >= 1e100: suffix_index = 13 num /= 1e100 elif num > 1: magnitude = math.floor(math.log(num, base)) suffix_index = min(math.floor(magnitude / exponent_distance), 12) num /= base ** (exponent_distance * suffix_index) else: suffix_index = 0 if digits is not None: num_str = f'{num:.{digits}f}' else: num_str = f'{num:.3f}'.strip('0').strip('.') return num_sign + num_str + suffixes[suffix_index] + ('i' if base == 2 else '') tests = [('87,654,321',), ('-998,877,665,544,332,211,000', 3), ('+112,233', 0), ('16,777,216', 1), ('456,789,100,000,000', 2), ('456,789,100,000,000', 2, 10), ('456,789,100,000,000', 5, 2), ('456,789,100,000.000e+00', 0, 10), ('+16777216', None, 2), ('1.2e101',)] for test in tests: print(' '.join(str(i) for i in test) + ' : ' + suffize(*test))
Write a version of this VB function in Python with identical behavior.
Public Sub test() Dim t(2) As Variant t(0) = [{1,2}] t(1) = [{3,4,1}] t(2) = 5 p = [{"Payload#0","Payload#1","Payload#2","Payload#3","Payload#4","Payload#5","Payload#6"}] Dim q(6) As Boolean For i = LBound(t) To UBound(t) If IsArray(t(i)) Then For j = LBound(t(i)) To UBound(t(i)) q(t(i)(j)) = True t(i)(j) = p(t(i)(j) + 1) Next j Else q(t(i)) = True t(i) = p(t(i) + 1) End If Next i For i = LBound(t) To UBound(t) If IsArray(t(i)) Then Debug.Print Join(t(i), ", ") Else Debug.Print t(i) End If Next i For i = LBound(q) To UBound(q) If Not q(i) Then Debug.Print p(i + 1); " is not used" Next i End Sub
from pprint import pprint as pp class Template(): def __init__(self, structure): self.structure = structure self.used_payloads, self.missed_payloads = [], [] def inject_payload(self, id2data): def _inject_payload(substruct, i2d, used, missed): used.extend(i2d[x] for x in substruct if type(x) is not tuple and x in i2d) missed.extend(f'?? for x in substruct if type(x) is not tuple and x not in i2d) return tuple(_inject_payload(x, i2d, used, missed) if type(x) is tuple else i2d.get(x, f'?? for x in substruct) ans = _inject_payload(self.structure, id2data, self.used_payloads, self.missed_payloads) self.unused_payloads = sorted(set(id2data.values()) - set(self.used_payloads)) self.missed_payloads = sorted(set(self.missed_payloads)) return ans if __name__ == '__main__': index2data = {p: f'Payload print(" print('\n '.join(list(index2data.values()))) for structure in [ (((1, 2), (3, 4, 1), 5),), (((1, 2), (10, 4, 1), 5),)]: print("\n\n pp(structure, width=13) print("\n TEMPLATE WITH PAYLOADS:") t = Template(structure) out = t.inject_payload(index2data) pp(out) print("\n UNUSED PAYLOADS:\n ", end='') unused = t.unused_payloads print('\n '.join(unused) if unused else '-') print(" MISSING PAYLOADS:\n ", end='') missed = t.missed_payloads print('\n '.join(missed) if missed else '-')
Change the programming language of this snippet from VB to Python without modifying what it does.
Dim n As Integer, c As Integer Dim a() As Integer Private Sub Command1_Click() Dim res As Integer If c < n Then Label3.Caption = "Please input completely.": Exit Sub res = getLantern(a()) Label3.Caption = "Result:" + Str(res) End Sub Private Sub Text1_Change() If Val(Text1.Text) <> 0 Then n = Val(Text1.Text) ReDim a(1 To n) As Integer End If End Sub Private Sub Text2_KeyPress(KeyAscii As Integer) If KeyAscii = Asc(vbCr) Then If Val(Text2.Text) = 0 Then Exit Sub c = c + 1 If c > n Then Exit Sub a(c) = Val(Text2.Text) List1.AddItem Str(a(c)) Text2.Text = "" End If End Sub Function getLantern(arr() As Integer) As Integer Dim res As Integer, i As Integer For i = 1 To n If arr(i) <> 0 Then arr(i) = arr(i) - 1 res = res + getLantern(arr()) arr(i) = arr(i) + 1 End If Next i If res = 0 Then res = 1 getLantern = res End Function
def getLantern(arr): res = 0 for i in range(0, n): if arr[i] != 0: arr[i] -= 1 res += getLantern(arr) arr[i] += 1 if res == 0: res = 1 return res a = [] n = int(input()) for i in range(0, n): a.append(int(input())) print(getLantern(a))
Please provide an equivalent version of this VB code in C#.
nx=15 h=1000 Wscript.StdOut.WriteLine "Recaman Wscript.StdOut.WriteLine recaman("seq",nx) Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0) Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h) Wscript.StdOut.Write vbCrlf&".../...": zz=Wscript.StdIn.ReadLine() function recaman(op,nn) Dim b,d,h Set b = CreateObject("Scripting.Dictionary") Set d = CreateObject("Scripting.Dictionary") list="0" : firstdup=0 if op="firstdup" then nn=1000 : firstdup=1 end if if op="numterm" then h=nn : nn=10000000 : numterm=1 end if ax=0 b.Add 0,1 s=0 for n=1 to nn-1 an=ax-n if an<=0 then an=ax+n elseif b.Exists(an) then an=ax+n end if ax=an if not b.Exists(an) then b.Add an,1 if op="seq" then list=list&" "&an end if if firstdup then if d.Exists(an) then recaman="a("&n&")="&an exit function else d.Add an,1 end if end if if numterm then if an<=h then if not d.Exists(an) then s=s+1 d.Add an,1 end if if s>=h then recaman=n exit function end if end if end if next recaman=list end function
using System; using System.Collections.Generic; namespace RecamanSequence { class Program { static void Main(string[] args) { List<int> a = new List<int>() { 0 }; HashSet<int> used = new HashSet<int>() { 0 }; HashSet<int> used1000 = new HashSet<int>() { 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.Count < 1001) { int next = a[n - 1] - n; if (next < 1 || used.Contains(next)) { next += 2 * n; } bool alreadyUsed = used.Contains(next); a.Add(next); if (!alreadyUsed) { used.Add(next); if (0 <= next && next <= 1000) { used1000.Add(next); } } if (n == 14) { Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a)); } if (!foundDup && alreadyUsed) { Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next); foundDup = true; } if (used1000.Count == 1001) { Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n); } n++; } } } }
Translate this program into C# but keep the logic exactly as in VB.
Option Explicit Private Lines(1 To 3, 1 To 3) As String Private Nb As Byte, player As Byte Private GameWin As Boolean, GameOver As Boolean Sub Main_TicTacToe() Dim p As String InitLines printLines Nb Do p = WhoPlay Debug.Print p & " play" If p = "Human" Then Call HumanPlay GameWin = IsWinner("X") Else Call ComputerPlay GameWin = IsWinner("O") End If If Not GameWin Then GameOver = IsEnd Loop Until GameWin Or GameOver If Not GameOver Then Debug.Print p & " Win !" Else Debug.Print "Game Over!" End If End Sub Sub InitLines(Optional S As String) Dim i As Byte, j As Byte Nb = 0: player = 0 For i = LBound(Lines, 1) To UBound(Lines, 1) For j = LBound(Lines, 2) To UBound(Lines, 2) Lines(i, j) = "#" Next j Next i End Sub Sub printLines(Nb As Byte) Dim i As Byte, j As Byte, strT As String Debug.Print "Loop " & Nb For i = LBound(Lines, 1) To UBound(Lines, 1) For j = LBound(Lines, 2) To UBound(Lines, 2) strT = strT & Lines(i, j) Next j Debug.Print strT strT = vbNullString Next i End Sub Function WhoPlay(Optional S As String) As String If player = 0 Then player = 1 WhoPlay = "Human" Else player = 0 WhoPlay = "Computer" End If End Function Sub HumanPlay(Optional S As String) Dim L As Byte, C As Byte, GoodPlay As Boolean Do L = Application.InputBox("Choose the row", "Numeric only", Type:=1) If L > 0 And L < 4 Then C = Application.InputBox("Choose the column", "Numeric only", Type:=1) If C > 0 And C < 4 Then If Lines(L, C) = "#" And Not Lines(L, C) = "X" And Not Lines(L, C) = "O" Then Lines(L, C) = "X" Nb = Nb + 1 printLines Nb GoodPlay = True End If End If End If Loop Until GoodPlay End Sub Sub ComputerPlay(Optional S As String) Dim L As Byte, C As Byte, GoodPlay As Boolean Randomize Timer Do L = Int((Rnd * 3) + 1) C = Int((Rnd * 3) + 1) If Lines(L, C) = "#" And Not Lines(L, C) = "X" And Not Lines(L, C) = "O" Then Lines(L, C) = "O" Nb = Nb + 1 printLines Nb GoodPlay = True End If Loop Until GoodPlay End Sub Function IsWinner(S As String) As Boolean Dim i As Byte, j As Byte, Ch As String, strTL As String, strTC As String Ch = String(UBound(Lines, 1), S) For i = LBound(Lines, 1) To UBound(Lines, 1) For j = LBound(Lines, 2) To UBound(Lines, 2) strTL = strTL & Lines(i, j) strTC = strTC & Lines(j, i) Next j If strTL = Ch Or strTC = Ch Then IsWinner = True: Exit For strTL = vbNullString: strTC = vbNullString Next i strTL = Lines(1, 1) & Lines(2, 2) & Lines(3, 3) strTC = Lines(1, 3) & Lines(2, 2) & Lines(3, 1) If strTL = Ch Or strTC = Ch Then IsWinner = True End Function Function IsEnd() As Boolean Dim i As Byte, j As Byte For i = LBound(Lines, 1) To UBound(Lines, 1) For j = LBound(Lines, 2) To UBound(Lines, 2) If Lines(i, j) = "#" Then Exit Function Next j Next i IsEnd = True End Function
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RosettaTicTacToe { class Program { static string[][] Players = new string[][] { new string[] { "COMPUTER", "X" }, new string[] { "HUMAN", "O" } }; const int Unplayed = -1; const int Computer = 0; const int Human = 1; static int[] GameBoard = new int[9]; static int[] corners = new int[] { 0, 2, 6, 8 }; static int[][] wins = new int[][] { new int[] { 0, 1, 2 }, new int[] { 3, 4, 5 }, new int[] { 6, 7, 8 }, new int[] { 0, 3, 6 }, new int[] { 1, 4, 7 }, new int[] { 2, 5, 8 }, new int[] { 0, 4, 8 }, new int[] { 2, 4, 6 } }; static void Main(string[] args) { while (true) { Console.Clear(); Console.WriteLine("Welcome to Rosetta Code Tic-Tac-Toe for C#."); initializeGameBoard(); displayGameBoard(); int currentPlayer = rnd.Next(0, 2); Console.WriteLine("The first move goes to {0} who is playing {1}s.\n", playerName(currentPlayer), playerToken(currentPlayer)); while (true) { int thisMove = getMoveFor(currentPlayer); if (thisMove == Unplayed) { Console.WriteLine("{0}, you've quit the game ... am I that good?", playerName(currentPlayer)); break; } playMove(thisMove, currentPlayer); displayGameBoard(); if (isGameWon()) { Console.WriteLine("{0} has won the game!", playerName(currentPlayer)); break; } else if (isGameTied()) { Console.WriteLine("Cat game ... we have a tie."); break; } currentPlayer = getNextPlayer(currentPlayer); } if (!playAgain()) return; } } static int getMoveFor(int player) { if (player == Human) return getManualMove(player); else { int selectedMove = getSemiRandomMove(player); Console.WriteLine("{0} selects position {1}.", playerName(player), selectedMove + 1); return selectedMove; } } static int getManualMove(int player) { while (true) { Console.Write("{0}, enter you move (number): ", playerName(player)); ConsoleKeyInfo keyInfo = Console.ReadKey(); Console.WriteLine(); if (keyInfo.Key == ConsoleKey.Escape) return Unplayed; if (keyInfo.Key >= ConsoleKey.D1 && keyInfo.Key <= ConsoleKey.D9) { int move = keyInfo.KeyChar - '1'; if (GameBoard[move] == Unplayed) return move; else Console.WriteLine("Spot {0} is already taken, please select again.", move + 1); } else Console.WriteLine("Illegal move, please select again.\n"); } } static int getRandomMove(int player) { int movesLeft = GameBoard.Count(position => position == Unplayed); int x = rnd.Next(0, movesLeft); for (int i = 0; i < GameBoard.Length; i++) { if (GameBoard[i] == Unplayed && x < 0) return i; x--; } return Unplayed; } static int getSemiRandomMove(int player) { int posToPlay; if (checkForWinningMove(player, out posToPlay)) return posToPlay; if (checkForBlockingMove(player, out posToPlay)) return posToPlay; return getRandomMove(player); } static int getBestMove(int player) { return -1; } static bool checkForWinningMove(int player, out int posToPlay) { posToPlay = Unplayed; foreach (var line in wins) if (twoOfThreeMatchPlayer(player, line, out posToPlay)) return true; return false; } static bool checkForBlockingMove(int player, out int posToPlay) { posToPlay = Unplayed; foreach (var line in wins) if (twoOfThreeMatchPlayer(getNextPlayer(player), line, out posToPlay)) return true; return false; } static bool twoOfThreeMatchPlayer(int player, int[] line, out int posToPlay) { int cnt = 0; posToPlay = int.MinValue; foreach (int pos in line) { if (GameBoard[pos] == player) cnt++; else if (GameBoard[pos] == Unplayed) posToPlay = pos; } return cnt == 2 && posToPlay >= 0; } static void playMove(int boardPosition, int player) { GameBoard[boardPosition] = player; } static bool isGameWon() { return wins.Any(line => takenBySamePlayer(line[0], line[1], line[2])); } static bool takenBySamePlayer(int a, int b, int c) { return GameBoard[a] != Unplayed && GameBoard[a] == GameBoard[b] && GameBoard[a] == GameBoard[c]; } static bool isGameTied() { return !GameBoard.Any(spot => spot == Unplayed); } static Random rnd = new Random(); static void initializeGameBoard() { for (int i = 0; i < GameBoard.Length; i++) GameBoard[i] = Unplayed; } static string playerName(int player) { return Players[player][0]; } static string playerToken(int player) { return Players[player][1]; } static int getNextPlayer(int player) { return (player + 1) % 2; } static void displayGameBoard() { Console.WriteLine(" {0} | {1} | {2}", pieceAt(0), pieceAt(1), pieceAt(2)); Console.WriteLine("---|---|---"); Console.WriteLine(" {0} | {1} | {2}", pieceAt(3), pieceAt(4), pieceAt(5)); Console.WriteLine("---|---|---"); Console.WriteLine(" {0} | {1} | {2}", pieceAt(6), pieceAt(7), pieceAt(8)); Console.WriteLine(); } static string pieceAt(int boardPosition) { if (GameBoard[boardPosition] == Unplayed) return (boardPosition + 1).ToString(); return playerToken(GameBoard[boardPosition]); } private static bool playAgain() { Console.WriteLine("\nDo you want to play again?"); return Console.ReadKey(false).Key == ConsoleKey.Y; } } }
Translate the given VB code snippet into C# without altering its behavior.
For i As Integer = 0 To Integer.MaxValue Console.WriteLine(i) Next
using System; using System.Numerics; class Program { static void Main() { BigInteger i = 1; while (true) { Console.WriteLine(i++); } } }
Port the following code from VB to C# with equivalent syntax and logic.
For i As Integer = 0 To Integer.MaxValue Console.WriteLine(i) Next
using System; using System.Numerics; class Program { static void Main() { BigInteger i = 1; while (true) { Console.WriteLine(i++); } } }
Please provide an equivalent version of this VB code in C#.
For i As Integer = 0 To Integer.MaxValue Console.WriteLine(i) Next
using System; using System.Numerics; class Program { static void Main() { BigInteger i = 1; while (true) { Console.WriteLine(i++); } } }
Keep all operations the same but rewrite the snippet in C#.
Function dns_query(url,ver) Set r = New RegExp r.Pattern = "Pinging.+?\[(.+?)\].+" Set objshell = CreateObject("WScript.Shell") Set objexec = objshell.Exec("%comspec% /c " & "ping -" & ver & " " & url) WScript.StdOut.WriteLine "URL: " & url Do Until objexec.StdOut.AtEndOfStream line = objexec.StdOut.ReadLine If r.Test(line) Then WScript.StdOut.WriteLine "IP Version " &_ ver & ": " & r.Replace(line,"$1") End If Loop End Function Call dns_query(WScript.Arguments(0),WScript.Arguments(1))
private string LookupDns(string s) { try { System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s); string result = ip.AddressList[0].ToString(); for (int i = 1; i < ip.AddressList.Length; ++i) result += ", " + ip.AddressList[i].ToString(); return result; } catch (System.Net.Sockets.SocketException se) { return se.Message; } }
Preserve the algorithm and functionality while converting the code from VB to C#.
Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean Dim Total As Long, Ei As Long, i As Integer Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double Debug.Print "[1] ""Data set:"" "; For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies) Total = Total + ObservationFrequencies(i) Debug.Print ObservationFrequencies(i); " "; Next i DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies) Ei = Total / (DegreesOfFreedom + 1) For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies) ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei Next i p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True) Debug.Print Debug.Print "Chi-squared test for given frequencies" Debug.Print "X-squared ="; Format(ChiSquared, "0.0000"); ", "; Debug.Print "df ="; DegreesOfFreedom; ", "; Debug.Print "p-value = "; Format(p_value, "0.0000") Test4DiscreteUniformDistribution = p_value > Significance End Function Private Function Dice5() As Integer Dice5 = Int(5 * Rnd + 1) End Function Private Function Dice7() As Integer Dim i As Integer Do i = 5 * (Dice5 - 1) + Dice5 Loop While i > 21 Dice7 = i Mod 7 + 1 End Function Sub TestDice7() Dim i As Long, roll As Integer Dim Bins(1 To 7) As Variant For i = 1 To 1000000 roll = Dice7 Bins(roll) = Bins(roll) + 1 Next i Debug.Print "[1] ""Uniform? "; Test4DiscreteUniformDistribution(Bins, 0.05); """" End Sub
using System; public class SevenSidedDice { Random random = new Random(); static void Main(string[] args) { SevenSidedDice sevenDice = new SevenSidedDice(); Console.WriteLine("Random number from 1 to 7: "+ sevenDice.seven()); Console.Read(); } int seven() { int v=21; while(v>20) v=five()+five()*5-6; return 1+v%7; } int five() { return 1 + random.Next(5); } }
Write a version of this VB function in C# with identical behavior.
Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean Dim Total As Long, Ei As Long, i As Integer Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double Debug.Print "[1] ""Data set:"" "; For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies) Total = Total + ObservationFrequencies(i) Debug.Print ObservationFrequencies(i); " "; Next i DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies) Ei = Total / (DegreesOfFreedom + 1) For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies) ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei Next i p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True) Debug.Print Debug.Print "Chi-squared test for given frequencies" Debug.Print "X-squared ="; Format(ChiSquared, "0.0000"); ", "; Debug.Print "df ="; DegreesOfFreedom; ", "; Debug.Print "p-value = "; Format(p_value, "0.0000") Test4DiscreteUniformDistribution = p_value > Significance End Function Private Function Dice5() As Integer Dice5 = Int(5 * Rnd + 1) End Function Private Function Dice7() As Integer Dim i As Integer Do i = 5 * (Dice5 - 1) + Dice5 Loop While i > 21 Dice7 = i Mod 7 + 1 End Function Sub TestDice7() Dim i As Long, roll As Integer Dim Bins(1 To 7) As Variant For i = 1 To 1000000 roll = Dice7 Bins(roll) = Bins(roll) + 1 Next i Debug.Print "[1] ""Uniform? "; Test4DiscreteUniformDistribution(Bins, 0.05); """" End Sub
using System; public class SevenSidedDice { Random random = new Random(); static void Main(string[] args) { SevenSidedDice sevenDice = new SevenSidedDice(); Console.WriteLine("Random number from 1 to 7: "+ sevenDice.seven()); Console.Read(); } int seven() { int v=21; while(v>20) v=five()+five()*5-6; return 1+v%7; } int five() { return 1 + random.Next(5); } }
Ensure the translated C# code behaves exactly like the original VB snippet.
Imports System, System.Console Module Module1 Dim np As Boolean() Sub ms(ByVal lmt As Long) np = New Boolean(CInt(lmt)) {} : np(0) = True : np(1) = True Dim n As Integer = 2, j As Integer = 1 : While n < lmt If Not np(n) Then Dim k As Long = CLng(n) * n While k < lmt : np(CInt(k)) = True : k += n : End While End If : n += j : j = 2 : End While End Sub Function is_Mag(ByVal n As Integer) As Boolean Dim res, rm As Integer, p As Integer = 10 While n >= p res = Math.DivRem(n, p, rm) If np(res + rm) Then Return False p = p * 10 : End While : Return True End Function Sub Main(ByVal args As String()) ms(100_009) : Dim mn As String = " magnanimous numbers:" WriteLine("First 45{0}", mn) : Dim l As Integer = 0, c As Integer = 0 While c < 400 : If is_Mag(l) Then c += 1 : If c <= 45 OrElse (c > 240 AndAlso c <= 250) OrElse c > 390 Then Write(If(c <= 45, "{0,4} ", "{0,8:n0} "), l) If c < 45 AndAlso c Mod 15 = 0 Then WriteLine() If c = 240 Then WriteLine(vbLf & vbLf & "241st through 250th{0}", mn) If c = 390 Then WriteLine(vbLf & vbLf & "391st through 400th{0}", mn) End If : l += 1 : End While End Sub End Module
using System; using static System.Console; class Program { static bool[] np; static void ms(long lmt) { np = new bool[lmt]; np[0] = np[1] = true; for (long n = 2, j = 1; n < lmt; n += j, j = 2) if (!np[n]) for (long k = n * n; k < lmt; k += n) np[k] = true; } static bool is_Mag(long n) { long res, rem; for (long p = 10; n >= p; p *= 10) { res = Math.DivRem (n, p, out rem); if (np[res + rem]) return false; } return true; } static void Main(string[] args) { ms(100_009); string mn; WriteLine("First 45{0}", mn = " magnanimous numbers:"); for (long l = 0, c = 0; c < 400; l++) if (is_Mag(l)) { if (c++ < 45 || (c > 240 && c <= 250) || c > 390) Write(c <= 45 ? "{0,4} " : "{0,8:n0} ", l); if (c < 45 && c % 15 == 0) WriteLine(); if (c == 240) WriteLine ("\n\n241st through 250th{0}", mn); if (c == 390) WriteLine ("\n\n391st through 400th{0}", mn); } } }