Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Translate the given VB code snippet into Python without altering its behavior.
Option Explicit Const numchars=127 Function LZWCompress(si) Dim oDict, intMaxCode, i,z,ii,ss,strCurrent,strNext,j Set oDict = CreateObject("Scripting.Dictionary") ReDim a(Len(si)) intMaxCode = numchars For i = 0 To numchars oDict.Add Chr(i), i Next strCurrent = Left(si,1) j=0 For ii=2 To Len(si) strNext = Mid(si,ii,1) ss=strCurrent & strNext If oDict.Exists(ss) Then strCurrent = ss Else a(j)=oDict.Item(strCurrent) :j=j+1 intMaxCode = intMaxCode + 1 oDict.Add ss, intMaxCode strCurrent = strNext End If Next a(j)=oDict.Item(strCurrent) ReDim preserve a(j) LZWCompress=a Set oDict = Nothing End Function Function lzwUncompress(sc) Dim intNext, intCurrent, intMaxCode, i,ss,istr,s,j s="" reDim dict(1000) intMaxCode = numchars For i = 0 To numchars : dict(i)= Chr(i) : Next intCurrent=sc(0) For j=1 To UBound(sc) ss=dict(intCurrent) s= s & ss intMaxCode = intMaxCode + 1 intnext=sc(j) If intNext<intMaxCode Then dict(intMaxCode)=ss & Left(dict(intNext), 1) Else dict(intMaxCode)=ss & Left(ss, 1) End If intCurrent = intNext Next s= s & dict(intCurrent) lzwUncompress=s End function Sub printvec(a) Dim s,i,x s="(" For i=0 To UBound (a) s=s & x & a(i) x=", " Next WScript.echo s &")" End sub Dim a,b b="TOBEORNOTTOBEORTOBEORNOT" WScript.Echo b a=LZWCompress (b) printvec(a) WScript.echo lzwUncompress (a ) wscript.quit 1
def compress(uncompressed): dict_size = 256 dictionary = dict((chr(i), i) for i in range(dict_size)) w = "" result = [] for c in uncompressed: wc = w + c if wc in dictionary: w = wc else: result.append(dictionary[w]) dictionary[wc] = dict_size dict_size += 1 w = c if w: result.append(dictionary[w]) return result def decompress(compressed): from io import StringIO dict_size = 256 dictionary = dict((i, chr(i)) for i in range(dict_size)) result = StringIO() w = chr(compressed.pop(0)) result.write(w) for k in compressed: if k in dictionary: entry = dictionary[k] elif k == dict_size: entry = w + w[0] else: raise ValueError('Bad compressed k: %s' % k) result.write(entry) dictionary[dict_size] = w + entry[0] dict_size += 1 w = entry return result.getvalue() compressed = compress('TOBEORNOTTOBEORTOBEORNOT') print (compressed) decompressed = decompress(compressed) print (decompressed)
Maintain the same structure and functionality when rewriting this code in Python.
Private Function ffr(n As Long) As Long Dim R As New Collection Dim S As New Collection R.Add 1 S.Add 2 For i = 2 To n R.Add R(i - 1) + S(i - 1) For j = S(S.Count) + 1 To R(i) - 1 S.Add j Next j For j = R(i) + 1 To R(i) + S(i - 1) S.Add j Next j Next i ffr = R(n) Set R = Nothing Set S = Nothing End Function Private Function ffs(n As Long) As Long Dim R As New Collection Dim S As New Collection R.Add 1 S.Add 2 For i = 2 To n R.Add R(i - 1) + S(i - 1) For j = S(S.Count) + 1 To R(i) - 1 S.Add j Next j For j = R(i) + 1 To R(i) + S(i - 1) S.Add j Next j If S.Count >= n Then Exit For Next i ffs = S(n) Set R = Nothing Set S = Nothing End Function Public Sub main() Dim i As Long Debug.Print "The first ten values of R are:" For i = 1 To 10 Debug.Print ffr(i); Next i Debug.Print Dim x As New Collection For i = 1 To 1000 x.Add i, CStr(i) Next i For i = 1 To 40 x.Remove CStr(ffr(i)) Next i For i = 1 To 960 x.Remove CStr(ffs(i)) Next i Debug.Print "The first 40 values of ffr plus the first 960 values of ffs " Debug.Print "include all the integers from 1 to 1000 exactly once is "; Format(x.Count = 0) End Sub
def ffr(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffr.r[n] except IndexError: r, s = ffr.r, ffs.s ffr_n_1 = ffr(n-1) lastr = r[-1] s += list(range(s[-1] + 1, lastr)) if s[-1] < lastr: s += [lastr + 1] len_s = len(s) ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1] ans = ffr_n_1 + ffs_n_1 r.append(ans) return ans ffr.r = [None, 1] def ffs(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffs.s[n] except IndexError: r, s = ffr.r, ffs.s for i in range(len(r), n+2): ffr(i) if len(s) > n: return s[n] raise Exception("Whoops!") ffs.s = [None, 2] if __name__ == '__main__': first10 = [ffr(i) for i in range(1,11)] assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], "ffr() value error(s)" print("ffr(n) for n = [1..10] is", first10) bin = [None] + [0]*1000 for i in range(40, 0, -1): bin[ffr(i)] += 1 for i in range(960, 0, -1): bin[ffs(i)] += 1 if all(b == 1 for b in bin[1:1000]): print("All Integers 1..1000 found OK") else: print("All Integers 1..1000 NOT found only once: ERROR")
Can you help me rewrite this code in Python instead of VB, keeping it the same logically?
Private Function ffr(n As Long) As Long Dim R As New Collection Dim S As New Collection R.Add 1 S.Add 2 For i = 2 To n R.Add R(i - 1) + S(i - 1) For j = S(S.Count) + 1 To R(i) - 1 S.Add j Next j For j = R(i) + 1 To R(i) + S(i - 1) S.Add j Next j Next i ffr = R(n) Set R = Nothing Set S = Nothing End Function Private Function ffs(n As Long) As Long Dim R As New Collection Dim S As New Collection R.Add 1 S.Add 2 For i = 2 To n R.Add R(i - 1) + S(i - 1) For j = S(S.Count) + 1 To R(i) - 1 S.Add j Next j For j = R(i) + 1 To R(i) + S(i - 1) S.Add j Next j If S.Count >= n Then Exit For Next i ffs = S(n) Set R = Nothing Set S = Nothing End Function Public Sub main() Dim i As Long Debug.Print "The first ten values of R are:" For i = 1 To 10 Debug.Print ffr(i); Next i Debug.Print Dim x As New Collection For i = 1 To 1000 x.Add i, CStr(i) Next i For i = 1 To 40 x.Remove CStr(ffr(i)) Next i For i = 1 To 960 x.Remove CStr(ffs(i)) Next i Debug.Print "The first 40 values of ffr plus the first 960 values of ffs " Debug.Print "include all the integers from 1 to 1000 exactly once is "; Format(x.Count = 0) End Sub
def ffr(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffr.r[n] except IndexError: r, s = ffr.r, ffs.s ffr_n_1 = ffr(n-1) lastr = r[-1] s += list(range(s[-1] + 1, lastr)) if s[-1] < lastr: s += [lastr + 1] len_s = len(s) ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1] ans = ffr_n_1 + ffs_n_1 r.append(ans) return ans ffr.r = [None, 1] def ffs(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffs.s[n] except IndexError: r, s = ffr.r, ffs.s for i in range(len(r), n+2): ffr(i) if len(s) > n: return s[n] raise Exception("Whoops!") ffs.s = [None, 2] if __name__ == '__main__': first10 = [ffr(i) for i in range(1,11)] assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], "ffr() value error(s)" print("ffr(n) for n = [1..10] is", first10) bin = [None] + [0]*1000 for i in range(40, 0, -1): bin[ffr(i)] += 1 for i in range(960, 0, -1): bin[ffs(i)] += 1 if all(b == 1 for b in bin[1:1000]): print("All Integers 1..1000 found OK") else: print("All Integers 1..1000 NOT found only once: ERROR")
Rewrite the snippet below in Python so it works the same as the original VB code.
Sub magicsquare() Const n = 9 Dim i As Integer, j As Integer, v As Integer Debug.Print "The square order is: " & n For i = 1 To n For j = 1 To n Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1 Next j Next i Debug.Print "The magic number of"; n; "x"; n; "square is:"; n * (n * n + 1) \ 2 End Sub
>>> def magic(n): for row in range(1, n + 1): print(' '.join('%*i' % (len(str(n**2)), cell) for cell in (n * ((row + col - 1 + n // 2) % n) + ((row + 2 * col - 2) % n) + 1 for col in range(1, n + 1)))) print('\nAll sum to magic number %i' % ((n * n + 1) * n // 2)) >>> for n in (5, 3, 7): print('\nOrder %i\n=======' % n) magic(n) Order 5 ======= 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 All sum to magic number 65 Order 3 ======= 8 1 6 3 5 7 4 9 2 All sum to magic number 15 Order 7 ======= 30 39 48 1 10 19 28 38 47 7 9 18 27 29 46 6 8 17 26 35 37 5 14 16 25 34 36 45 13 15 24 33 42 44 4 21 23 32 41 43 3 12 22 31 40 49 2 11 20 All sum to magic number 175 >>>
Rewrite this program in Python while keeping its functionality equivalent to the VB version.
Sub magicsquare() Const n = 9 Dim i As Integer, j As Integer, v As Integer Debug.Print "The square order is: " & n For i = 1 To n For j = 1 To n Cells(i, j) = ((i * 2 - j + n - 1) Mod n) * n + ((i * 2 + j - 2) Mod n) + 1 Next j Next i Debug.Print "The magic number of"; n; "x"; n; "square is:"; n * (n * n + 1) \ 2 End Sub
>>> def magic(n): for row in range(1, n + 1): print(' '.join('%*i' % (len(str(n**2)), cell) for cell in (n * ((row + col - 1 + n // 2) % n) + ((row + 2 * col - 2) % n) + 1 for col in range(1, n + 1)))) print('\nAll sum to magic number %i' % ((n * n + 1) * n // 2)) >>> for n in (5, 3, 7): print('\nOrder %i\n=======' % n) magic(n) Order 5 ======= 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 All sum to magic number 65 Order 3 ======= 8 1 6 3 5 7 4 9 2 All sum to magic number 15 Order 7 ======= 30 39 48 1 10 19 28 38 47 7 9 18 27 29 46 6 8 17 26 35 37 5 14 16 25 34 36 45 13 15 24 33 42 44 4 21 23 32 41 43 3 12 22 31 40 49 2 11 20 All sum to magic number 175 >>>
Please provide an equivalent version of this VB code in Python.
Sub BenfordLaw() Dim BenResult(1 To 9) As Long BENref = "30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%" For Each c In Selection.Cells If InStr(1, "-0123456789", Left(c, 1)) > 0 Then For i = 1 To 9 If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For Next End If Next Total= Application.Sum(BenResult) biggest= Len(CStr(BenResult(1))) txt = "# | Values | Real | Expected " & vbCrLf For i = 1 To 9 If BenResult(i) > 0 Then txt = txt & "#" & i & " | " & vbTab txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, " ") & Format(BenResult(i), "0") & " | " & vbTab txt = txt & String((Len(CStr(Format(BenResult(1) / Total, "##0.0%"))) - Len(CStr(Format(BenResult(i) / Total, "##0.0%")))) * 2, " ") & Format(BenResult(i) / Total, "##0.0%") & " | " & vbTab txt = txt & Format(Split(BENref, "|")(i - 1), " ##0.0%") & vbCrLf End If Next MsgBox txt, vbOKOnly, "Finish" End Sub }
from __future__ import division from itertools import islice, count from collections import Counter from math import log10 from random import randint expected = [log10(1+1/d) for d in range(1,10)] def fib(): a,b = 1,1 while True: yield a a,b = b,a+b def power_of_threes(): return (3**k for k in count(0)) def heads(s): for a in s: yield int(str(a)[0]) def show_dist(title, s): c = Counter(s) size = sum(c.values()) res = [c[d]/size for d in range(1,10)] print("\n%s Benfords deviation" % title) for r, e in zip(res, expected): print("%5.1f%% %5.1f%% %5.1f%%" % (r*100., e*100., abs(r - e)*100.)) def rand1000(): while True: yield randint(1,9999) if __name__ == '__main__': show_dist("fibbed", islice(heads(fib()), 1000)) show_dist("threes", islice(heads(power_of_threes()), 1000)) show_dist("random", islice(heads(rand1000()), 10000))
Convert the following code from VB to Python, ensuring the logic remains intact.
Sub BenfordLaw() Dim BenResult(1 To 9) As Long BENref = "30,1%|17,6%|12,5%|9,7%|7,9%|6,7%|5,8%|5,1%|4,6%" For Each c In Selection.Cells If InStr(1, "-0123456789", Left(c, 1)) > 0 Then For i = 1 To 9 If CInt(Left(Abs(c), 1)) = i Then BenResult(i) = BenResult(i) + 1: Exit For Next End If Next Total= Application.Sum(BenResult) biggest= Len(CStr(BenResult(1))) txt = "# | Values | Real | Expected " & vbCrLf For i = 1 To 9 If BenResult(i) > 0 Then txt = txt & "#" & i & " | " & vbTab txt = txt & String((biggest - Len(CStr(BenResult(i)))) * 2, " ") & Format(BenResult(i), "0") & " | " & vbTab txt = txt & String((Len(CStr(Format(BenResult(1) / Total, "##0.0%"))) - Len(CStr(Format(BenResult(i) / Total, "##0.0%")))) * 2, " ") & Format(BenResult(i) / Total, "##0.0%") & " | " & vbTab txt = txt & Format(Split(BENref, "|")(i - 1), " ##0.0%") & vbCrLf End If Next MsgBox txt, vbOKOnly, "Finish" End Sub }
from __future__ import division from itertools import islice, count from collections import Counter from math import log10 from random import randint expected = [log10(1+1/d) for d in range(1,10)] def fib(): a,b = 1,1 while True: yield a a,b = b,a+b def power_of_threes(): return (3**k for k in count(0)) def heads(s): for a in s: yield int(str(a)[0]) def show_dist(title, s): c = Counter(s) size = sum(c.values()) res = [c[d]/size for d in range(1,10)] print("\n%s Benfords deviation" % title) for r, e in zip(res, expected): print("%5.1f%% %5.1f%% %5.1f%%" % (r*100., e*100., abs(r - e)*100.)) def rand1000(): while True: yield randint(1,9999) if __name__ == '__main__': show_dist("fibbed", islice(heads(fib()), 1000)) show_dist("threes", islice(heads(power_of_threes()), 1000)) show_dist("random", islice(heads(rand1000()), 10000))
Ensure the translated Python code behaves exactly like the original VB snippet.
Sub Main() Debug.Print F(-10) Debug.Print F(10) End Sub Private Function F(N As Long) As Variant If N < 0 Then F = "Error. Negative argument" ElseIf N <= 1 Then F = N Else F = F(N - 1) + F(N - 2) End If End Function
>>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args))) >>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2))) >>> [ Y(fib)(i) for i in range(-2, 10) ] [None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Port the following code from VB to Python with equivalent syntax and logic.
string = "Small Basic" TextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) TextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) TextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2))
print "knight"[1:] print "socks"[:-1] print "brooms"[1:-1]
Produce a language-to-language conversion: from VB to Python, same semantics.
string = "Small Basic" TextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) TextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) TextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2))
print "knight"[1:] print "socks"[:-1] print "brooms"[1:-1]
Can you help me rewrite this code in Python instead of VB, keeping it the same logically?
Set objfso = CreateObject("Scripting.FileSystemObject") Set objfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_ "\input.txt",1) list = "" previous_line = "" l = Len(previous_line) Do Until objfile.AtEndOfStream current_line = objfile.ReadLine If Mid(current_line,l+1,1) <> "" Then list = current_line & vbCrLf previous_line = current_line l = Len(previous_line) ElseIf Mid(current_line,l,1) <> "" And Mid(current_line,(l+1),1) = "" Then list = list & current_line & vbCrLf End If Loop WScript.Echo list objfile.Close Set objfso = Nothing
import fileinput def longer(a, b): try: b[len(a)-1] return False except: return True longest, lines = '', '' for x in fileinput.input(): if longer(x, longest): lines, longest = x, x elif not longer(longest, x): lines += x print(lines, end='')
Rewrite this program in Python while keeping its functionality equivalent to the VB version.
Set objfso = CreateObject("Scripting.FileSystemObject") Set objfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_ "\input.txt",1) list = "" previous_line = "" l = Len(previous_line) Do Until objfile.AtEndOfStream current_line = objfile.ReadLine If Mid(current_line,l+1,1) <> "" Then list = current_line & vbCrLf previous_line = current_line l = Len(previous_line) ElseIf Mid(current_line,l,1) <> "" And Mid(current_line,(l+1),1) = "" Then list = list & current_line & vbCrLf End If Loop WScript.Echo list objfile.Close Set objfso = Nothing
import fileinput def longer(a, b): try: b[len(a)-1] return False except: return True longest, lines = '', '' for x in fileinput.input(): if longer(x, longest): lines, longest = x, x elif not longer(longest, x): lines += x print(lines, end='')
Write the same code in Python as shown below in VB.
Option Base 1 Public Enum sett name_ = 1 initState endState blank rules End Enum Public incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant Private Sub init() incrementer = Array("Simple incrementer", _ "q0", _ "qf", _ "B", _ Array( _ Array("q0", "1", "1", "right", "q0"), _ Array("q0", "B", "1", "stay", "qf"))) threeStateBB = Array("Three-state busy beaver", _ "a", _ "halt", _ "0", _ Array( _ Array("a", "0", "1", "right", "b"), _ Array("a", "1", "1", "left", "c"), _ Array("b", "0", "1", "left", "a"), _ Array("b", "1", "1", "right", "b"), _ Array("c", "0", "1", "left", "b"), _ Array("c", "1", "1", "stay", "halt"))) fiveStateBB = Array("Five-state busy beaver", _ "A", _ "H", _ "0", _ Array( _ Array("A", "0", "1", "right", "B"), _ Array("A", "1", "1", "left", "C"), _ Array("B", "0", "1", "right", "C"), _ Array("B", "1", "1", "right", "B"), _ Array("C", "0", "1", "right", "D"), _ Array("C", "1", "0", "left", "E"), _ Array("D", "0", "1", "left", "A"), _ Array("D", "1", "1", "left", "D"), _ Array("E", "0", "1", "stay", "H"), _ Array("E", "1", "0", "left", "A"))) End Sub Private Sub show(state As String, headpos As Long, tape As Collection) Debug.Print " "; state; String$(7 - Len(state), " "); "| "; For p = 1 To tape.Count Debug.Print IIf(p = headpos, "[" & tape(p) & "]", " " & tape(p) & " "); Next p Debug.Print End Sub Private Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0) Dim state As String: state = machine(initState) Dim headpos As Long: headpos = 1 Dim counter As Long, rule As Variant Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), "=") If Not countOnly Then Debug.Print " State | Tape [head]" & vbCrLf & "---------------------" Do While True If headpos > tape.Count Then tape.Add machine(blank) Else If headpos < 1 Then tape.Add machine(blank), Before:=1 headpos = 1 End If End If If Not countOnly Then show state, headpos, tape For i = LBound(machine(rules)) To UBound(machine(rules)) rule = machine(rules)(i) If rule(1) = state And rule(2) = tape(headpos) Then tape.Remove headpos If headpos > tape.Count Then tape.Add rule(3) Else tape.Add rule(3), Before:=headpos End If If rule(4) = "left" Then headpos = headpos - 1 If rule(4) = "right" Then headpos = headpos + 1 state = rule(5) Exit For End If Next i counter = counter + 1 If counter Mod 100000 = 0 Then Debug.Print counter DoEvents DoEvents End If If state = machine(endState) Then Exit Do Loop DoEvents If countOnly Then Debug.Print "Steps taken: ", counter Else show state, headpos, tape Debug.Print End If End Sub Public Sub main() init Dim tap As New Collection tap.Add "1": tap.Add "1": tap.Add "1" UTM incrementer, tap Set tap = New Collection UTM threeStateBB, tap Set tap = New Collection UTM fiveStateBB, tap, countOnly:=-1 End Sub
from __future__ import print_function def run_utm( state = None, blank = None, rules = [], tape = [], halt = None, pos = 0): st = state if not tape: tape = [blank] if pos < 0: pos += len(tape) if pos >= len(tape) or pos < 0: raise Error( "bad init position") rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules) while True: print(st, '\t', end=" ") for i, v in enumerate(tape): if i == pos: print("[%s]" % (v,), end=" ") else: print(v, end=" ") print() if st == halt: break if (st, tape[pos]) not in rules: break (v1, dr, s1) = rules[(st, tape[pos])] tape[pos] = v1 if dr == 'left': if pos > 0: pos -= 1 else: tape.insert(0, blank) if dr == 'right': pos += 1 if pos >= len(tape): tape.append(blank) st = s1 print("incr machine\n") run_utm( halt = 'qf', state = 'q0', tape = list("111"), blank = 'B', rules = map(tuple, ["q0 1 1 right q0".split(), "q0 B 1 stay qf".split()] ) ) print("\nbusy beaver\n") run_utm( halt = 'halt', state = 'a', blank = '0', rules = map(tuple, ["a 0 1 right b".split(), "a 1 1 left c".split(), "b 0 1 left a".split(), "b 1 1 right b".split(), "c 0 1 left b".split(), "c 1 1 stay halt".split()] ) ) print("\nsorting test\n") run_utm(halt = 'STOP', state = 'A', blank = '0', tape = "2 2 2 1 2 2 1 2 1 2 1 2 1 2".split(), rules = map(tuple, ["A 1 1 right A".split(), "A 2 3 right B".split(), "A 0 0 left E".split(), "B 1 1 right B".split(), "B 2 2 right B".split(), "B 0 0 left C".split(), "C 1 2 left D".split(), "C 2 2 left C".split(), "C 3 2 left E".split(), "D 1 1 left D".split(), "D 2 2 left D".split(), "D 3 1 right A".split(), "E 1 1 left E".split(), "E 0 0 right STOP".split()] ) )
Maintain the same structure and functionality when rewriting this code in Python.
Option Base 1 Public Enum sett name_ = 1 initState endState blank rules End Enum Public incrementer As Variant, threeStateBB As Variant, fiveStateBB As Variant Private Sub init() incrementer = Array("Simple incrementer", _ "q0", _ "qf", _ "B", _ Array( _ Array("q0", "1", "1", "right", "q0"), _ Array("q0", "B", "1", "stay", "qf"))) threeStateBB = Array("Three-state busy beaver", _ "a", _ "halt", _ "0", _ Array( _ Array("a", "0", "1", "right", "b"), _ Array("a", "1", "1", "left", "c"), _ Array("b", "0", "1", "left", "a"), _ Array("b", "1", "1", "right", "b"), _ Array("c", "0", "1", "left", "b"), _ Array("c", "1", "1", "stay", "halt"))) fiveStateBB = Array("Five-state busy beaver", _ "A", _ "H", _ "0", _ Array( _ Array("A", "0", "1", "right", "B"), _ Array("A", "1", "1", "left", "C"), _ Array("B", "0", "1", "right", "C"), _ Array("B", "1", "1", "right", "B"), _ Array("C", "0", "1", "right", "D"), _ Array("C", "1", "0", "left", "E"), _ Array("D", "0", "1", "left", "A"), _ Array("D", "1", "1", "left", "D"), _ Array("E", "0", "1", "stay", "H"), _ Array("E", "1", "0", "left", "A"))) End Sub Private Sub show(state As String, headpos As Long, tape As Collection) Debug.Print " "; state; String$(7 - Len(state), " "); "| "; For p = 1 To tape.Count Debug.Print IIf(p = headpos, "[" & tape(p) & "]", " " & tape(p) & " "); Next p Debug.Print End Sub Private Sub UTM(machine As Variant, tape As Collection, Optional countOnly As Long = 0) Dim state As String: state = machine(initState) Dim headpos As Long: headpos = 1 Dim counter As Long, rule As Variant Debug.Print machine(name_); vbCrLf; String$(Len(machine(name_)), "=") If Not countOnly Then Debug.Print " State | Tape [head]" & vbCrLf & "---------------------" Do While True If headpos > tape.Count Then tape.Add machine(blank) Else If headpos < 1 Then tape.Add machine(blank), Before:=1 headpos = 1 End If End If If Not countOnly Then show state, headpos, tape For i = LBound(machine(rules)) To UBound(machine(rules)) rule = machine(rules)(i) If rule(1) = state And rule(2) = tape(headpos) Then tape.Remove headpos If headpos > tape.Count Then tape.Add rule(3) Else tape.Add rule(3), Before:=headpos End If If rule(4) = "left" Then headpos = headpos - 1 If rule(4) = "right" Then headpos = headpos + 1 state = rule(5) Exit For End If Next i counter = counter + 1 If counter Mod 100000 = 0 Then Debug.Print counter DoEvents DoEvents End If If state = machine(endState) Then Exit Do Loop DoEvents If countOnly Then Debug.Print "Steps taken: ", counter Else show state, headpos, tape Debug.Print End If End Sub Public Sub main() init Dim tap As New Collection tap.Add "1": tap.Add "1": tap.Add "1" UTM incrementer, tap Set tap = New Collection UTM threeStateBB, tap Set tap = New Collection UTM fiveStateBB, tap, countOnly:=-1 End Sub
from __future__ import print_function def run_utm( state = None, blank = None, rules = [], tape = [], halt = None, pos = 0): st = state if not tape: tape = [blank] if pos < 0: pos += len(tape) if pos >= len(tape) or pos < 0: raise Error( "bad init position") rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules) while True: print(st, '\t', end=" ") for i, v in enumerate(tape): if i == pos: print("[%s]" % (v,), end=" ") else: print(v, end=" ") print() if st == halt: break if (st, tape[pos]) not in rules: break (v1, dr, s1) = rules[(st, tape[pos])] tape[pos] = v1 if dr == 'left': if pos > 0: pos -= 1 else: tape.insert(0, blank) if dr == 'right': pos += 1 if pos >= len(tape): tape.append(blank) st = s1 print("incr machine\n") run_utm( halt = 'qf', state = 'q0', tape = list("111"), blank = 'B', rules = map(tuple, ["q0 1 1 right q0".split(), "q0 B 1 stay qf".split()] ) ) print("\nbusy beaver\n") run_utm( halt = 'halt', state = 'a', blank = '0', rules = map(tuple, ["a 0 1 right b".split(), "a 1 1 left c".split(), "b 0 1 left a".split(), "b 1 1 right b".split(), "c 0 1 left b".split(), "c 1 1 stay halt".split()] ) ) print("\nsorting test\n") run_utm(halt = 'STOP', state = 'A', blank = '0', tape = "2 2 2 1 2 2 1 2 1 2 1 2 1 2".split(), rules = map(tuple, ["A 1 1 right A".split(), "A 2 3 right B".split(), "A 0 0 left E".split(), "B 1 1 right B".split(), "B 2 2 right B".split(), "B 0 0 left C".split(), "C 1 2 left D".split(), "C 2 2 left C".split(), "C 3 2 left E".split(), "D 1 1 left D".split(), "D 2 2 left D".split(), "D 3 1 right A".split(), "E 1 1 left E".split(), "E 0 0 right STOP".split()] ) )
Rewrite the snippet below in Python so it works the same as the original VB code.
Public Sub create_file() Dim FileNumber As Integer FileNumber = FreeFile MkDir "docs" Open "docs\output.txt" For Output As #FreeFile Close #FreeFile MkDir "C:\docs" Open "C:\docs\output.txt" For Output As #FreeFile Close #FreeFile End Sub
import os for directory in ['/', './']: open(directory + 'output.txt', 'w').close() os.mkdir(directory + 'docs')
Convert the following code from VB to Python, ensuring the logic remains intact.
b=_ "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" &_ "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" &_ "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" &_ "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" &_ "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" &_ "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" &_ "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" &_ "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" &_ "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" &_ "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" s="SEQUENCE:" acnt=0:ccnt=0:gcnt=0:tcnt=0 for i=0 to len(b)-1 if (i mod 30)=0 then s = s & vbcrlf & right(" "& i+1,3)&": " if (i mod 5)=0 then s=s& " " m=mid(b,i+1,1) s=s & m select case m case "A":acnt=acnt+1 case "C":ccnt=ccnt+1 case "G":gcnt=gcnt+1 case "T":tcnt=tcnt+1 case else wscript.echo "error at ",i+1, m end select next wscript.echo s & vbcrlf wscript.echo "Count: A="&acnt & " C=" & ccnt & " G=" & gcnt & " T=" & tcnt
from collections import Counter def basecount(dna): return sorted(Counter(dna).items()) def seq_split(dna, n=50): return [dna[i: i+n] for i in range(0, len(dna), n)] def seq_pp(dna, n=50): for i, part in enumerate(seq_split(dna, n)): print(f"{i*n:>5}: {part}") print("\n BASECOUNT:") tot = 0 for base, count in basecount(dna): print(f" {base:>3}: {count}") tot += count base, count = 'TOT', tot print(f" {base:>3}= {count}") if __name__ == '__main__': print("SEQUENCE:") sequence = seq_pp(sequence)
Please provide an equivalent version of this VB code in Python.
b=_ "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" &_ "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" &_ "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" &_ "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" &_ "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" &_ "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" &_ "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" &_ "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" &_ "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" &_ "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" s="SEQUENCE:" acnt=0:ccnt=0:gcnt=0:tcnt=0 for i=0 to len(b)-1 if (i mod 30)=0 then s = s & vbcrlf & right(" "& i+1,3)&": " if (i mod 5)=0 then s=s& " " m=mid(b,i+1,1) s=s & m select case m case "A":acnt=acnt+1 case "C":ccnt=ccnt+1 case "G":gcnt=gcnt+1 case "T":tcnt=tcnt+1 case else wscript.echo "error at ",i+1, m end select next wscript.echo s & vbcrlf wscript.echo "Count: A="&acnt & " C=" & ccnt & " G=" & gcnt & " T=" & tcnt
from collections import Counter def basecount(dna): return sorted(Counter(dna).items()) def seq_split(dna, n=50): return [dna[i: i+n] for i in range(0, len(dna), n)] def seq_pp(dna, n=50): for i, part in enumerate(seq_split(dna, n)): print(f"{i*n:>5}: {part}") print("\n BASECOUNT:") tot = 0 for base, count in basecount(dna): print(f" {base:>3}: {count}") tot += count base, count = 'TOT', tot print(f" {base:>3}= {count}") if __name__ == '__main__': print("SEQUENCE:") sequence = seq_pp(sequence)
Write a version of this VB function in Python with identical behavior.
b=_ "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" &_ "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" &_ "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" &_ "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" &_ "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" &_ "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" &_ "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" &_ "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" &_ "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" &_ "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" s="SEQUENCE:" acnt=0:ccnt=0:gcnt=0:tcnt=0 for i=0 to len(b)-1 if (i mod 30)=0 then s = s & vbcrlf & right(" "& i+1,3)&": " if (i mod 5)=0 then s=s& " " m=mid(b,i+1,1) s=s & m select case m case "A":acnt=acnt+1 case "C":ccnt=ccnt+1 case "G":gcnt=gcnt+1 case "T":tcnt=tcnt+1 case else wscript.echo "error at ",i+1, m end select next wscript.echo s & vbcrlf wscript.echo "Count: A="&acnt & " C=" & ccnt & " G=" & gcnt & " T=" & tcnt
from collections import Counter def basecount(dna): return sorted(Counter(dna).items()) def seq_split(dna, n=50): return [dna[i: i+n] for i in range(0, len(dna), n)] def seq_pp(dna, n=50): for i, part in enumerate(seq_split(dna, n)): print(f"{i*n:>5}: {part}") print("\n BASECOUNT:") tot = 0 for base, count in basecount(dna): print(f" {base:>3}: {count}") tot += count base, count = 'TOT', tot print(f" {base:>3}= {count}") if __name__ == '__main__': print("SEQUENCE:") sequence = seq_pp(sequence)
Keep all operations the same but rewrite the snippet in Python.
Public Const HOLDON = False Public Const DIJKSTRASOLUTION = True Public Const X = 10 Public Const GETS = 0 Public Const PUTS = 1 Public Const EATS = 2 Public Const THKS = 5 Public Const FRSTFORK = 0 Public Const SCNDFORK = 1 Public Const SPAGHETI = 0 Public Const UNIVERSE = 1 Public Const MAXCOUNT = 100000 Public Const PHILOSOPHERS = 5 Public semaphore(PHILOSOPHERS - 1) As Integer Public positi0n(1, PHILOSOPHERS - 1) As Integer Public programcounter(PHILOSOPHERS - 1) As Long Public statistics(PHILOSOPHERS - 1, 5, 1) As Long Public names As Variant Private Sub init() names = [{"Aquinas","Babbage","Carroll","Derrida","Erasmus"}] For j = 0 To PHILOSOPHERS - 2 positi0n(0, j) = j + 1 positi0n(1, j) = j Next j If DIJKSTRASOLUTION Then positi0n(0, PHILOSOPHERS - 1) = j positi0n(1, PHILOSOPHERS - 1) = 0 Else positi0n(0, PHILOSOPHERS - 1) = 0 positi0n(1, PHILOSOPHERS - 1) = j End If End Sub Private Sub philosopher(subject As Integer, verb As Integer, objekt As Integer) statistics(subject, verb, objekt) = statistics(subject, verb, objekt) + 1 If verb < 2 Then If semaphore(positi0n(objekt, subject)) <> verb Then If Not HOLDON Then semaphore(positi0n(FRSTFORK, subject)) = 1 - objekt programcounter(subject) = 0 End If Else semaphore(positi0n(objekt, subject)) = 1 - verb programcounter(subject) = (programcounter(subject) + 1) Mod 6 End If Else programcounter(subject) = IIf(X * Rnd > 1, verb, verb + 1) Mod 6 End If End Sub Private Sub dine() Dim ph As Integer Do While TC < MAXCOUNT For ph = 0 To PHILOSOPHERS - 1 Select Case programcounter(ph) Case 0: philosopher ph, GETS, FRSTFORK Case 1: philosopher ph, GETS, SCNDFORK Case 2: philosopher ph, EATS, SPAGHETI Case 3: philosopher ph, PUTS, FRSTFORK Case 4: philosopher ph, PUTS, SCNDFORK Case 5: philosopher ph, THKS, UNIVERSE End Select TC = TC + 1 Next ph Loop End Sub Private Sub show() Debug.Print "Stats", "Gets", "Gets", "Eats", "Puts", "Puts", "Thinks" Debug.Print "", "First", "Second", "Spag-", "First", "Second", "About" Debug.Print "", "Fork", "Fork", "hetti", "Fork", "Fork", "Universe" For subject = 0 To PHILOSOPHERS - 1 Debug.Print names(subject + 1), For objekt = 0 To 1 Debug.Print statistics(subject, GETS, objekt), Next objekt Debug.Print statistics(subject, EATS, SPAGHETI), For objekt = 0 To 1 Debug.Print statistics(subject, PUTS, objekt), Next objekt Debug.Print statistics(subject, THKS, UNIVERSE) Next subject End Sub Public Sub main() init dine show End Sub
import threading import random import time class Philosopher(threading.Thread): running = True def __init__(self, xname, forkOnLeft, forkOnRight): threading.Thread.__init__(self) self.name = xname self.forkOnLeft = forkOnLeft self.forkOnRight = forkOnRight def run(self): while(self.running): time.sleep( random.uniform(3,13)) print '%s is hungry.' % self.name self.dine() def dine(self): fork1, fork2 = self.forkOnLeft, self.forkOnRight while self.running: fork1.acquire(True) locked = fork2.acquire(False) if locked: break fork1.release() print '%s swaps forks' % self.name fork1, fork2 = fork2, fork1 else: return self.dining() fork2.release() fork1.release() def dining(self): print '%s starts eating '% self.name time.sleep(random.uniform(1,10)) print '%s finishes eating and leaves to think.' % self.name def DiningPhilosophers(): forks = [threading.Lock() for n in range(5)] philosopherNames = ('Aristotle','Kant','Spinoza','Marx', 'Russel') philosophers= [Philosopher(philosopherNames[i], forks[i%5], forks[(i+1)%5]) \ for i in range(5)] random.seed(507129) Philosopher.running = True for p in philosophers: p.start() time.sleep(100) Philosopher.running = False print ("Now we're finishing.") DiningPhilosophers()
Please provide an equivalent version of this VB code in Python.
Dim fact() nn1=9 : nn2=12 lim=1499999 ReDim fact(nn2) fact(0)=1 For i=1 To nn2 fact(i)=fact(i-1)*i Next For base=nn1 To nn2 list="" For i=1 To lim s=0 t=i Do While t<>0 d=t Mod base s=s+fact(d) t=t\base Loop If s=i Then list=list &" "& i Next Wscript.Echo "the factorions for base "& right(" "& base,2) &" are: "& list Next
fact = [1] for n in range(1, 12): fact.append(fact[n-1] * n) for b in range(9, 12+1): print(f"The factorions for base {b} are:") for i in range(1, 1500000): fact_sum = 0 j = i while j > 0: d = j % b fact_sum += fact[d] j = j//b if fact_sum == i: print(i, end=" ") print("\n")
Write the same code in Python as shown below in VB.
Dim fact() nn1=9 : nn2=12 lim=1499999 ReDim fact(nn2) fact(0)=1 For i=1 To nn2 fact(i)=fact(i-1)*i Next For base=nn1 To nn2 list="" For i=1 To lim s=0 t=i Do While t<>0 d=t Mod base s=s+fact(d) t=t\base Loop If s=i Then list=list &" "& i Next Wscript.Echo "the factorions for base "& right(" "& base,2) &" are: "& list Next
fact = [1] for n in range(1, 12): fact.append(fact[n-1] * n) for b in range(9, 12+1): print(f"The factorions for base {b} are:") for i in range(1, 1500000): fact_sum = 0 j = i while j > 0: d = j % b fact_sum += fact[d] j = j//b if fact_sum == i: print(i, end=" ") print("\n")
Convert this VB snippet to Python and keep its semantics consistent.
Private Function ValidateUserWords(userstring As String) As String Dim s As String Dim user_words() As String Dim command_table As Scripting.Dictionary Set command_table = New Scripting.Dictionary Dim abbreviations As Scripting.Dictionary Set abbreviations = New Scripting.Dictionary abbreviations.CompareMode = TextCompare Dim commandtable() As String Dim commands As String s = s & "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " s = s & "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " s = s & "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " s = s & "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " s = s & "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " s = s & "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " s = s & "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up " commandtable = Split(s, " ") Dim i As Integer For Each word In commandtable If Len(word) > 0 Then i = 1 Do While Mid(word, i, 1) >= "A" And Mid(word, i, 1) <= "Z" i = i + 1 Loop command_table.Add Key:=word, Item:=i - 1 End If Next word For Each word In command_table For i = command_table(word) To Len(word) On Error Resume Next abbreviations.Add Key:=Left(word, i), Item:=UCase(word) Next i Next word user_words() = Split(userstring, " ") For Each word In user_words If Len(word) > 0 Then If abbreviations.exists(word) Then commands = commands & abbreviations(word) & " " Else commands = commands & "*error* " End If End If Next word ValidateUserWords = commands End Function Public Sub program() Dim guserstring As String guserstring = "riG rePEAT copies put mo rest types fup. 6 poweRin" Debug.Print "user words:", guserstring Debug.Print "full words:", ValidateUserWords(guserstring) End Sub
command_table_text = \ user_words = "riG rePEAT copies put mo rest types fup. 6 poweRin" def find_abbreviations_length(command_table_text): command_table = dict() for word in command_table_text.split(): abbr_len = sum(1 for c in word if c.isupper()) if abbr_len == 0: abbr_len = len(word) command_table[word] = abbr_len return command_table def find_abbreviations(command_table): abbreviations = dict() for command, min_abbr_len in command_table.items(): for l in range(min_abbr_len, len(command)+1): abbr = command[:l].lower() abbreviations[abbr] = command.upper() return abbreviations def parse_user_string(user_string, abbreviations): user_words = [word.lower() for word in user_string.split()] commands = [abbreviations.get(user_word, "*error*") for user_word in user_words] return " ".join(commands) command_table = find_abbreviations_length(command_table_text) abbreviations_table = find_abbreviations(command_table) full_words = parse_user_string(user_words, abbreviations_table) print("user words:", user_words) print("full words:", full_words)
Generate a Python translation of this VB snippet without changing its computational steps.
Private Function ValidateUserWords(userstring As String) As String Dim s As String Dim user_words() As String Dim command_table As Scripting.Dictionary Set command_table = New Scripting.Dictionary Dim abbreviations As Scripting.Dictionary Set abbreviations = New Scripting.Dictionary abbreviations.CompareMode = TextCompare Dim commandtable() As String Dim commands As String s = s & "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " s = s & "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " s = s & "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " s = s & "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " s = s & "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " s = s & "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " s = s & "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up " commandtable = Split(s, " ") Dim i As Integer For Each word In commandtable If Len(word) > 0 Then i = 1 Do While Mid(word, i, 1) >= "A" And Mid(word, i, 1) <= "Z" i = i + 1 Loop command_table.Add Key:=word, Item:=i - 1 End If Next word For Each word In command_table For i = command_table(word) To Len(word) On Error Resume Next abbreviations.Add Key:=Left(word, i), Item:=UCase(word) Next i Next word user_words() = Split(userstring, " ") For Each word In user_words If Len(word) > 0 Then If abbreviations.exists(word) Then commands = commands & abbreviations(word) & " " Else commands = commands & "*error* " End If End If Next word ValidateUserWords = commands End Function Public Sub program() Dim guserstring As String guserstring = "riG rePEAT copies put mo rest types fup. 6 poweRin" Debug.Print "user words:", guserstring Debug.Print "full words:", ValidateUserWords(guserstring) End Sub
command_table_text = \ user_words = "riG rePEAT copies put mo rest types fup. 6 poweRin" def find_abbreviations_length(command_table_text): command_table = dict() for word in command_table_text.split(): abbr_len = sum(1 for c in word if c.isupper()) if abbr_len == 0: abbr_len = len(word) command_table[word] = abbr_len return command_table def find_abbreviations(command_table): abbreviations = dict() for command, min_abbr_len in command_table.items(): for l in range(min_abbr_len, len(command)+1): abbr = command[:l].lower() abbreviations[abbr] = command.upper() return abbreviations def parse_user_string(user_string, abbreviations): user_words = [word.lower() for word in user_string.split()] commands = [abbreviations.get(user_word, "*error*") for user_word in user_words] return " ".join(commands) command_table = find_abbreviations_length(command_table_text) abbreviations_table = find_abbreviations(command_table) full_words = parse_user_string(user_words, abbreviations_table) print("user words:", user_words) print("full words:", full_words)
Can you help me rewrite this code in Python instead of VB, keeping it the same logically?
Imports System.Text Module Module1 ReadOnly CODES As New Dictionary(Of Char, String) From { {"a", "AAAAA"}, {"b", "AAAAB"}, {"c", "AAABA"}, {"d", "AAABB"}, {"e", "AABAA"}, {"f", "AABAB"}, {"g", "AABBA"}, {"h", "AABBB"}, {"i", "ABAAA"}, {"j", "ABAAB"}, {"k", "ABABA"}, {"l", "ABABB"}, {"m", "ABBAA"}, {"n", "ABBAB"}, {"o", "ABBBA"}, {"p", "ABBBB"}, {"q", "BAAAA"}, {"r", "BAAAB"}, {"s", "BAABA"}, {"t", "BAABB"}, {"u", "BABAA"}, {"v", "BABAB"}, {"w", "BABBA"}, {"x", "BABBB"}, {"y", "BBAAA"}, {"z", "BBAAB"}, {" ", "BBBAA"} } Function Encode(plainText As String, message As String) As String Dim pt = plainText.ToLower() Dim sb As New StringBuilder() For Each c In pt If "a" <= c AndAlso c <= "z" Then sb.Append(CODES(c)) Else sb.Append(CODES(" ")) End If Next Dim et = sb.ToString() Dim mg = message.ToLower() sb.Length = 0 Dim count = 0 For Each c In mg If "a" <= c AndAlso c <= "z" Then If et(count) = "A" Then sb.Append(c) Else sb.Append(Chr(Asc(c) - 32)) End If count += 1 If count = et.Length Then Exit For End If Else sb.Append(c) End If Next Return sb.ToString() End Function Function Decode(message As String) As String Dim sb As New StringBuilder For Each c In message If "a" <= c AndAlso c <= "z" Then sb.Append("A") ElseIf "A" <= c AndAlso c <= "Z" Then sb.Append("B") End If Next Dim et = sb.ToString() sb.Length = 0 For index = 0 To et.Length - 1 Step 5 Dim quintet = et.Substring(index, 5) Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key sb.Append(key) Next Return sb.ToString() End Function Sub Main() Dim plainText = "the quick brown fox jumps over the lazy dog" Dim message = "bacon "this task is to implement a program for encryption and decryption of " + "plaintext using the simple alphabet of the baconian cipher or some " + "other kind of representation of this alphabet (make anything signify anything). " + "the baconian alphabet may optionally be extended to encode all lower " + "case characters individually and/or adding a few punctuation characters " + "such as the space." Dim cipherText = Encode(plainText, message) Console.WriteLine("Cipher text ->" & Environment.NewLine & "{0}", cipherText) Dim decodedText = Decode(cipherText) Console.WriteLine(Environment.NewLine & "Hidden text ->" & Environment.NewLine & "{0}", decodedText) End Sub End Module
import string sometext = .lower() lc2bin = {ch: '{:05b}'.format(i) for i, ch in enumerate(string.ascii_lowercase + ' .')} bin2lc = {val: key for key, val in lc2bin.items()} phrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower() def to_5binary(msg): return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower())) def encrypt(message, text): bin5 = to_5binary(message) textlist = list(text.lower()) out = [] for capitalise in bin5: while textlist: ch = textlist.pop(0) if ch.isalpha(): if capitalise: ch = ch.upper() out.append(ch) break else: out.append(ch) else: raise Exception('ERROR: Ran out of characters in sometext') return ''.join(out) + '...' def decrypt(bacontext): binary = [] bin5 = [] out = [] for ch in bacontext: if ch.isalpha(): binary.append('1' if ch.isupper() else '0') if len(binary) == 5: bin5 = ''.join(binary) out.append(bin2lc[bin5]) binary = [] return ''.join(out) print('PLAINTEXT = \n%s\n' % phrase) encrypted = encrypt(phrase, sometext) print('ENCRYPTED = \n%s\n' % encrypted) decrypted = decrypt(encrypted) print('DECRYPTED = \n%s\n' % decrypted) assert phrase == decrypted, 'Round-tripping error'
Ensure the translated Python code behaves exactly like the original VB snippet.
Imports System.Text Module Module1 ReadOnly CODES As New Dictionary(Of Char, String) From { {"a", "AAAAA"}, {"b", "AAAAB"}, {"c", "AAABA"}, {"d", "AAABB"}, {"e", "AABAA"}, {"f", "AABAB"}, {"g", "AABBA"}, {"h", "AABBB"}, {"i", "ABAAA"}, {"j", "ABAAB"}, {"k", "ABABA"}, {"l", "ABABB"}, {"m", "ABBAA"}, {"n", "ABBAB"}, {"o", "ABBBA"}, {"p", "ABBBB"}, {"q", "BAAAA"}, {"r", "BAAAB"}, {"s", "BAABA"}, {"t", "BAABB"}, {"u", "BABAA"}, {"v", "BABAB"}, {"w", "BABBA"}, {"x", "BABBB"}, {"y", "BBAAA"}, {"z", "BBAAB"}, {" ", "BBBAA"} } Function Encode(plainText As String, message As String) As String Dim pt = plainText.ToLower() Dim sb As New StringBuilder() For Each c In pt If "a" <= c AndAlso c <= "z" Then sb.Append(CODES(c)) Else sb.Append(CODES(" ")) End If Next Dim et = sb.ToString() Dim mg = message.ToLower() sb.Length = 0 Dim count = 0 For Each c In mg If "a" <= c AndAlso c <= "z" Then If et(count) = "A" Then sb.Append(c) Else sb.Append(Chr(Asc(c) - 32)) End If count += 1 If count = et.Length Then Exit For End If Else sb.Append(c) End If Next Return sb.ToString() End Function Function Decode(message As String) As String Dim sb As New StringBuilder For Each c In message If "a" <= c AndAlso c <= "z" Then sb.Append("A") ElseIf "A" <= c AndAlso c <= "Z" Then sb.Append("B") End If Next Dim et = sb.ToString() sb.Length = 0 For index = 0 To et.Length - 1 Step 5 Dim quintet = et.Substring(index, 5) Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key sb.Append(key) Next Return sb.ToString() End Function Sub Main() Dim plainText = "the quick brown fox jumps over the lazy dog" Dim message = "bacon "this task is to implement a program for encryption and decryption of " + "plaintext using the simple alphabet of the baconian cipher or some " + "other kind of representation of this alphabet (make anything signify anything). " + "the baconian alphabet may optionally be extended to encode all lower " + "case characters individually and/or adding a few punctuation characters " + "such as the space." Dim cipherText = Encode(plainText, message) Console.WriteLine("Cipher text ->" & Environment.NewLine & "{0}", cipherText) Dim decodedText = Decode(cipherText) Console.WriteLine(Environment.NewLine & "Hidden text ->" & Environment.NewLine & "{0}", decodedText) End Sub End Module
import string sometext = .lower() lc2bin = {ch: '{:05b}'.format(i) for i, ch in enumerate(string.ascii_lowercase + ' .')} bin2lc = {val: key for key, val in lc2bin.items()} phrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower() def to_5binary(msg): return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower())) def encrypt(message, text): bin5 = to_5binary(message) textlist = list(text.lower()) out = [] for capitalise in bin5: while textlist: ch = textlist.pop(0) if ch.isalpha(): if capitalise: ch = ch.upper() out.append(ch) break else: out.append(ch) else: raise Exception('ERROR: Ran out of characters in sometext') return ''.join(out) + '...' def decrypt(bacontext): binary = [] bin5 = [] out = [] for ch in bacontext: if ch.isalpha(): binary.append('1' if ch.isupper() else '0') if len(binary) == 5: bin5 = ''.join(binary) out.append(bin2lc[bin5]) binary = [] return ''.join(out) print('PLAINTEXT = \n%s\n' % phrase) encrypted = encrypt(phrase, sometext) print('ENCRYPTED = \n%s\n' % encrypted) decrypted = decrypt(encrypted) print('DECRYPTED = \n%s\n' % decrypted) assert phrase == decrypted, 'Round-tripping error'
Write a version of this VB function in Python with identical behavior.
Imports System.Text Module Module1 ReadOnly CODES As New Dictionary(Of Char, String) From { {"a", "AAAAA"}, {"b", "AAAAB"}, {"c", "AAABA"}, {"d", "AAABB"}, {"e", "AABAA"}, {"f", "AABAB"}, {"g", "AABBA"}, {"h", "AABBB"}, {"i", "ABAAA"}, {"j", "ABAAB"}, {"k", "ABABA"}, {"l", "ABABB"}, {"m", "ABBAA"}, {"n", "ABBAB"}, {"o", "ABBBA"}, {"p", "ABBBB"}, {"q", "BAAAA"}, {"r", "BAAAB"}, {"s", "BAABA"}, {"t", "BAABB"}, {"u", "BABAA"}, {"v", "BABAB"}, {"w", "BABBA"}, {"x", "BABBB"}, {"y", "BBAAA"}, {"z", "BBAAB"}, {" ", "BBBAA"} } Function Encode(plainText As String, message As String) As String Dim pt = plainText.ToLower() Dim sb As New StringBuilder() For Each c In pt If "a" <= c AndAlso c <= "z" Then sb.Append(CODES(c)) Else sb.Append(CODES(" ")) End If Next Dim et = sb.ToString() Dim mg = message.ToLower() sb.Length = 0 Dim count = 0 For Each c In mg If "a" <= c AndAlso c <= "z" Then If et(count) = "A" Then sb.Append(c) Else sb.Append(Chr(Asc(c) - 32)) End If count += 1 If count = et.Length Then Exit For End If Else sb.Append(c) End If Next Return sb.ToString() End Function Function Decode(message As String) As String Dim sb As New StringBuilder For Each c In message If "a" <= c AndAlso c <= "z" Then sb.Append("A") ElseIf "A" <= c AndAlso c <= "Z" Then sb.Append("B") End If Next Dim et = sb.ToString() sb.Length = 0 For index = 0 To et.Length - 1 Step 5 Dim quintet = et.Substring(index, 5) Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key sb.Append(key) Next Return sb.ToString() End Function Sub Main() Dim plainText = "the quick brown fox jumps over the lazy dog" Dim message = "bacon "this task is to implement a program for encryption and decryption of " + "plaintext using the simple alphabet of the baconian cipher or some " + "other kind of representation of this alphabet (make anything signify anything). " + "the baconian alphabet may optionally be extended to encode all lower " + "case characters individually and/or adding a few punctuation characters " + "such as the space." Dim cipherText = Encode(plainText, message) Console.WriteLine("Cipher text ->" & Environment.NewLine & "{0}", cipherText) Dim decodedText = Decode(cipherText) Console.WriteLine(Environment.NewLine & "Hidden text ->" & Environment.NewLine & "{0}", decodedText) End Sub End Module
import string sometext = .lower() lc2bin = {ch: '{:05b}'.format(i) for i, ch in enumerate(string.ascii_lowercase + ' .')} bin2lc = {val: key for key, val in lc2bin.items()} phrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower() def to_5binary(msg): return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower())) def encrypt(message, text): bin5 = to_5binary(message) textlist = list(text.lower()) out = [] for capitalise in bin5: while textlist: ch = textlist.pop(0) if ch.isalpha(): if capitalise: ch = ch.upper() out.append(ch) break else: out.append(ch) else: raise Exception('ERROR: Ran out of characters in sometext') return ''.join(out) + '...' def decrypt(bacontext): binary = [] bin5 = [] out = [] for ch in bacontext: if ch.isalpha(): binary.append('1' if ch.isupper() else '0') if len(binary) == 5: bin5 = ''.join(binary) out.append(bin2lc[bin5]) binary = [] return ''.join(out) print('PLAINTEXT = \n%s\n' % phrase) encrypted = encrypt(phrase, sometext) print('ENCRYPTED = \n%s\n' % encrypted) decrypted = decrypt(encrypted) print('DECRYPTED = \n%s\n' % decrypted) assert phrase == decrypted, 'Round-tripping error'
Write the same algorithm in Python as shown in this VB implementation.
Function build_spiral(n) botcol = 0 : topcol = n - 1 botrow = 0 : toprow = n - 1 Dim matrix() ReDim matrix(topcol,toprow) dir = 0 : col = 0 : row = 0 For i = 0 To n*n-1 matrix(col,row) = i Select Case dir Case 0 If col < topcol Then col = col + 1 Else dir = 1 : row = row + 1 : botrow = botrow + 1 End If Case 1 If row < toprow Then row = row + 1 Else dir = 2 : col = col - 1 : topcol = topcol - 1 End If Case 2 If col > botcol Then col = col - 1 Else dir = 3 : row = row - 1 : toprow = toprow - 1 End If Case 3 If row > botrow Then row = row - 1 Else dir = 0 : col = col + 1 : botcol = botcol + 1 End If End Select Next For y = 0 To n-1 For x = 0 To n-1 WScript.StdOut.Write matrix(x,y) & vbTab Next WScript.StdOut.WriteLine Next End Function build_spiral(CInt(WScript.Arguments(0)))
def spiral(n): dx,dy = 1,0 x,y = 0,0 myarray = [[None]* n for j in range(n)] for i in xrange(n**2): myarray[x][y] = i nx,ny = x+dx, y+dy if 0<=nx<n and 0<=ny<n and myarray[nx][ny] == None: x,y = nx,ny else: dx,dy = -dy,dx x,y = x+dx, y+dy return myarray def printspiral(myarray): n = range(len(myarray)) for y in n: for x in n: print "%2i" % myarray[x][y], print printspiral(spiral(5))
Produce a functionally identical Python code for the snippet given in VB.
Private Sub optional_parameters(theRange As String, _ Optional ordering As Integer = 0, _ Optional column As Integer = 1, _ Optional reverse As Integer = 1) ActiveSheet.Sort.SortFields.Clear ActiveSheet.Sort.SortFields.Add _ Key:=Range(theRange).Columns(column), _ SortOn:=SortOnValues, _ Order:=reverse, _ DataOption:=ordering With ActiveSheet.Sort .SetRange Range(theRange) .Header = xlGuess .MatchCase = False .Orientation = xlTopToBottom .SortMethod = xlPinYin .Apply End With End Sub Public Sub main() optional_parameters theRange:="A1:C4", ordering:=1, column:=2, reverse:=1 End Sub
>>> def printtable(data): for row in data: print ' '.join('%-5s' % ('"%s"' % cell) for cell in row) >>> import operator >>> def sorttable(table, ordering=None, column=0, reverse=False): return sorted(table, cmp=ordering, key=operator.itemgetter(column), reverse=reverse) >>> data = [["a", "b", "c"], ["", "q", "z"], ["zap", "zip", "Zot"]] >>> printtable(data) "a" "b" "c" "" "q" "z" "zap" "zip" "Zot" >>> printtable( sorttable(data) ) "" "q" "z" "a" "b" "c" "zap" "zip" "Zot" >>> printtable( sorttable(data, column=2) ) "zap" "zip" "Zot" "a" "b" "c" "" "q" "z" >>> printtable( sorttable(data, column=1) ) "a" "b" "c" "" "q" "z" "zap" "zip" "Zot" >>> printtable( sorttable(data, column=1, reverse=True) ) "zap" "zip" "Zot" "" "q" "z" "a" "b" "c" >>> printtable( sorttable(data, ordering=lambda a,b: cmp(len(b),len(a))) ) "zap" "zip" "Zot" "a" "b" "c" "" "q" "z" >>>
Convert the following code from VB to Python, ensuring the logic remains intact.
Declare Function CreateFileW Lib "Kernel32" (FileName As WString, DesiredAccess As Integer, ShareMode As Integer, SecurityAttributes As Integer, _ CreateDisposition As Integer, Flags As Integer, Template As Integer) As Integer Declare Function WriteFile Lib "Kernel32" (fHandle As Integer, writeData As Ptr, numOfBytes As Integer, ByRef numOfBytesWritten As Integer, _ overlapped As Ptr) As Boolean Declare Function GetLastError Lib "Kernel32" () As Integer Declare Function CloseHandle Lib "kernel32" (hObject As Integer) As Boolean Const FILE_SHARE_READ = &h00000001 Const FILE_SHARE_WRITE = &h00000002 Const OPEN_EXISTING = 3 Dim fHandle As Integer = CreateFileW("C:\foo.txt", 0, FILE_SHARE_READ Or FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0) If fHandle > 0 Then Dim mb As MemoryBlock = "Hello, World!" Dim bytesWritten As Integer If Not WriteFile(fHandle, mb, mb.Size, bytesWritten, Nil) Then MsgBox("Error Number: " + Str(GetLastError)) End If Call CloseHandle(fHandle) Else MsgBox("Error Number: " + Str(GetLastError)) End If
import ctypes libc = ctypes.CDLL("/lib/libc.so.6") libc.strcmp("abc", "def") libc.strcmp("hello", "hello")
Please provide an equivalent version of this VB code in Python.
Module Module1 Class Frac Private ReadOnly num As Long Private ReadOnly denom As Long Public Shared ReadOnly ZERO = New Frac(0, 1) Public Shared ReadOnly ONE = New Frac(1, 1) Public Sub New(n As Long, d As Long) If d = 0 Then Throw New ArgumentException("d must not be zero") End If Dim nn = n Dim dd = d If nn = 0 Then dd = 1 ElseIf dd < 0 Then nn = -nn dd = -dd End If Dim g = Math.Abs(Gcd(nn, dd)) If g > 1 Then nn /= g dd /= g End If num = nn denom = dd End Sub Private Shared Function Gcd(a As Long, b As Long) As Long If b = 0 Then Return a Else Return Gcd(b, a Mod b) End If End Function Public Shared Operator -(self As Frac) As Frac Return New Frac(-self.num, self.denom) End Operator Public Shared Operator +(lhs As Frac, rhs As Frac) As Frac Return New Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom) End Operator Public Shared Operator -(lhs As Frac, rhs As Frac) As Frac Return lhs + -rhs End Operator Public Shared Operator *(lhs As Frac, rhs As Frac) As Frac Return New Frac(lhs.num * rhs.num, lhs.denom * rhs.denom) End Operator Public Shared Operator <(lhs As Frac, rhs As Frac) As Boolean Dim x = lhs.num / lhs.denom Dim y = rhs.num / rhs.denom Return x < y End Operator Public Shared Operator >(lhs As Frac, rhs As Frac) As Boolean Dim x = lhs.num / lhs.denom Dim y = rhs.num / rhs.denom Return x > y End Operator Public Shared Operator =(lhs As Frac, rhs As Frac) As Boolean Return lhs.num = rhs.num AndAlso lhs.denom = rhs.denom End Operator Public Shared Operator <>(lhs As Frac, rhs As Frac) As Boolean Return lhs.num <> rhs.num OrElse lhs.denom <> rhs.denom End Operator Public Overrides Function ToString() As String If denom = 1 Then Return num.ToString Else Return String.Format("{0}/{1}", num, denom) End If End Function Public Overrides Function Equals(obj As Object) As Boolean Dim frac = CType(obj, Frac) Return Not IsNothing(frac) AndAlso num = frac.num AndAlso denom = frac.denom End Function End Class Function Bernoulli(n As Integer) As Frac If n < 0 Then Throw New ArgumentException("n may not be negative or zero") End If Dim a(n + 1) As Frac For m = 0 To n a(m) = New Frac(1, m + 1) For j = m To 1 Step -1 a(j - 1) = (a(j - 1) - a(j)) * New Frac(j, 1) Next Next If n <> 1 Then Return a(0) Else Return -a(0) End If End Function Function Binomial(n As Integer, k As Integer) As Integer If n < 0 OrElse k < 0 OrElse n < k Then Throw New ArgumentException() End If If n = 0 OrElse k = 0 Then Return 1 End If Dim num = 1 For i = k + 1 To n num *= i Next Dim denom = 1 For i = 2 To n - k denom *= i Next Return num \ denom End Function Function FaulhaberTriangle(p As Integer) As Frac() Dim coeffs(p + 1) As Frac For i = 1 To p + 1 coeffs(i - 1) = Frac.ZERO Next Dim q As New Frac(1, p + 1) Dim sign = -1 For j = 0 To p sign *= -1 coeffs(p - j) = q * New Frac(sign, 1) * New Frac(Binomial(p + 1, j), 1) * Bernoulli(j) Next Return coeffs End Function Sub Main() For i = 1 To 10 Dim coeffs = FaulhaberTriangle(i - 1) For Each coeff In coeffs Console.Write("{0,5} ", coeff) Next Console.WriteLine() Next End Sub End Module
from itertools import accumulate, chain, count, islice from fractions import Fraction def faulhaberTriangle(m): def go(rs, n): def f(x, y): return Fraction(n, x) * y xs = list(map(f, islice(count(2), m), rs)) return [Fraction(1 - sum(xs), 1)] + xs return list(accumulate( [[]] + list(islice(count(0), 1 + m)), go ))[1:] def faulhaberSum(p, n): def go(x, y): return y * (n ** x) return sum( map(go, count(1), faulhaberTriangle(p)[-1]) ) def main(): fs = faulhaberTriangle(9) print( fTable(__doc__ + ':\n')(str)( compose(concat)( fmap(showRatio(3)(3)) ) )( index(fs) )(range(0, len(fs))) ) print('') print( faulhaberSum(17, 1000) ) def fTable(s): def gox(xShow): def gofx(fxShow): def gof(f): def goxs(xs): ys = [xShow(x) for x in xs] w = max(map(len, ys)) def arrowed(x, y): return y.rjust(w, ' ') + ' -> ' + ( fxShow(f(x)) ) return s + '\n' + '\n'.join( map(arrowed, xs, ys) ) return goxs return gof return gofx return gox def compose(g): return lambda f: lambda x: g(f(x)) def concat(xs): def f(ys): zs = list(chain(*ys)) return ''.join(zs) if isinstance(ys[0], str) else zs return ( f(xs) if isinstance(xs, list) else ( chain.from_iterable(xs) ) ) if xs else [] def fmap(f): def go(xs): return list(map(f, xs)) return go def index(xs): return lambda n: None if 0 > n else ( xs[n] if ( hasattr(xs, "__getitem__") ) else next(islice(xs, n, None)) ) def showRatio(m): def go(n): def f(r): d = r.denominator return str(r.numerator).rjust(m, ' ') + ( ('/' + str(d).ljust(n, ' ')) if 1 != d else ( ' ' * (1 + n) ) ) return f return go if __name__ == '__main__': main()
Maintain the same structure and functionality when rewriting this code in Python.
Function Run(args() as String) As Integer For each arg As String In args Stdout.WriteLine(arg) Next End Function
import sys program_name = sys.argv[0] arguments = sys.argv[1:] count = len(arguments)
Convert this VB snippet to Python and keep its semantics consistent.
Function Run(args() as String) As Integer For each arg As String In args Stdout.WriteLine(arg) Next End Function
import sys program_name = sys.argv[0] arguments = sys.argv[1:] count = len(arguments)
Rewrite this program in Python while keeping its functionality equivalent to the VB version.
Const wheel="ndeokgelw" Sub print(s): On Error Resume Next WScript.stdout.WriteLine (s) If err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit End Sub Dim oDic Set oDic = WScript.CreateObject("scripting.dictionary") Dim cnt(127) Dim fso Set fso = WScript.CreateObject("Scripting.Filesystemobject") Set ff=fso.OpenTextFile("unixdict.txt") i=0 print "reading words of 3 or more letters" While Not ff.AtEndOfStream x=LCase(ff.ReadLine) If Len(x)>=3 Then If Not odic.exists(x) Then oDic.Add x,0 End If Wend print "remaining words: "& oDic.Count & vbcrlf ff.Close Set ff=Nothing Set fso=Nothing Set re=New RegExp print "removing words with chars not in the wheel" re.pattern="[^"& wheel &"]" For Each w In oDic.Keys If re.test(w) Then oDic.remove(w) Next print "remaining words: "& oDic.Count & vbcrlf print "ensuring the mandatory letter "& Mid(wheel,5,1) & " is present" re.Pattern=Mid(wheel,5,1) For Each w In oDic.Keys If Not re.test(w) Then oDic.remove(w) Next print "remaining words: "& oDic.Count & vbcrlf print "checking number of chars" Dim nDic Set nDic = WScript.CreateObject("scripting.dictionary") For i=1 To Len(wheel) x=Mid(wheel,i,1) If nDic.Exists(x) Then a=nDic(x) nDic(x)=Array(a(0)+1,0) Else nDic.add x,Array(1,0) End If Next For Each w In oDic.Keys For Each c In nDic.Keys ndic(c)=Array(nDic(c)(0),0) Next For ii = 1 To len(w) c=Mid(w,ii,1) a=nDic(c) If (a(0)=a(1)) Then oDic.Remove(w):Exit For End If nDic(c)=Array(a(0),a(1)+1) Next Next print "Remaining words "& oDic.count For Each w In oDic.Keys print w Next
import urllib.request from collections import Counter GRID = def getwords(url='http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'): "Return lowercased words of 3 to 9 characters" words = urllib.request.urlopen(url).read().decode().strip().lower().split() return (w for w in words if 2 < len(w) < 10) def solve(grid, dictionary): gridcount = Counter(grid) mid = grid[4] return [word for word in dictionary if mid in word and not (Counter(word) - gridcount)] if __name__ == '__main__': chars = ''.join(GRID.strip().lower().split()) found = solve(chars, dictionary=getwords()) print('\n'.join(found))
Ensure the translated Python code behaves exactly like the original VB snippet.
DEFINT A(1 to 4) = {1, 2, 3, 4} DEFINT B(1 to 4) = {10, 20, 30, 40} Redim A(1 to 8) as integer MEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)
arr1 = [1, 2, 3] arr2 = [4, 5, 6] arr3 = [7, 8, 9] arr4 = arr1 + arr2 assert arr4 == [1, 2, 3, 4, 5, 6] arr4.extend(arr3) assert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]
Generate an equivalent Python version of this VB code.
Public Sub text() Debug.Print InputBox("Input a string") Debug.Print InputBox("Input the integer 75000", "Input an integer", 75000, Context = "Long") End Sub
string = raw_input("Input a string: ")
Keep all operations the same but rewrite the snippet in Python.
Public Sub text() Debug.Print InputBox("Input a string") Debug.Print InputBox("Input the integer 75000", "Input an integer", 75000, Context = "Long") End Sub
string = raw_input("Input a string: ")
Produce a language-to-language conversion: from VB to Python, same semantics.
Option Explicit Declare Function Beep Lib "kernel32" (ByVal Freq As Long, ByVal Dur As Long) As Long Sub Musical_Scale() Dim Fqs, i As Integer Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528) For i = LBound(Fqs) To UBound(Fqs) Beep Fqs(i), 500 Next End Sub
>>> import winsound >>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]: winsound.Beep(int(note+.5), 500) >>>
Translate this program into Python but keep the logic exactly as in VB.
Option Explicit Declare Function Beep Lib "kernel32" (ByVal Freq As Long, ByVal Dur As Long) As Long Sub Musical_Scale() Dim Fqs, i As Integer Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528) For i = LBound(Fqs) To UBound(Fqs) Beep Fqs(i), 500 Next End Sub
>>> import winsound >>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]: winsound.Beep(int(note+.5), 500) >>>
Rewrite this program in Python while keeping its functionality equivalent to the VB version.
Option Explicit Const maxWeight = 400 Dim DataList As Variant Dim xList(64, 3) As Variant Dim nItems As Integer Dim s As String, xss As String Dim xwei As Integer, xval As Integer, nn As Integer Sub Main() Dim i As Integer, j As Integer DataList = Array("map", 9, 150, "compass", 13, 35, "water", 153, 200, "sandwich", 50, 160, _ "glucose", 15, 60, "tin", 68, 45, "banana", 27, 60, "apple", 39, 40, _ "cheese", 23, 30, "beer", 52, 10, "suntan cream", 11, 70, "camera", 32, 30, _ "T-shirt", 24, 15, "trousers", 48, 10, "umbrella", 73, 40, "book", 30, 10, _ "waterproof trousers", 42, 70, "waterproof overclothes", 43, 75, _ "note-case", 22, 80, "sunglasses", 7, 20, "towel", 18, 12, "socks", 4, 50) nItems = (UBound(DataList) + 1) / 3 j = 0 For i = 1 To nItems xList(i, 1) = DataList(j) xList(i, 2) = DataList(j + 1) xList(i, 3) = DataList(j + 2) j = j + 3 Next i s = "" For i = 1 To nItems s = s & Chr(i) Next nn = 0 Call ChoiceBin(1, "") For i = 1 To Len(xss) j = Asc(Mid(xss, i, 1)) Debug.Print xList(j, 1) Next i Debug.Print "count=" & Len(xss), "weight=" & xwei, "value=" & xval End Sub Private Sub ChoiceBin(n As String, ss As String) Dim r As String Dim i As Integer, j As Integer, iwei As Integer, ival As Integer Dim ipct As Integer If n = Len(s) + 1 Then iwei = 0: ival = 0 For i = 1 To Len(ss) j = Asc(Mid(ss, i, 1)) iwei = iwei + xList(j, 2) ival = ival + xList(j, 3) Next If iwei <= maxWeight And ival > xval Then xss = ss: xwei = iwei: xval = ival End If Else r = Mid(s, n, 1) Call ChoiceBin(n + 1, ss & r) Call ChoiceBin(n + 1, ss) End If End Sub
from itertools import combinations def anycomb(items): ' return combinations of any length from the items ' return ( comb for r in range(1, len(items)+1) for comb in combinations(items, r) ) def totalvalue(comb): ' Totalise a particular combination of items' totwt = totval = 0 for item, wt, val in comb: totwt += wt totval += val return (totval, -totwt) if totwt <= 400 else (0, 0) items = ( ("map", 9, 150), ("compass", 13, 35), ("water", 153, 200), ("sandwich", 50, 160), ("glucose", 15, 60), ("tin", 68, 45), ("banana", 27, 60), ("apple", 39, 40), ("cheese", 23, 30), ("beer", 52, 10), ("suntan cream", 11, 70), ("camera", 32, 30), ("t-shirt", 24, 15), ("trousers", 48, 10), ("umbrella", 73, 40), ("waterproof trousers", 42, 70), ("waterproof overclothes", 43, 75), ("note-case", 22, 80), ("sunglasses", 7, 20), ("towel", 18, 12), ("socks", 4, 50), ("book", 30, 10), ) bagged = max( anycomb(items), key=totalvalue) print("Bagged the following items\n " + '\n '.join(sorted(item for item,_,_ in bagged))) val, wt = totalvalue(bagged) print("for a total value of %i and a total weight of %i" % (val, -wt))
Ensure the translated Python code behaves exactly like the original VB snippet.
Imports System.Math Module Module1 Const MAXPRIME = 99 Const MAXPARENT = 99 Const NBRCHILDREN = 547100 Public Primes As New Collection() Public PrimesR As New Collection() Public Ancestors As New Collection() Public Parents(MAXPARENT + 1) As Integer Public CptDescendants(MAXPARENT + 1) As Integer Public Children(NBRCHILDREN) As ChildStruct Public iChildren As Integer Public Delimiter As String = ", " Public Structure ChildStruct Public Child As Long Public pLower As Integer Public pHigher As Integer End Structure Sub Main() Dim Parent As Short Dim Sum As Short Dim i As Short Dim TotDesc As Integer = 0 Dim MidPrime As Integer If GetPrimes(Primes, MAXPRIME) = vbFalse Then Return End If For i = Primes.Count To 1 Step -1 PrimesR.Add(Primes.Item(i)) Next MidPrime = PrimesR.Item(1) / 2 For Each Prime In PrimesR Parents(Prime) = InsertChild(Parents(Prime), Prime) CptDescendants(Prime) += 1 If Prime > MidPrime Then Continue For End If For Parent = 1 To MAXPARENT Sum = Parent + Prime If Sum > MAXPARENT Then Exit For End If If Parents(Parent) Then InsertPreorder(Parents(Parent), Sum, Prime) CptDescendants(Sum) += CptDescendants(Parent) End If Next Next RemoveFalseChildren() If MAXPARENT > MAXPRIME Then If GetPrimes(Primes, MAXPARENT) = vbFalse Then Return End If End If FileOpen(1, "Ancestors.txt", OpenMode.Output) For Parent = 1 To MAXPARENT GetAncestors(Parent) PrintLine(1, "[" & Parent.ToString & "] Level: " & Ancestors.Count.ToString) If Ancestors.Count Then Print(1, "Ancestors: " & Ancestors.Item(1).ToString) For i = 2 To Ancestors.Count Print(1, ", " & Ancestors.Item(i).ToString) Next PrintLine(1) Ancestors.Clear() Else PrintLine(1, "Ancestors: None") End If If CptDescendants(Parent) Then PrintLine(1, "Descendants: " & CptDescendants(Parent).ToString) Delimiter = "" PrintDescendants(Parents(Parent)) PrintLine(1) TotDesc += CptDescendants(Parent) Else PrintLine(1, "Descendants: None") End If PrintLine(1) Next Primes.Clear() PrimesR.Clear() PrintLine(1, "Total descendants " & TotDesc.ToString) PrintLine(1) FileClose(1) End Sub Function InsertPreorder(_index As Integer, _sum As Short, _prime As Short) Parents(_sum) = InsertChild(Parents(_sum), Children(_index).Child * _prime) If Children(_index).pLower Then InsertPreorder(Children(_index).pLower, _sum, _prime) End If If Children(_index).pHigher Then InsertPreorder(Children(_index).pHigher, _sum, _prime) End If Return Nothing End Function Function InsertChild(_index As Integer, _child As Long) As Integer If _index Then If _child <= Children(_index).Child Then Children(_index).pLower = InsertChild(Children(_index).pLower, _child) Else Children(_index).pHigher = InsertChild(Children(_index).pHigher, _child) End If Else iChildren += 1 _index = iChildren Children(_index).Child = _child Children(_index).pLower = 0 Children(_index).pHigher = 0 End If Return _index End Function Function RemoveFalseChildren() Dim Exclusions As New Collection Exclusions.Add(4) For Each Prime In Primes Exclusions.Add(Prime) Next For Each ex In Exclusions Parents(ex) = Children(Parents(ex)).pHigher CptDescendants(ex) -= 1 Next Exclusions.Clear() Return Nothing End Function Function GetAncestors(_child As Short) Dim Child As Short = _child Dim Parent As Short = 0 For Each Prime In Primes If Child = 1 Then Exit For End If While Child Mod Prime = 0 Child /= Prime Parent += Prime End While Next If Parent = _child Or _child = 1 Then Return Nothing End If GetAncestors(Parent) Ancestors.Add(Parent) Return Nothing End Function Function PrintDescendants(_index As Integer) If Children(_index).pLower Then PrintDescendants(Children(_index).pLower) End If Print(1, Delimiter.ToString & Children(_index).Child.ToString) Delimiter = ", " If Children(_index).pHigher Then PrintDescendants(Children(_index).pHigher) End If Return Nothing End Function Function GetPrimes(ByRef _primes As Object, Optional _maxPrime As Integer = 2) As Boolean Dim Value As Integer = 3 Dim Max As Integer Dim Prime As Integer If _maxPrime < 2 Then Return vbFalse End If _primes.Add(2) While Value <= _maxPrime Max = Floor(Sqrt(Value)) For Each Prime In _primes If Prime > Max Then _primes.Add(Value) Exit For End If If Value Mod Prime = 0 Then Exit For End If Next Value += 2 End While Return vbTrue End Function End Module
from __future__ import print_function from itertools import takewhile maxsum = 99 def get_primes(max): if max < 2: return [] lprimes = [2] for x in range(3, max + 1, 2): for p in lprimes: if x % p == 0: break else: lprimes.append(x) return lprimes descendants = [[] for _ in range(maxsum + 1)] ancestors = [[] for _ in range(maxsum + 1)] primes = get_primes(maxsum) for p in primes: descendants[p].append(p) for s in range(1, len(descendants) - p): descendants[s + p] += [p * pr for pr in descendants[s]] for p in primes + [4]: descendants[p].pop() total = 0 for s in range(1, maxsum + 1): descendants[s].sort() for d in takewhile(lambda x: x <= maxsum, descendants[s]): ancestors[d] = ancestors[s] + [s] print([s], "Level:", len(ancestors[s])) print("Ancestors:", ancestors[s] if len(ancestors[s]) else "None") print("Descendants:", len(descendants[s]) if len(descendants[s]) else "None") if len(descendants[s]): print(descendants[s]) print() total += len(descendants[s]) print("Total descendants", total)
Transform the following VB implementation into Python, maintaining the same output and logic.
Imports System.Runtime.CompilerServices Module Module1 <Extension()> Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T)) Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)} Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item})) End Function Sub Main() Dim empty(-1) As Integer Dim list1 = {1, 2} Dim list2 = {3, 4} Dim list3 = {1776, 1789} Dim list4 = {7, 12} Dim list5 = {4, 14, 23} Dim list6 = {0, 1} Dim list7 = {1, 2, 3} Dim list8 = {30} Dim list9 = {500, 100} For Each sequnceList As Integer()() In { ({list1, list2}), ({list2, list1}), ({list1, empty}), ({empty, list1}), ({list3, list4, list5, list6}), ({list7, list8, list9}), ({list7, empty, list9}) } Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $"({String.Join(", ", tuple)})") Console.WriteLine($"{{{String.Join(", ", cart)}}}") Next End Sub End Module
import itertools def cp(lsts): return list(itertools.product(*lsts)) if __name__ == '__main__': from pprint import pprint as pp for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []], ((1776, 1789), (7, 12), (4, 14, 23), (0, 1)), ((1, 2, 3), (30,), (500, 100)), ((1, 2, 3), (), (500, 100))]: print(lists, '=>') pp(cp(lists), indent=2)
Generate an equivalent Python version of this VB code.
Imports System.Runtime.CompilerServices Module Module1 <Extension()> Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T)) Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)} Return sequences.Aggregate(emptyProduct, Function(accumulator, sequence) From acc In accumulator From item In sequence Select acc.Concat({item})) End Function Sub Main() Dim empty(-1) As Integer Dim list1 = {1, 2} Dim list2 = {3, 4} Dim list3 = {1776, 1789} Dim list4 = {7, 12} Dim list5 = {4, 14, 23} Dim list6 = {0, 1} Dim list7 = {1, 2, 3} Dim list8 = {30} Dim list9 = {500, 100} For Each sequnceList As Integer()() In { ({list1, list2}), ({list2, list1}), ({list1, empty}), ({empty, list1}), ({list3, list4, list5, list6}), ({list7, list8, list9}), ({list7, empty, list9}) } Dim cart = sequnceList.CartesianProduct().Select(Function(tuple) $"({String.Join(", ", tuple)})") Console.WriteLine($"{{{String.Join(", ", cart)}}}") Next End Sub End Module
import itertools def cp(lsts): return list(itertools.product(*lsts)) if __name__ == '__main__': from pprint import pprint as pp for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []], ((1776, 1789), (7, 12), (4, 14, 23), (0, 1)), ((1, 2, 3), (30,), (500, 100)), ((1, 2, 3), (), (500, 100))]: print(lists, '=>') pp(cp(lists), indent=2)
Produce a language-to-language conversion: from VB to Python, same semantics.
dim _proper_divisors(100) sub proper_divisors(n) dim i dim _proper_divisors_count = 0 if n <> 1 then for i = 1 to (n \ 2) if n %% i = 0 then _proper_divisors_count = _proper_divisors_count + 1 _proper_divisors(_proper_divisors_count) = i end if next end if return _proper_divisors_count end sub sub show_proper_divisors(n, tabbed) dim cnt = proper_divisors(n) print str$(n) + ":"; tab(4);"(" + str$(cnt) + " items) "; dim j for j = 1 to cnt if tabbed then print str$(_proper_divisors(j)), else print str$(_proper_divisors(j)); end if if (j < cnt) then print ","; next print end sub dim i for i = 1 to 10 show_proper_divisors(i, false) next dim c dim maxindex = 0 dim maxlength = 0 for t = 1 to 20000 c = proper_divisors(t) if c > maxlength then maxindex = t maxlength = c end if next print "A maximum at "; show_proper_divisors(maxindex, false)
>>> def proper_divs2(n): ... return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x} ... >>> [proper_divs2(n) for n in range(1, 11)] [set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}] >>> >>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1]) >>> n 15120 >>> length 79 >>>
Write a version of this VB function in Python with identical behavior.
Module XMLOutput Sub Main() Dim charRemarks As New Dictionary(Of String, String) charRemarks.Add("April", "Bubbly: I charRemarks.Add("Tam O charRemarks.Add("Emily", "Short & shrift") Dim xml = <CharacterRemarks> <%= From cr In charRemarks Select <Character name=<%= cr.Key %>><%= cr.Value %></Character> %> </CharacterRemarks> Console.WriteLine(xml) End Sub End Module
>>> from xml.etree import ElementTree as ET >>> from itertools import izip >>> def characterstoxml(names, remarks): root = ET.Element("CharacterRemarks") for name, remark in izip(names, remarks): c = ET.SubElement(root, "Character", {'name': name}) c.text = remark return ET.tostring(root) >>> print characterstoxml( names = ["April", "Tam O'Shanter", "Emily"], remarks = [ "Bubbly: I'm > Tam and <= Emily", 'Burns: "When chapman billies leave the street ..."', 'Short & shrift' ] ).replace('><','>\n<')
Write a version of this VB function in Python with identical behavior.
Private Sub plot_coordinate_pairs(x As Variant, y As Variant) Dim chrt As Chart Set chrt = ActiveSheet.Shapes.AddChart.Chart With chrt .ChartType = xlLine .HasLegend = False .HasTitle = True .ChartTitle.Text = "Time" .SeriesCollection.NewSeries .SeriesCollection.Item(1).XValues = x .SeriesCollection.Item(1).Values = y .Axes(xlValue, xlPrimary).HasTitle = True .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "microseconds" End With End Sub Public Sub main() x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}] y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}] plot_coordinate_pairs x, y End Sub
>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0] >>> import pylab >>> pylab.plot(x, y, 'bo') >>> pylab.savefig('qsort-range-10-9.png')
Rewrite this program in Python while keeping its functionality equivalent to the VB version.
Private Sub plot_coordinate_pairs(x As Variant, y As Variant) Dim chrt As Chart Set chrt = ActiveSheet.Shapes.AddChart.Chart With chrt .ChartType = xlLine .HasLegend = False .HasTitle = True .ChartTitle.Text = "Time" .SeriesCollection.NewSeries .SeriesCollection.Item(1).XValues = x .SeriesCollection.Item(1).Values = y .Axes(xlValue, xlPrimary).HasTitle = True .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "microseconds" End With End Sub Public Sub main() x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}] y = [{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}] plot_coordinate_pairs x, y End Sub
>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0] >>> import pylab >>> pylab.plot(x, y, 'bo') >>> pylab.savefig('qsort-range-10-9.png')
Transform the following VB implementation into Python, maintaining the same output and logic.
text = "I need more coffee!!!" Set regex = New RegExp regex.Global = True regex.Pattern = "\s" If regex.Test(text) Then WScript.StdOut.Write regex.Replace(text,vbCrLf) Else WScript.StdOut.Write "No matching pattern" End If
import re string = "This is a string" if re.search('string$', string): print("Ends with string.") string = re.sub(" a ", " another ", string) print(string)
Please provide an equivalent version of this VB code in Python.
Set dict = CreateObject("Scripting.Dictionary") os = Array("Windows", "Linux", "MacOS") owner = Array("Microsoft", "Linus Torvalds", "Apple") For n = 0 To 2 dict.Add os(n), owner(n) Next MsgBox dict.Item("Linux") MsgBox dict.Item("MacOS") MsgBox dict.Item("Windows")
keys = ['a', 'b', 'c'] values = [1, 2, 3] hash = {key: value for key, value in zip(keys, values)}
Change the programming language of this snippet from VB to Python without modifying what it does.
Public Class Main Inherits System.Windows.Forms.Form Public Sub New() Me.FormBorderStyle = FormBorderStyle.None Me.WindowState = FormWindowState.Maximized End Sub Private Sub Main_Load(sender As Object, e As EventArgs) Handles Me.Load Dim Index As Integer Dim Colors() As Color = {Color.Black, Color.Red, Color.Green, Color.Magenta, Color.Cyan, Color.Yellow, Color.White} Dim Height = (Me.ClientSize.Height / 4) + 1 For y = 1 To 4 Dim Top = Me.ClientSize.Height / 4 * (y - 1) For x = 0 To Me.ClientSize.Width Step y If Index = 6 Then Index = 0 Else Index += 1 Me.Controls.Add(New Panel With {.Top = Top, .Height = Height, .Left = x, .Width = y, .BackColor = Colors(Index)}) Next Next End Sub End Class
from turtle import * colors = ["black", "red", "green", "blue", "magenta", "cyan", "yellow", "white"] screen = getscreen() left_edge = -screen.window_width()//2 right_edge = screen.window_width()//2 quarter_height = screen.window_height()//4 half_height = quarter_height * 2 speed("fastest") for quarter in range(4): pensize(quarter+1) colornum = 0 min_y = half_height - ((quarter + 1) * quarter_height) max_y = half_height - ((quarter) * quarter_height) for x in range(left_edge,right_edge,quarter+1): penup() pencolor(colors[colornum]) colornum = (colornum + 1) % len(colors) setposition(x,min_y) pendown() setposition(x,max_y) notused = input("Hit enter to continue: ")
Can you help me rewrite this code in Python instead of VB, keeping it the same logically?
Function cocktailShakerSort(ByVal A As Variant) As Variant beginIdx = LBound(A) endIdx = UBound(A) - 1 Do While beginIdx <= endIdx newBeginIdx = endIdx newEndIdx = beginIdx For ii = beginIdx To endIdx If A(ii) > A(ii + 1) Then tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp newEndIdx = ii End If Next ii endIdx = newEndIdx - 1 For ii = endIdx To beginIdx Step -1 If A(ii) > A(ii + 1) Then tmp = A(ii): A(ii) = A(ii + 1): A(ii + 1) = tmp newBeginIdx = ii End If Next ii beginIdx = newBeginIdx + 1 Loop cocktailShakerSort = A End Function Public Sub main() Dim B(20) As Variant For i = LBound(B) To UBound(B) B(i) = Int(Rnd() * 100) Next i Debug.Print Join(B, ", ") Debug.Print Join(cocktailShakerSort(B), ", ") End Sub
def cocktailshiftingbounds(A): beginIdx = 0 endIdx = len(A) - 1 while beginIdx <= endIdx: newBeginIdx = endIdx newEndIdx = beginIdx for ii in range(beginIdx,endIdx): if A[ii] > A[ii + 1]: A[ii+1], A[ii] = A[ii], A[ii+1] newEndIdx = ii endIdx = newEndIdx for ii in range(endIdx,beginIdx-1,-1): if A[ii] > A[ii + 1]: A[ii+1], A[ii] = A[ii], A[ii+1] newBeginIdx = ii beginIdx = newBeginIdx + 1 test1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0] cocktailshiftingbounds(test1) print(test1) test2=list('big fjords vex quick waltz nymph') cocktailshiftingbounds(test2) print(''.join(test2))
Maintain the same structure and functionality when rewriting this code in Python.
option explicit const dt = 0.15 const length=23 dim ans0:ans0=chr(27)&"[" dim Veloc,Accel,angle,olr,olc,r,c const r0=1 const c0=40 cls angle=0.7 while 1 wscript.sleep(50) Accel = -.9 * sin(Angle) Veloc = Veloc + Accel * dt Angle = Angle + Veloc * dt r = r0 + int(cos(Angle) * Length) c = c0+ int(2*sin(Angle) * Length) cls draw_line r,c,r0,c0 toxy r,c,"O" olr=r :olc=c wend sub cls() wscript.StdOut.Write ans0 &"2J"&ans0 &"?25l":end sub sub toxy(r,c,s) wscript.StdOut.Write ans0 & r & ";" & c & "f" & s :end sub Sub draw_line(r1,c1, r2,c2) Dim x,y,xf,yf,dx,dy,sx,sy,err,err2 x =r1 : y =c1 xf=r2 : yf=c2 dx=Abs(xf-x) : dy=Abs(yf-y) If x<xf Then sx=+1: Else sx=-1 If y<yf Then sy=+1: Else sy=-1 err=dx-dy Do toxy x,y,"." If x=xf And y=yf Then Exit Do err2=err+err If err2>-dy Then err=err-dy: x=x+sx If err2< dx Then err=err+dx: y=y+sy Loop End Sub
import pygame, sys from pygame.locals import * from math import sin, cos, radians pygame.init() WINDOWSIZE = 250 TIMETICK = 100 BOBSIZE = 15 window = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE)) pygame.display.set_caption("Pendulum") screen = pygame.display.get_surface() screen.fill((255,255,255)) PIVOT = (WINDOWSIZE/2, WINDOWSIZE/10) SWINGLENGTH = PIVOT[1]*4 class BobMass(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.theta = 45 self.dtheta = 0 self.rect = pygame.Rect(PIVOT[0]-SWINGLENGTH*cos(radians(self.theta)), PIVOT[1]+SWINGLENGTH*sin(radians(self.theta)), 1,1) self.draw() def recomputeAngle(self): scaling = 3000.0/(SWINGLENGTH**2) firstDDtheta = -sin(radians(self.theta))*scaling midDtheta = self.dtheta + firstDDtheta midtheta = self.theta + (self.dtheta + midDtheta)/2.0 midDDtheta = -sin(radians(midtheta))*scaling midDtheta = self.dtheta + (firstDDtheta + midDDtheta)/2 midtheta = self.theta + (self.dtheta + midDtheta)/2 midDDtheta = -sin(radians(midtheta)) * scaling lastDtheta = midDtheta + midDDtheta lasttheta = midtheta + (midDtheta + lastDtheta)/2.0 lastDDtheta = -sin(radians(lasttheta)) * scaling lastDtheta = midDtheta + (midDDtheta + lastDDtheta)/2.0 lasttheta = midtheta + (midDtheta + lastDtheta)/2.0 self.dtheta = lastDtheta self.theta = lasttheta self.rect = pygame.Rect(PIVOT[0]- SWINGLENGTH*sin(radians(self.theta)), PIVOT[1]+ SWINGLENGTH*cos(radians(self.theta)),1,1) def draw(self): pygame.draw.circle(screen, (0,0,0), PIVOT, 5, 0) pygame.draw.circle(screen, (0,0,0), self.rect.center, BOBSIZE, 0) pygame.draw.aaline(screen, (0,0,0), PIVOT, self.rect.center) pygame.draw.line(screen, (0,0,0), (0, PIVOT[1]), (WINDOWSIZE, PIVOT[1])) def update(self): self.recomputeAngle() screen.fill((255,255,255)) self.draw() bob = BobMass() TICK = USEREVENT + 2 pygame.time.set_timer(TICK, TIMETICK) def input(events): for event in events: if event.type == QUIT: sys.exit(0) elif event.type == TICK: bob.update() while True: input(pygame.event.get()) pygame.display.flip()
Convert this VB snippet to Python and keep its semantics consistent.
Function Encoder(ByVal n) Encoder = n Xor (n \ 2) End Function Function Decoder(ByVal n) Dim g : g = 0 Do While n > 0 g = g Xor n n = n \ 2 Loop Decoder = g End Function Function Dec2bin(ByVal n, ByVal length) Dim i, strbin : strbin = "" For i = 1 to 5 strbin = (n Mod 2) & strbin n = n \ 2 Next Dec2Bin = strbin End Function WScript.StdOut.WriteLine("Binary -> Gray Code -> Binary") For i = 0 to 31 encoded = Encoder(i) decoded = Decoder(encoded) WScript.StdOut.WriteLine(Dec2Bin(i, 5) & " -> " & Dec2Bin(encoded, 5) & " -> " & Dec2Bin(decoded, 5)) Next
>>> def int2bin(n): 'From positive integer to list of binary bits, msb at index 0' if n: bits = [] while n: n,remainder = divmod(n, 2) bits.insert(0, remainder) return bits else: return [0] >>> def bin2int(bits): 'From binary bits, msb at index 0 to integer' i = 0 for bit in bits: i = i * 2 + bit return i
Write the same code in Python as shown below in VB.
Function Encoder(ByVal n) Encoder = n Xor (n \ 2) End Function Function Decoder(ByVal n) Dim g : g = 0 Do While n > 0 g = g Xor n n = n \ 2 Loop Decoder = g End Function Function Dec2bin(ByVal n, ByVal length) Dim i, strbin : strbin = "" For i = 1 to 5 strbin = (n Mod 2) & strbin n = n \ 2 Next Dec2Bin = strbin End Function WScript.StdOut.WriteLine("Binary -> Gray Code -> Binary") For i = 0 to 31 encoded = Encoder(i) decoded = Decoder(encoded) WScript.StdOut.WriteLine(Dec2Bin(i, 5) & " -> " & Dec2Bin(encoded, 5) & " -> " & Dec2Bin(decoded, 5)) Next
>>> def int2bin(n): 'From positive integer to list of binary bits, msb at index 0' if n: bits = [] while n: n,remainder = divmod(n, 2) bits.insert(0, remainder) return bits else: return [0] >>> def bin2int(bits): 'From binary bits, msb at index 0 to integer' i = 0 for bit in bits: i = i * 2 + bit return i
Rewrite the snippet below in Python so it works the same as the original VB code.
Function Encoder(ByVal n) Encoder = n Xor (n \ 2) End Function Function Decoder(ByVal n) Dim g : g = 0 Do While n > 0 g = g Xor n n = n \ 2 Loop Decoder = g End Function Function Dec2bin(ByVal n, ByVal length) Dim i, strbin : strbin = "" For i = 1 to 5 strbin = (n Mod 2) & strbin n = n \ 2 Next Dec2Bin = strbin End Function WScript.StdOut.WriteLine("Binary -> Gray Code -> Binary") For i = 0 to 31 encoded = Encoder(i) decoded = Decoder(encoded) WScript.StdOut.WriteLine(Dec2Bin(i, 5) & " -> " & Dec2Bin(encoded, 5) & " -> " & Dec2Bin(decoded, 5)) Next
>>> def int2bin(n): 'From positive integer to list of binary bits, msb at index 0' if n: bits = [] while n: n,remainder = divmod(n, 2) bits.insert(0, remainder) return bits else: return [0] >>> def bin2int(bits): 'From binary bits, msb at index 0 to integer' i = 0 for bit in bits: i = i * 2 + bit return i
Rewrite the snippet below in Python so it works the same as the original VB code.
class playingcard dim suit dim pips end class class carddeck private suitnames private pipnames private cardno private deck(52) private nTop sub class_initialize dim suit dim pips suitnames = split("H,D,C,S",",") pipnames = split("A,2,3,4,5,6,7,8,9,10,J,Q,K",",") cardno = 0 for suit = 1 to 4 for pips = 1 to 13 set deck(cardno) = new playingcard deck(cardno).suit = suitnames(suit-1) deck(cardno).pips = pipnames(pips-1) cardno = cardno + 1 next next nTop = 0 end sub public sub showdeck dim a redim a(51-nTop) for i = nTop to 51 a(i) = deck(i).pips & deck(i).suit next wscript.echo join( a, ", ") end sub public sub shuffle dim r randomize timer for i = nTop to 51 r = int( rnd * ( 52 - nTop ) ) if r <> i then objswap deck(i),deck(r) end if next end sub public function deal() set deal = deck( nTop ) nTop = nTop + 1 end function public property get cardsRemaining cardsRemaining = 52 - nTop end property private sub objswap( a, b ) dim tmp set tmp = a set a = b set b = tmp end sub end class
import random class Card(object): suits = ("Clubs","Hearts","Spades","Diamonds") pips = ("2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace") def __init__(self, pip,suit): self.pip=pip self.suit=suit def __str__(self): return "%s %s"%(self.pip,self.suit) class Deck(object): def __init__(self): self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips] def __str__(self): return "[%s]"%", ".join( (str(card) for card in self.deck)) def shuffle(self): random.shuffle(self.deck) def deal(self): self.shuffle() return self.deck.pop(0)
Generate a Python translation of this VB snippet without changing its computational steps.
Option Base {0|1}
array = [] array.append(1) array.append(3) array[0] = 2 print array[0]
Convert this VB block to Python, preserving its control flow and logic.
Option Base {0|1}
array = [] array.append(1) array.append(3) array[0] = 2 print array[0]
Write the same code in Python as shown below in VB.
Const Order = 4 Function InCarpet(ByVal x As Integer, ByVal y As Integer) Do While x <> 0 And y <> 0 If x Mod 3 = 1 And y Mod 3 = 1 Then InCarpet = " " Exit Function End If x = x \ 3 y = y \ 3 Loop InCarpet = "#" End Function Public Sub sierpinski_carpet() Dim i As Integer, j As Integer For i = 0 To 3 ^ Order - 1 For j = 0 To 3 ^ Order - 1 Debug.Print InCarpet(i, j); Next j Debug.Print Next i End Sub
def setup(): size(729, 729) fill(0) background(255) noStroke() rect(width / 3, height / 3, width / 3, width / 3) rectangles(width / 3, height / 3, width / 3) def rectangles(x, y, s): if s < 1: return xc, yc = x - s, y - s for row in range(3): for col in range(3): if not (row == 1 and col == 1): xx, yy = xc + row * s, yc + col * s delta = s / 3 rect(xx + delta, yy + delta, delta, delta) rectangles(xx + s / 3, yy + s / 3, s / 3)
Can you help me rewrite this code in Python instead of VB, keeping it the same logically?
Private Function Knuth(a As Variant) As Variant Dim t As Variant, i As Integer If Not IsMissing(a) Then For i = UBound(a) To LBound(a) + 1 Step -1 j = Int((UBound(a) - LBound(a) + 1) * Rnd + LBound(a)) t = a(i) a(i) = a(j) a(j) = t Next i End If Knuth = a End Function Private Function inOrder(s As Variant) i = 2 Do While i <= UBound(s) If s(i) < s(i - 1) Then inOrder = False Exit Function End If i = i + 1 Loop inOrder = True End Function Private Function bogosort(ByVal s As Variant) As Variant Do While Not inOrder(s) Debug.Print Join(s, ", ") s = Knuth(s) Loop bogosort = s End Function Public Sub main() Debug.Print Join(bogosort(Knuth([{1,2,3,4,5,6}])), ", ") End Sub
import random def bogosort(l): while not in_order(l): random.shuffle(l) return l def in_order(l): if not l: return True last = l[0] for x in l[1:]: if x < last: return False last = x return True
Port the following code from VB to Python with equivalent syntax and logic.
Private Sub ivp_euler(f As String, y As Double, step As Integer, end_t As Integer) Dim t As Integer Debug.Print " Step "; step; ": ", Do While t <= end_t If t Mod 10 = 0 Then Debug.Print Format(y, "0.000"), y = y + step * Application.Run(f, y) t = t + step Loop Debug.Print End Sub Sub analytic() Debug.Print " Time: ", For t = 0 To 100 Step 10 Debug.Print " "; t, Next t Debug.Print Debug.Print "Analytic: ", For t = 0 To 100 Step 10 Debug.Print Format(20 + 80 * Exp(-0.07 * t), "0.000"), Next t Debug.Print End Sub Private Function cooling(temp As Double) As Double cooling = -0.07 * (temp - 20) End Function Public Sub euler_method() Dim r_cooling As String r_cooling = "cooling" analytic ivp_euler r_cooling, 100, 2, 100 ivp_euler r_cooling, 100, 5, 100 ivp_euler r_cooling, 100, 10, 100 End Sub
def euler(f,y0,a,b,h): t,y = a,y0 while t <= b: print "%6.3f %6.3f" % (t,y) t += h y += h * f(t,y) def newtoncooling(time, temp): return -0.07 * (temp - 20) euler(newtoncooling,100,0,100,10)
Produce a language-to-language conversion: from VB to Python, same semantics.
Sub Main() Dim i&, c&, j#, s$ Const N& = 1000000 s = "values for n in the range 1 to 22 : " For i = 1 To 22 s = s & ns(i) & ", " Next For i = 1 To N j = Sqr(ns(i)) If j = CInt(j) Then c = c + 1 Next Debug.Print s Debug.Print c & " squares less than " & N End Sub Private Function ns(l As Long) As Long ns = l + Int(1 / 2 + Sqr(l)) End Function
>>> from math import floor, sqrt >>> def non_square(n): return n + floor(1/2 + sqrt(n)) >>> >>> print(*map(non_square, range(1, 23))) 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27 >>> >>> def is_square(n): return sqrt(n).is_integer() >>> non_squares = map(non_square, range(1, 10 ** 6)) >>> next(filter(is_square, non_squares)) StopIteration Traceback (most recent call last) <ipython-input-45-f32645fc1c0a> in <module>() 1 non_squares = map(non_square, range(1, 10 ** 6)) ----> 2 next(filter(is_square, non_squares)) StopIteration:
Write a version of this VB function in Python with identical behavior.
Sub Main() Dim i&, c&, j#, s$ Const N& = 1000000 s = "values for n in the range 1 to 22 : " For i = 1 To 22 s = s & ns(i) & ", " Next For i = 1 To N j = Sqr(ns(i)) If j = CInt(j) Then c = c + 1 Next Debug.Print s Debug.Print c & " squares less than " & N End Sub Private Function ns(l As Long) As Long ns = l + Int(1 / 2 + Sqr(l)) End Function
>>> from math import floor, sqrt >>> def non_square(n): return n + floor(1/2 + sqrt(n)) >>> >>> print(*map(non_square, range(1, 23))) 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27 >>> >>> def is_square(n): return sqrt(n).is_integer() >>> non_squares = map(non_square, range(1, 10 ** 6)) >>> next(filter(is_square, non_squares)) StopIteration Traceback (most recent call last) <ipython-input-45-f32645fc1c0a> in <module>() 1 non_squares = map(non_square, range(1, 10 ** 6)) ----> 2 next(filter(is_square, non_squares)) StopIteration:
Write a version of this VB function in Python with identical behavior.
Public Sub substring() sentence = "the last thing the man said was the" n = 10: m = 5 Debug.Print Mid(sentence, n, 5) Debug.Print Right(sentence, Len(sentence) - n + 1) Debug.Print Left(sentence, Len(sentence) - 1) k = InStr(1, sentence, "m") Debug.Print Mid(sentence, k, 5) k = InStr(1, sentence, "aid") Debug.Print Mid(sentence, k, 5) End Sub
>>> s = 'abcdefgh' >>> n, m, char, chars = 2, 3, 'd', 'cd' >>> >>> s[n-1:n+m-1] 'bcd' >>> >>> s[n-1:] 'bcdefgh' >>> >>> s[:-1] 'abcdefg' >>> >>> indx = s.index(char) >>> s[indx:indx+m] 'def' >>> >>> indx = s.index(chars) >>> s[indx:indx+m] 'cde' >>>
Transform the following VB implementation into Python, maintaining the same output and logic.
Function JortSort(s) JortSort = True arrPreSort = Split(s,",") Set arrSorted = CreateObject("System.Collections.ArrayList") For i = 0 To UBound(arrPreSort) arrSorted.Add(arrPreSort(i)) Next arrSorted.Sort() For j = 0 To UBound(arrPreSort) If arrPreSort(j) <> arrSorted(j) Then JortSort = False Exit For End If Next End Function WScript.StdOut.Write JortSort("1,2,3,4,5") WScript.StdOut.WriteLine WScript.StdOut.Write JortSort("1,2,3,5,4") WScript.StdOut.WriteLine WScript.StdOut.Write JortSort("a,b,c") WScript.StdOut.WriteLine WScript.StdOut.Write JortSort("a,c,b")
>>> def jortsort(sequence): return list(sequence) == sorted(sequence) >>> for data in [(1,2,4,3), (14,6,8), ['a', 'c'], ['s', 'u', 'x'], 'CVGH', 'PQRST']: print(f'jortsort({repr(data)}) is {jortsort(data)}') jortsort((1, 2, 4, 3)) is False jortsort((14, 6, 8)) is False jortsort(['a', 'c']) is True jortsort(['s', 'u', 'x']) is True jortsort('CVGH') is False jortsort('PQRST') is True >>>
Generate an equivalent Python version of this VB code.
Public Function Leap_year(year As Integer) As Boolean Leap_year = (Month(DateSerial(year, 2, 29)) = 2) End Function
import calendar calendar.isleap(year)
Preserve the algorithm and functionality while converting the code from VB to Python.
dim i,j Wscript.StdOut.WriteLine "-- Long Integer - Permutations - from 1 to 12" for i=1 to 12 for j=1 to i Wscript.StdOut.Write "P(" & i & "," & j & ")=" & perm(i,j) & " " next Wscript.StdOut.WriteLine "" next Wscript.StdOut.WriteLine "-- Float integer - Combinations from 10 to 60" for i=10 to 60 step 10 for j=1 to i step i\5 Wscript.StdOut.Write "C(" & i & "," & j & ")=" & comb(i,j) & " " next Wscript.StdOut.WriteLine "" next Wscript.StdOut.WriteLine "-- Float integer - Permutations from 5000 to 15000" for i=5000 to 15000 step 5000 for j=10 to 70 step 20 Wscript.StdOut.Write "C(" & i & "," & j & ")=" & perm(i,j) & " " next Wscript.StdOut.WriteLine "" next Wscript.StdOut.WriteLine "-- Float integer - Combinations from 200 to 1000" for i=200 to 1000 step 200 for j=20 to 100 step 20 Wscript.StdOut.Write "P(" & i & "," & j & ")=" & comb(i,j) & " " next Wscript.StdOut.WriteLine "" next function perm(x,y) dim i,z z=1 for i=x-y+1 to x z=z*i next perm=z end function function fact(x) dim i,z z=1 for i=2 to x z=z*i next fact=z end function function comb(byval x,byval y) if y>x then comb=0 elseif x=y then comb=1 else if x-y<y then y=x-y comb=perm(x,y)/fact(y) end if end function
from __future__ import print_function from scipy.misc import factorial as fact from scipy.misc import comb def perm(N, k, exact=0): return comb(N, k, exact) * fact(k, exact) exact=True print('Sample Perms 1..12') for N in range(1, 13): k = max(N-2, 1) print('%iP%i =' % (N, k), perm(N, k, exact), end=', ' if N % 5 else '\n') print('\n\nSample Combs 10..60') for N in range(10, 61, 10): k = N-2 print('%iC%i =' % (N, k), comb(N, k, exact), end=', ' if N % 50 else '\n') exact=False print('\n\nSample Perms 5..1500 Using FP approximations') for N in [5, 15, 150, 1500, 15000]: k = N-2 print('%iP%i =' % (N, k), perm(N, k, exact)) print('\nSample Combs 100..1000 Using FP approximations') for N in range(100, 1001, 100): k = N-2 print('%iC%i =' % (N, k), comb(N, k, exact))
Translate this program into Python but keep the logic exactly as in VB.
Public Function sortlexicographically(N As Integer) Dim arrList As Object Set arrList = CreateObject("System.Collections.ArrayList") For i = 1 To N arrList.Add CStr(i) Next i arrList.Sort Dim item As Variant For Each item In arrList Debug.Print item & ", "; Next End Function Public Sub main() Call sortlexicographically(13) End Sub
n=13 print(sorted(range(1,n+1), key=str))
Translate the given VB code snippet into Python without altering its behavior.
Public twenties As Variant Public decades As Variant Public orders As Variant Private Sub init() twenties = [{"zero","one","two","three","four","five","six","seven","eight","nine","ten", "eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"}] decades = [{"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"}] orders = [{1E15,"quadrillion"; 1E12,"trillion"; 1E9,"billion"; 1E6,"million"; 1E3,"thousand"}] End Sub Private Function Twenty(N As Variant) Twenty = twenties(N Mod 20 + 1) End Function Private Function Decade(N As Variant) Decade = decades(N Mod 10 - 1) End Function Private Function Hundred(N As Variant) If N < 20 Then Hundred = Twenty(N) Exit Function Else If N Mod 10 = 0 Then Hundred = Decade((N \ 10) Mod 10) Exit Function End If End If Hundred = Decade(N \ 10) & "-" & Twenty(N Mod 10) End Function Private Function Thousand(N As Variant, withand As String) If N < 100 Then Thousand = withand & Hundred(N) Exit Function Else If N Mod 100 = 0 Then Thousand = withand & Twenty(WorksheetFunction.Floor_Precise(N / 100)) & " hundred" Exit Function End If End If Thousand = Twenty(N \ 100) & " hundred and " & Hundred(N Mod 100) End Function Private Function Triplet(N As Variant) Dim Order, High As Variant, Low As Variant Dim Name As String, res As String For i = 1 To UBound(orders) Order = orders(i, 1) Name = orders(i, 2) High = WorksheetFunction.Floor_Precise(N / Order) Low = N - High * Order If High <> 0 Then res = res & Thousand(High, "") & " " & Name End If N = Low If Low = 0 Then Exit For If Len(res) And High <> 0 Then res = res & ", " End If Next i If N <> 0 Or res = "" Then res = res & Thousand(WorksheetFunction.Floor_Precise(N), IIf(res = "", "", "and ")) N = N - Int(N) If N > 0.000001 Then res = res & " point" For i = 1 To 10 n_ = WorksheetFunction.Floor_Precise(N * 10.0000001) res = res & " " & twenties(n_ + 1) N = N * 10 - n_ If Abs(N) < 0.000001 Then Exit For Next i End If End If Triplet = res End Function Private Function spell(N As Variant) Dim res As String If N < 0 Then res = "minus " N = -N End If res = res & Triplet(N) spell = res End Function Private Function smartp(N As Variant) Dim res As String If N = WorksheetFunction.Floor_Precise(N) Then smartp = CStr(N) Exit Function End If res = CStr(N) If InStr(1, res, ".") Then res = Left(res, InStr(1, res, ".")) End If smartp = res End Function Sub Main() Dim si As Variant init Samples1 = [{99, 300, 310, 417, 1501, 12609, 200000000000100, 999999999999999, -123456787654321,102003000400005,1020030004,102003,102,1,0,-1,-99, -1501,1234,12.34}] Samples2 = [{10000001.2,1E-3,-2.7182818, 201021002001,-20102100200,2010210020,-201021002,20102100,-2010210, 201021,-20102,2010,-201,20,-2}] For i = 1 To UBound(Samples1) si = Samples1(i) Debug.Print Format(smartp(si), "@@@@@@@@@@@@@@@@"); " "; spell(si) Next i For i = 1 To UBound(Samples2) si = Samples2(i) Debug.Print Format(smartp(si), "@@@@@@@@@@@@@@@@"); " "; spell(si) Next i End Sub
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) if __name__ == '__main__': for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29): print('%+4i -> %s' % (n, spell_integer(n))) print('') n = 201021002001 while n: print('%-12i -> %s' % (n, spell_integer(n))) n //= -10 print('%-12i -> %s' % (n, spell_integer(n))) print('')
Produce a language-to-language conversion: from VB to Python, same semantics.
Sub arrShellSort(ByVal arrData As Variant) Dim lngHold, lngGap As Long Dim lngCount, lngMin, lngMax As Long Dim varItem As Variant lngMin = LBound(arrData) lngMax = UBound(arrData) lngGap = lngMin Do While (lngGap < lngMax) lngGap = 3 * lngGap + 1 Loop Do While (lngGap > 1) lngGap = lngGap \ 3 For lngCount = lngGap + lngMin To lngMax varItem = arrData(lngCount) lngHold = lngCount Do While ((arrData(lngHold - lngGap) > varItem)) arrData(lngHold) = arrData(lngHold - lngGap) lngHold = lngHold - lngGap If (lngHold < lngMin + lngGap) Then Exit Do Loop arrData(lngHold) = varItem Next Loop arrShellSort = arrData End Sub
def shell(seq): inc = len(seq) // 2 while inc: for i, el in enumerate(seq[inc:], inc): while i >= inc and seq[i - inc] > el: seq[i] = seq[i - inc] i -= inc seq[i] = el inc = 1 if inc == 2 else inc * 5 // 11
Write a version of this VB function in Python with identical behavior.
Public Class DoubleLinkList(Of T) Private m_Head As Node(Of T) Private m_Tail As Node(Of T) Public Sub AddHead(ByVal value As T) Dim node As New Node(Of T)(Me, value) If m_Head Is Nothing Then m_Head = Node m_Tail = m_Head Else node.Next = m_Head m_Head = node End If End Sub Public Sub AddTail(ByVal value As T) Dim node As New Node(Of T)(Me, value) If m_Tail Is Nothing Then m_Head = node m_Tail = m_Head Else node.Previous = m_Tail m_Tail = node End If End Sub Public ReadOnly Property Head() As Node(Of T) Get Return m_Head End Get End Property Public ReadOnly Property Tail() As Node(Of T) Get Return m_Tail End Get End Property Public Sub RemoveTail() If m_Tail Is Nothing Then Return If m_Tail.Previous Is Nothing Then m_Head = Nothing m_Tail = Nothing Else m_Tail = m_Tail.Previous m_Tail.Next = Nothing End If End Sub Public Sub RemoveHead() If m_Head Is Nothing Then Return If m_Head.Next Is Nothing Then m_Head = Nothing m_Tail = Nothing Else m_Head = m_Head.Next m_Head.Previous = Nothing End If End Sub End Class Public Class Node(Of T) Private ReadOnly m_Value As T Private m_Next As Node(Of T) Private m_Previous As Node(Of T) Private ReadOnly m_Parent As DoubleLinkList(Of T) Public Sub New(ByVal parent As DoubleLinkList(Of T), ByVal value As T) m_Parent = parent m_Value = value End Sub Public Property [Next]() As Node(Of T) Get Return m_Next End Get Friend Set(ByVal value As Node(Of T)) m_Next = value End Set End Property Public Property Previous() As Node(Of T) Get Return m_Previous End Get Friend Set(ByVal value As Node(Of T)) m_Previous = value End Set End Property Public ReadOnly Property Value() As T Get Return m_Value End Get End Property Public Sub InsertAfter(ByVal value As T) If m_Next Is Nothing Then m_Parent.AddTail(value) ElseIf m_Previous Is Nothing Then m_Parent.AddHead(value) Else Dim node As New Node(Of T)(m_Parent, value) node.Previous = Me node.Next = Me.Next Me.Next.Previous = node Me.Next = node End If End Sub Public Sub Remove() If m_Next Is Nothing Then m_Parent.RemoveTail() ElseIf m_Previous Is Nothing Then m_Parent.RemoveHead() Else m_Previous.Next = Me.Next m_Next.Previous = Me.Previous End If End Sub End Class
from collections import deque some_list = deque(["a", "b", "c"]) print(some_list) some_list.appendleft("Z") print(some_list) for value in reversed(some_list): print(value)
Produce a functionally identical Python code for the snippet given in VB.
TYPE regChar Character AS STRING * 3 Count AS LONG END TYPE DIM iChar AS INTEGER DIM iCL AS INTEGER DIM iCountChars AS INTEGER DIM iFile AS INTEGER DIM i AS INTEGER DIM lMUC AS LONG DIM iMUI AS INTEGER DIM lLUC AS LONG DIM iLUI AS INTEGER DIM iMaxIdx AS INTEGER DIM iP AS INTEGER DIM iPause AS INTEGER DIM iPMI AS INTEGER DIM iPrint AS INTEGER DIM lHowMany AS LONG DIM lTotChars AS LONG DIM sTime AS SINGLE DIM strFile AS STRING DIM strTxt AS STRING DIM strDate AS STRING DIM strTime AS STRING DIM strKey AS STRING CONST LngReg = 256 CONST Letters = 1 CONST FALSE = 0 CONST TRUE = NOT FALSE strDate = DATE$ strTime = TIME$ iFile = FREEFILE DO CLS PRINT "This program counts letters or characters in a text file." PRINT INPUT "File to open: ", strFile OPEN strFile FOR BINARY AS #iFile IF LOF(iFile) > 0 THEN PRINT "Count: 1) Letters 2) Characters (1 or 2)"; DO strKey = INKEY$ LOOP UNTIL strKey = "1" OR strKey = "2" PRINT ". Option selected: "; strKey iCL = VAL(strKey) sTime = TIMER iP = POS(0) lHowMany = LOF(iFile) strTxt = SPACE$(LngReg) IF iCL = Letters THEN iMaxIdx = 26 ELSE iMaxIdx = 255 END IF IF iMaxIdx <> iPMI THEN iPMI = iMaxIdx REDIM rChar(0 TO iMaxIdx) AS regChar FOR i = 0 TO iMaxIdx IF iCL = Letters THEN strTxt = CHR$(i + 65) IF i = 26 THEN strTxt = CHR$(165) ELSE SELECT CASE i CASE 0: strTxt = "nul" CASE 7: strTxt = "bel" CASE 9: strTxt = "tab" CASE 10: strTxt = "lf" CASE 11: strTxt = "vt" CASE 12: strTxt = "ff" CASE 13: strTxt = "cr" CASE 28: strTxt = "fs" CASE 29: strTxt = "gs" CASE 30: strTxt = "rs" CASE 31: strTxt = "us" CASE 32: strTxt = "sp" CASE ELSE: strTxt = CHR$(i) END SELECT END IF rChar(i).Character = strTxt NEXT i ELSE FOR i = 0 TO iMaxIdx rChar(i).Count = 0 NEXT i END IF PRINT "Looking for "; IF iCL = Letters THEN PRINT "letters."; ELSE PRINT "characters."; PRINT " File is"; STR$(lHowMany); " in size. Working"; : COLOR 23: PRINT "..."; : COLOR (7) DO WHILE LOC(iFile) < LOF(iFile) IF LOC(iFile) + LngReg > LOF(iFile) THEN strTxt = SPACE$(LOF(iFile) - LOC(iFile)) END IF GET #iFile, , strTxt FOR i = 1 TO LEN(strTxt) IF iCL = Letters THEN iChar = ASC(UCASE$(MID$(strTxt, i, 1))) SELECT CASE iChar CASE 164: iChar = 165 CASE 160: iChar = 65 CASE 130, 144: iChar = 69 CASE 161: iChar = 73 CASE 162: iChar = 79 CASE 163, 129: iChar = 85 END SELECT iChar = iChar - 65 IF iChar >= 0 AND iChar <= 25 THEN rChar(iChar).Count = rChar(iChar).Count + 1 ELSEIF iChar = 100 THEN rChar(iMaxIdx).Count = rChar(iMaxIdx).Count + 1 END IF ELSE iChar = ASC(MID$(strTxt, i, 1)) rChar(iChar).Count = rChar(iChar).Count + 1 END IF NEXT i LOOP CLOSE #iFile lMUC = 0 iMUI = 0 lLUC = 2147483647 iLUI = 0 iPrint = FALSE lTotChars = 0 iCountChars = 0 iPause = FALSE CLS IF iCL = Letters THEN PRINT "Letters found: "; ELSE PRINT "Characters found: "; FOR i = 0 TO iMaxIdx IF lMUC < rChar(i).Count THEN lMUC = rChar(i).Count iMUI = i END IF IF rChar(i).Count > 0 THEN strTxt = "" IF iPrint THEN strTxt = ", " ELSE iPrint = TRUE strTxt = strTxt + LTRIM$(RTRIM$(rChar(i).Character)) strTxt = strTxt + "=" + LTRIM$(STR$(rChar(i).Count)) iP = POS(0) IF iP + LEN(strTxt) + 1 >= 80 AND iPrint THEN PRINT "," IF CSRLIN >= 23 AND NOT iPause THEN iPause = TRUE PRINT "Press a key to continue..." DO strKey = INKEY$ LOOP UNTIL strKey <> "" END IF strTxt = MID$(strTxt, 3) END IF PRINT strTxt; lTotChars = lTotChars + rChar(i).Count iCountChars = iCountChars + 1 IF lLUC > rChar(i).Count THEN lLUC = rChar(i).Count iLUI = i END IF END IF NEXT i PRINT "." PRINT PRINT "File analyzed....................: "; strFile PRINT "Looked for.......................: "; : IF iCL = Letters THEN PRINT "Letters" ELSE PRINT "Characters" PRINT "Total characters in file.........:"; lHowMany PRINT "Total characters counted.........:"; lTotChars IF iCL = Letters THEN PRINT "Characters discarded on count....:"; lHowMany - lTotChars PRINT "Distinct characters found in file:"; iCountChars; "of"; iMaxIdx + 1 PRINT "Most used character was..........: "; iPrint = FALSE FOR i = 0 TO iMaxIdx IF rChar(i).Count = lMUC THEN IF iPrint THEN PRINT ", "; ELSE iPrint = TRUE PRINT RTRIM$(LTRIM$(rChar(i).Character)); END IF NEXT i PRINT " ("; LTRIM$(STR$(rChar(iMUI).Count)); " times)" PRINT "Least used character was.........: "; iPrint = FALSE FOR i = 0 TO iMaxIdx IF rChar(i).Count = lLUC THEN IF iPrint THEN PRINT ", "; ELSE iPrint = TRUE PRINT RTRIM$(LTRIM$(rChar(i).Character)); END IF NEXT i PRINT " ("; LTRIM$(STR$(rChar(iLUI).Count)); " times)" PRINT "Time spent in the process........:"; TIMER - sTime; "seconds" ELSE CLOSE #iFile KILL strFile PRINT PRINT "File does not exist." END IF PRINT PRINT "Again? (Y/n)" DO strTxt = UCASE$(INKEY$) LOOP UNTIL strTxt = "N" OR strTxt = "Y" OR strTxt = CHR$(13) OR strTxt = CHR$(27) LOOP UNTIL strTxt = "N" OR strTxt = CHR$(27) CLS PRINT "End of execution." PRINT "Start time: "; strDate; " "; strTime; ", end time: "; DATE$; " "; TIME$; "." END
import collections, sys def filecharcount(openfile): return sorted(collections.Counter(c for l in openfile for c in l).items()) f = open(sys.argv[1]) print(filecharcount(f))
Generate an equivalent Python version of this VB code.
Dim s As String = "123" s = CStr(CInt("123") + 1) s = (CInt("123") + 1).ToString
next = str(int('123') + 1)
Port the provided VB code into Python while preserving the original functionality.
Dim s As String = "123" s = CStr(CInt("123") + 1) s = (CInt("123") + 1).ToString
next = str(int('123') + 1)
Change the following VB code into Python without altering its purpose.
Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean) Dim i As Integer, stReplace As String If bSpace = True Then stReplace = " " Else stReplace = "" End If For i = 1 To Len(stStripChars) stString = Replace(stString, Mid(stStripChars, i, 1), stReplace) Next i StripChars = stString End Function
>>> def stripchars(s, chars): ... return s.translate(None, chars) ... >>> stripchars("She was a soul stripper. She took my heart!", "aei") 'Sh ws soul strppr. Sh took my hrt!'
Change the following VB code into Python without altering its purpose.
Private Function mean(v() As Double, ByVal leng As Integer) As Variant Dim sum As Double, i As Integer sum = 0: i = 0 For i = 0 To leng - 1 sum = sum + vv Next i If leng = 0 Then mean = CVErr(xlErrDiv0) Else mean = sum / leng End If End Function Public Sub main() Dim v(4) As Double Dim i As Integer, leng As Integer v(0) = 1# v(1) = 2# v(2) = 2.178 v(3) = 3# v(4) = 3.142 For leng = 5 To 0 Step -1 Debug.Print "mean["; For i = 0 To leng - 1 Debug.Print IIf(i, "; " & v(i), "" & v(i)); Next i Debug.Print "] = "; mean(v, leng) Next leng End Sub
from math import fsum def average(x): return fsum(x)/float(len(x)) if x else 0 print (average([0,0,3,1,4,1,5,9,0,0])) print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))
Change the programming language of this snippet from VB to Python without modifying what it does.
Private Function ValidateUserWords(userstring As String) As String Dim s As String Dim user_words() As String Dim command_table As Scripting.Dictionary Set command_table = New Scripting.Dictionary Dim abbreviations As Scripting.Dictionary Set abbreviations = New Scripting.Dictionary abbreviations.CompareMode = TextCompare Dim commandtable() As String Dim commands As String s = s & "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " s = s & "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " s = s & "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " s = s & "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " s = s & "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " s = s & "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " s = s & "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " s = s & "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 " commandtable = Split(s, " ") Dim i As Integer, word As Variant, number As Integer For i = LBound(commandtable) To UBound(commandtable) word = commandtable(i) If Len(word) > 0 Then i = i + 1 Do While Len(commandtable(i)) = 0: i = i + 1: Loop number = Val(commandtable(i)) If number > 0 Then command_table.Add Key:=word, Item:=number Else command_table.Add Key:=word, Item:=Len(word) i = i - 1 End If End If Next i For Each word In command_table For i = command_table(word) To Len(word) On Error Resume Next abbreviations.Add Key:=Left(word, i), Item:=UCase(word) Next i Next word user_words() = Split(userstring, " ") For Each word In user_words If Len(word) > 0 Then If abbreviations.exists(word) Then commands = commands & abbreviations(word) & " " Else commands = commands & "*error* " End If End If Next word ValidateUserWords = commands End Function Public Sub program() Dim guserstring As String guserstring = "riG rePEAT copies put mo rest types fup. 6 poweRin" Debug.Print "user words:", guserstring Debug.Print "full words:", ValidateUserWords(guserstring) End Sub
command_table_text = user_words = "riG rePEAT copies put mo rest types fup. 6 poweRin" def find_abbreviations_length(command_table_text): command_table = dict() input_iter = iter(command_table_text.split()) word = None try: while True: if word is None: word = next(input_iter) abbr_len = next(input_iter, len(word)) try: command_table[word] = int(abbr_len) word = None except ValueError: command_table[word] = len(word) word = abbr_len except StopIteration: pass return command_table def find_abbreviations(command_table): abbreviations = dict() for command, min_abbr_len in command_table.items(): for l in range(min_abbr_len, len(command)+1): abbr = command[:l].lower() abbreviations[abbr] = command.upper() return abbreviations def parse_user_string(user_string, abbreviations): user_words = [word.lower() for word in user_string.split()] commands = [abbreviations.get(user_word, "*error*") for user_word in user_words] return " ".join(commands) command_table = find_abbreviations_length(command_table_text) abbreviations_table = find_abbreviations(command_table) full_words = parse_user_string(user_words, abbreviations_table) print("user words:", user_words) print("full words:", full_words)
Translate this program into Python but keep the logic exactly as in VB.
Private Function ValidateUserWords(userstring As String) As String Dim s As String Dim user_words() As String Dim command_table As Scripting.Dictionary Set command_table = New Scripting.Dictionary Dim abbreviations As Scripting.Dictionary Set abbreviations = New Scripting.Dictionary abbreviations.CompareMode = TextCompare Dim commandtable() As String Dim commands As String s = s & "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " s = s & "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " s = s & "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " s = s & "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " s = s & "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " s = s & "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " s = s & "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " s = s & "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 " commandtable = Split(s, " ") Dim i As Integer, word As Variant, number As Integer For i = LBound(commandtable) To UBound(commandtable) word = commandtable(i) If Len(word) > 0 Then i = i + 1 Do While Len(commandtable(i)) = 0: i = i + 1: Loop number = Val(commandtable(i)) If number > 0 Then command_table.Add Key:=word, Item:=number Else command_table.Add Key:=word, Item:=Len(word) i = i - 1 End If End If Next i For Each word In command_table For i = command_table(word) To Len(word) On Error Resume Next abbreviations.Add Key:=Left(word, i), Item:=UCase(word) Next i Next word user_words() = Split(userstring, " ") For Each word In user_words If Len(word) > 0 Then If abbreviations.exists(word) Then commands = commands & abbreviations(word) & " " Else commands = commands & "*error* " End If End If Next word ValidateUserWords = commands End Function Public Sub program() Dim guserstring As String guserstring = "riG rePEAT copies put mo rest types fup. 6 poweRin" Debug.Print "user words:", guserstring Debug.Print "full words:", ValidateUserWords(guserstring) End Sub
command_table_text = user_words = "riG rePEAT copies put mo rest types fup. 6 poweRin" def find_abbreviations_length(command_table_text): command_table = dict() input_iter = iter(command_table_text.split()) word = None try: while True: if word is None: word = next(input_iter) abbr_len = next(input_iter, len(word)) try: command_table[word] = int(abbr_len) word = None except ValueError: command_table[word] = len(word) word = abbr_len except StopIteration: pass return command_table def find_abbreviations(command_table): abbreviations = dict() for command, min_abbr_len in command_table.items(): for l in range(min_abbr_len, len(command)+1): abbr = command[:l].lower() abbreviations[abbr] = command.upper() return abbreviations def parse_user_string(user_string, abbreviations): user_words = [word.lower() for word in user_string.split()] commands = [abbreviations.get(user_word, "*error*") for user_word in user_words] return " ".join(commands) command_table = find_abbreviations_length(command_table_text) abbreviations_table = find_abbreviations(command_table) full_words = parse_user_string(user_words, abbreviations_table) print("user words:", user_words) print("full words:", full_words)
Produce a functionally identical Python code for the snippet given in VB.
Private Function tokenize(s As String, sep As String, esc As String) As Collection Dim ret As New Collection Dim this As String Dim skip As Boolean If Len(s) <> 0 Then For i = 1 To Len(s) si = Mid(s, i, 1) If skip Then this = this & si skip = False Else If si = esc Then skip = True Else If si = sep Then ret.Add this this = "" Else this = this & si End If End If End If Next i ret.Add this End If Set tokenize = ret End Function Public Sub main() Dim out As Collection Set out = tokenize("one^|uno||three^^^^|four^^^|^cuatro|", "|", "^") Dim outstring() As String ReDim outstring(out.Count - 1) For i = 0 To out.Count - 1 outstring(i) = out(i + 1) Next i Debug.Print Join(outstring, ", ") End Sub
def token_with_escape(a, escape = '^', separator = '|'): result = [] token = '' state = 0 for c in a: if state == 0: if c == escape: state = 1 elif c == separator: result.append(token) token = '' else: token += c elif state == 1: token += c state = 0 result.append(token) return result
Port the following code from VB to Python with equivalent syntax and logic.
Module ForwardDifference Sub Main() Dim lNum As New List(Of Integer)(New Integer() {90, 47, 58, 29, 22, 32, 55, 5, 55, 73}) For i As UInteger = 0 To 9 Console.WriteLine(String.Join(" ", (From n In Difference(i, lNum) Select String.Format("{0,5}", n)).ToArray())) Next Console.ReadKey() End Sub Private Function Difference(ByVal Level As UInteger, ByVal Numbers As List(Of Integer)) As List(Of Integer) If Level >= Numbers.Count Then Throw New ArgumentOutOfRangeException("Level", "Level must be less than number of items in Numbers") For i As Integer = 1 To Level Numbers = (From n In Enumerable.Range(0, Numbers.Count - 1) _ Select Numbers(n + 1) - Numbers(n)).ToList() Next Return Numbers End Function End Module
>>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])] >>> >>> difn = lambda s, n: difn(dif(s), n-1) if n else s >>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] >>> difn(s, 0) [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] >>> difn(s, 1) [-43, 11, -29, -7, 10, 23, -50, 50, 18] >>> difn(s, 2) [54, -40, 22, 17, 13, -73, 100, -32] >>> from pprint import pprint >>> pprint( [difn(s, i) for i in xrange(10)] ) [[90, 47, 58, 29, 22, 32, 55, 5, 55, 73], [-43, 11, -29, -7, 10, 23, -50, 50, 18], [54, -40, 22, 17, 13, -73, 100, -32], [-94, 62, -5, -4, -86, 173, -132], [156, -67, 1, -82, 259, -305], [-223, 68, -83, 341, -564], [291, -151, 424, -905], [-442, 575, -1329], [1017, -1904], [-2921]]
Keep all operations the same but rewrite the snippet in Python.
Option Explicit Sub FirstTwentyPrimes() Dim count As Integer, i As Long, t(19) As String Do i = i + 1 If IsPrime(i) Then t(count) = i count = count + 1 End If Loop While count <= UBound(t) Debug.Print Join(t, ", ") End Sub Function IsPrime(Nb As Long) As Boolean If Nb = 2 Then IsPrime = True ElseIf Nb < 2 Or Nb Mod 2 = 0 Then Exit Function Else Dim i As Long For i = 3 To Sqr(Nb) Step 2 If Nb Mod i = 0 Then Exit Function Next IsPrime = True End If End Function
def prime(a): return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))
Please provide an equivalent version of this VB code in Python.
Function binomial(n,k) binomial = factorial(n)/(factorial(n-k)*factorial(k)) End Function Function factorial(n) If n = 0 Then factorial = 1 Else For i = n To 1 Step -1 If i = n Then factorial = n Else factorial = factorial * i End If Next End If End Function WScript.StdOut.Write "the binomial coefficient of 5 and 3 = " & binomial(5,3) WScript.StdOut.WriteLine
def binomialCoeff(n, k): result = 1 for i in range(1, k+1): result = result * (n-i+1) / i return result if __name__ == "__main__": print(binomialCoeff(5, 3))
Please provide an equivalent version of this VB code in Python.
Dim coll As New Collection coll.Add "apple" coll.Add "banana"
collection = [0, '1'] x = collection[0] collection.append(2) collection.insert(0, '-1') y = collection[0] collection.extend([2,'3']) collection += [2,'3'] collection[2:6] len(collection) collection = (0, 1) collection[:] collection[-4:-1] collection[::2] collection="some string" x = collection[::-1] collection[::2] == "some string"[::2] collection.__getitem__(slice(0,len(collection),2)) collection = {0: "zero", 1: "one"} collection['zero'] = 2 collection = set([0, '1'])
Rewrite the snippet below in Python so it works the same as the original VB code.
Dim coll As New Collection coll.Add "apple" coll.Add "banana"
collection = [0, '1'] x = collection[0] collection.append(2) collection.insert(0, '-1') y = collection[0] collection.extend([2,'3']) collection += [2,'3'] collection[2:6] len(collection) collection = (0, 1) collection[:] collection[-4:-1] collection[::2] collection="some string" x = collection[::-1] collection[::2] == "some string"[::2] collection.__getitem__(slice(0,len(collection),2)) collection = {0: "zero", 1: "one"} collection['zero'] = 2 collection = set([0, '1'])
Can you help me rewrite this code in Python instead of VB, keeping it the same logically?
Private Sub Iterate(ByVal list As LinkedList(Of Integer)) Dim node = list.First Do Until node Is Nothing node = node.Next Loop End Sub
for node in lst: print node.value
Translate the given VB code snippet into Python without altering its behavior.
Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String) Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height) Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3) Dim bytes(bufferSize - 1) As Byte Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length) Dim index As Integer = header.Length For y As Integer = 0 To rasterBitmap.Height - 1 For x As Integer = 0 To rasterBitmap.Width - 1 Dim color As Rgb = rasterBitmap.GetPixel(x, y) bytes(index) = color.R bytes(index + 1) = color.G bytes(index + 2) = color.B index += 3 Next Next My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False) End Sub
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
Convert this VB block to Python, preserving its control flow and logic.
Option Explicit Sub DeleteFileOrDirectory() Dim myPath As String myPath = "C:\Users\surname.name\Desktop\Docs" Kill myPath & "\input.txt" RmDir myPath End Sub
import os os.remove("output.txt") os.rmdir("docs") os.remove("/output.txt") os.rmdir("/docs")
Rewrite the snippet below in Python so it works the same as the original VB code.
Const MAX = 20 Const ITER = 1000000 Function expected(n As Long) As Double Dim sum As Double For i = 1 To n sum = sum + WorksheetFunction.Fact(n) / n ^ i / WorksheetFunction.Fact(n - i) Next i expected = sum End Function Function test(n As Long) As Double Dim count As Long Dim x As Long, bits As Long For i = 1 To ITER x = 1 bits = 0 Do While Not bits And x count = count + 1 bits = bits Or x x = 2 ^ (Int(n * Rnd())) Loop Next i test = count / ITER End Function Public Sub main() Dim n As Long Debug.Print " n avg. exp. (error%)" Debug.Print "== ====== ====== ========" For n = 1 To MAX av = test(n) ex = expected(n) Debug.Print Format(n, "@@"); " "; Format(av, "0.0000"); " "; Debug.Print Format(ex, "0.0000"); " ("; Format(Abs(1 - av / ex), "0.000%"); ")" Next n End Sub
from __future__ import division from math import factorial from random import randrange MAX_N = 20 TIMES = 1000000 def analytical(n): return sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1)) def test(n, times): count = 0 for i in range(times): x, bits = 1, 0 while not (bits & x): count += 1 bits |= x x = 1 << randrange(n) return count / times if __name__ == '__main__': print(" n\tavg\texp.\tdiff\n-------------------------------") for n in range(1, MAX_N+1): avg = test(n, TIMES) theory = analytical(n) diff = (avg / theory - 1) * 100 print("%2d %8.4f %8.4f %6.3f%%" % (n, avg, theory, diff))
Write the same code in Python as shown below in VB.
Const MAX = 20 Const ITER = 1000000 Function expected(n As Long) As Double Dim sum As Double For i = 1 To n sum = sum + WorksheetFunction.Fact(n) / n ^ i / WorksheetFunction.Fact(n - i) Next i expected = sum End Function Function test(n As Long) As Double Dim count As Long Dim x As Long, bits As Long For i = 1 To ITER x = 1 bits = 0 Do While Not bits And x count = count + 1 bits = bits Or x x = 2 ^ (Int(n * Rnd())) Loop Next i test = count / ITER End Function Public Sub main() Dim n As Long Debug.Print " n avg. exp. (error%)" Debug.Print "== ====== ====== ========" For n = 1 To MAX av = test(n) ex = expected(n) Debug.Print Format(n, "@@"); " "; Format(av, "0.0000"); " "; Debug.Print Format(ex, "0.0000"); " ("; Format(Abs(1 - av / ex), "0.000%"); ")" Next n End Sub
from __future__ import division from math import factorial from random import randrange MAX_N = 20 TIMES = 1000000 def analytical(n): return sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1)) def test(n, times): count = 0 for i in range(times): x, bits = 1, 0 while not (bits & x): count += 1 bits |= x x = 1 << randrange(n) return count / times if __name__ == '__main__': print(" n\tavg\texp.\tdiff\n-------------------------------") for n in range(1, MAX_N+1): avg = test(n, TIMES) theory = analytical(n) diff = (avg / theory - 1) * 100 print("%2d %8.4f %8.4f %6.3f%%" % (n, avg, theory, diff))
Port the provided VB code into Python while preserving the original functionality.
Dim name as String = "J. Doe" Dim balance as Double = 123.45 Dim prompt as String = String.Format("Hello {0}, your balance is {1}.", name, balance) Console.WriteLine(prompt)
>>> original = 'Mary had a %s lamb.' >>> extra = 'little' >>> original % extra 'Mary had a little lamb.'
Rewrite the snippet below in Python so it works the same as the original VB code.
Module Module1 Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,) Dim length = a.GetLength(0) - 1 Dim result(length - 1, length - 1) As Double For i = 1 To length For j = 1 To length If i < x AndAlso j < y Then result(i - 1, j - 1) = a(i - 1, j - 1) ElseIf i >= x AndAlso j < y Then result(i - 1, j - 1) = a(i, j - 1) ElseIf i < x AndAlso j >= y Then result(i - 1, j - 1) = a(i - 1, j) Else result(i - 1, j - 1) = a(i, j) End If Next Next Return result End Function Function Det(a As Double(,)) As Double If a.GetLength(0) = 1 Then Return a(0, 0) Else Dim sign = 1 Dim sum = 0.0 For i = 1 To a.GetLength(0) sum += sign * a(0, i - 1) * Det(Minor(a, 0, i)) sign *= -1 Next Return sum End If End Function Function Perm(a As Double(,)) As Double If a.GetLength(0) = 1 Then Return a(0, 0) Else Dim sum = 0.0 For i = 1 To a.GetLength(0) sum += a(0, i - 1) * Perm(Minor(a, 0, i)) Next Return sum End If End Function Sub WriteLine(a As Double(,)) For i = 1 To a.GetLength(0) Console.Write("[") For j = 1 To a.GetLength(1) If j > 1 Then Console.Write(", ") End If Console.Write(a(i - 1, j - 1)) Next Console.WriteLine("]") Next End Sub Sub Test(a As Double(,)) If a.GetLength(0) <> a.GetLength(1) Then Throw New ArgumentException("The dimensions must be equal") End If WriteLine(a) Console.WriteLine("Permanant  : {0}", Perm(a)) Console.WriteLine("Determinant: {0}", Det(a)) Console.WriteLine() End Sub Sub Main() Test({{1, 2}, {3, 4}}) Test({{1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13}}) Test({{0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24}}) End Sub End Module
from itertools import permutations from operator import mul from math import fsum from spermutations import spermutations def prod(lst): return reduce(mul, lst, 1) def perm(a): n = len(a) r = range(n) s = permutations(r) return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s) def det(a): n = len(a) r = range(n) s = spermutations(n) return fsum(sign * prod(a[i][sigma[i]] for i in r) for sigma, sign in s) if __name__ == '__main__': from pprint import pprint as pp for a in ( [ [1, 2], [3, 4]], [ [1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10], [10, 11, 12, 13]], [ [ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]], ): print('') pp(a) print('Perm: %s Det: %s' % (perm(a), det(a)))
Translate the given VB code snippet into Python without altering its behavior.
Module Module1 Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,) Dim length = a.GetLength(0) - 1 Dim result(length - 1, length - 1) As Double For i = 1 To length For j = 1 To length If i < x AndAlso j < y Then result(i - 1, j - 1) = a(i - 1, j - 1) ElseIf i >= x AndAlso j < y Then result(i - 1, j - 1) = a(i, j - 1) ElseIf i < x AndAlso j >= y Then result(i - 1, j - 1) = a(i - 1, j) Else result(i - 1, j - 1) = a(i, j) End If Next Next Return result End Function Function Det(a As Double(,)) As Double If a.GetLength(0) = 1 Then Return a(0, 0) Else Dim sign = 1 Dim sum = 0.0 For i = 1 To a.GetLength(0) sum += sign * a(0, i - 1) * Det(Minor(a, 0, i)) sign *= -1 Next Return sum End If End Function Function Perm(a As Double(,)) As Double If a.GetLength(0) = 1 Then Return a(0, 0) Else Dim sum = 0.0 For i = 1 To a.GetLength(0) sum += a(0, i - 1) * Perm(Minor(a, 0, i)) Next Return sum End If End Function Sub WriteLine(a As Double(,)) For i = 1 To a.GetLength(0) Console.Write("[") For j = 1 To a.GetLength(1) If j > 1 Then Console.Write(", ") End If Console.Write(a(i - 1, j - 1)) Next Console.WriteLine("]") Next End Sub Sub Test(a As Double(,)) If a.GetLength(0) <> a.GetLength(1) Then Throw New ArgumentException("The dimensions must be equal") End If WriteLine(a) Console.WriteLine("Permanant  : {0}", Perm(a)) Console.WriteLine("Determinant: {0}", Det(a)) Console.WriteLine() End Sub Sub Main() Test({{1, 2}, {3, 4}}) Test({{1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13}}) Test({{0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24}}) End Sub End Module
from itertools import permutations from operator import mul from math import fsum from spermutations import spermutations def prod(lst): return reduce(mul, lst, 1) def perm(a): n = len(a) r = range(n) s = permutations(r) return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s) def det(a): n = len(a) r = range(n) s = spermutations(n) return fsum(sign * prod(a[i][sigma[i]] for i in r) for sigma, sign in s) if __name__ == '__main__': from pprint import pprint as pp for a in ( [ [1, 2], [3, 4]], [ [1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10], [10, 11, 12, 13]], [ [ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]], ): print('') pp(a) print('Perm: %s Det: %s' % (perm(a), det(a)))
Rewrite this program in Python while keeping its functionality equivalent to the VB version.
Imports System.Math Module RayCasting Private square As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}} Private squareHole As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}, New Integer() {5, 5}, New Integer() {15, 5}, New Integer() {15, 15}, New Integer() {5, 15}} Private strange As Integer()() = {New Integer() {0, 0}, New Integer() {5, 5}, New Integer() {0, 20}, New Integer() {5, 15}, New Integer() {15, 15}, New Integer() {20, 20}, New Integer() {20, 0}} Private hexagon As Integer()() = {New Integer() {6, 0}, New Integer() {14, 0}, New Integer() {20, 10}, New Integer() {14, 20}, New Integer() {6, 20}, New Integer() {0, 10}} Private shapes As Integer()()() = {square, squareHole, strange, hexagon} Public Sub Main() Dim testPoints As Double()() = {New Double() {10, 10}, New Double() {10, 16}, New Double() {-20, 10}, New Double() {0, 10}, New Double() {20, 10}, New Double() {16, 10}, New Double() {20, 20}} For Each shape As Integer()() In shapes For Each point As Double() In testPoints Console.Write(String.Format("{0} ", Contains(shape, point).ToString.PadLeft(7))) Next Console.WriteLine() Next End Sub Private Function Contains(shape As Integer()(), point As Double()) As Boolean Dim inside As Boolean = False Dim length As Integer = shape.Length For i As Integer = 0 To length - 1 If Intersects(shape(i), shape((i + 1) Mod length), point) Then inside = Not inside End If Next Return inside End Function Private Function Intersects(a As Integer(), b As Integer(), p As Double()) As Boolean If a(1) > b(1) Then Return Intersects(b, a, p) If p(1) = a(1) Or p(1) = b(1) Then p(1) += 0.0001 If p(1) > b(1) Or p(1) < a(1) Or p(0) >= Max(a(0), b(0)) Then Return False If p(0) < Min(a(0), b(0)) Then Return True Dim red As Double = (p(1) - a(1)) / (p(0) - a(0)) Dim blue As Double = (b(1) - a(1)) / (b(0) - a(0)) Return red >= blue End Function End Module
from collections import namedtuple from pprint import pprint as pp import sys Pt = namedtuple('Pt', 'x, y') Edge = namedtuple('Edge', 'a, b') Poly = namedtuple('Poly', 'name, edges') _eps = 0.00001 _huge = sys.float_info.max _tiny = sys.float_info.min def rayintersectseg(p, edge): a,b = edge if a.y > b.y: a,b = b,a if p.y == a.y or p.y == b.y: p = Pt(p.x, p.y + _eps) intersect = False if (p.y > b.y or p.y < a.y) or ( p.x > max(a.x, b.x)): return False if p.x < min(a.x, b.x): intersect = True else: if abs(a.x - b.x) > _tiny: m_red = (b.y - a.y) / float(b.x - a.x) else: m_red = _huge if abs(a.x - p.x) > _tiny: m_blue = (p.y - a.y) / float(p.x - a.x) else: m_blue = _huge intersect = m_blue >= m_red return intersect def _odd(x): return x%2 == 1 def ispointinside(p, poly): ln = len(poly) return _odd(sum(rayintersectseg(p, edge) for edge in poly.edges )) def polypp(poly): print ("\n Polygon(name='%s', edges=(" % poly.name) print (' ', ',\n '.join(str(e) for e in poly.edges) + '\n ))') if __name__ == '__main__': polys = [ Poly(name='square', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)) )), Poly(name='square_hole', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)), Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)), Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)), Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)), Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5)) )), Poly(name='strange', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)), Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)), Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)), Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5)) )), Poly(name='exagon', edges=( Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)), Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)), Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)), Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)), Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)), Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0)) )), ] testpoints = (Pt(x=5, y=5), Pt(x=5, y=8), Pt(x=-10, y=5), Pt(x=0, y=5), Pt(x=10, y=5), Pt(x=8, y=5), Pt(x=10, y=10)) print ("\n TESTING WHETHER POINTS ARE WITHIN POLYGONS") for poly in polys: polypp(poly) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[:3])) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[3:6])) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[6:]))
Convert the following code from VB to Python, ensuring the logic remains intact.
Function CountSubstring(str,substr) CountSubstring = 0 For i = 1 To Len(str) If Len(str) >= Len(substr) Then If InStr(i,str,substr) Then CountSubstring = CountSubstring + 1 i = InStr(i,str,substr) + Len(substr) - 1 End If Else Exit For End If Next End Function WScript.StdOut.Write CountSubstring("the three truths","th") & vbCrLf WScript.StdOut.Write CountSubstring("ababababab","abab") & vbCrLf
>>> "the three truths".count("th") 3 >>> "ababababab".count("abab") 2
Write a version of this VB function in Python with identical behavior.
Imports System Imports System.Console Imports LI = System.Collections.Generic.SortedSet(Of Integer) Module Module1 Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI If lft = 0 Then res.Add(vlu) ElseIf lft > 0 Then For Each itm As Integer In lst res = unl(res, lst, lft - itm, mul * 10, vlu + itm * mul) Next End If Return res End Function Sub Main(ByVal args As String()) WriteLine(string.Join(" ", unl(new LI From {}, new LI From { 2, 3, 5, 7 }, 13))) End Sub End Module
from collections import deque def prime_digits_sum(r): q = deque([(r, 0)]) while q: r, n = q.popleft() for d in 2, 3, 5, 7: if d >= r: if d == r: yield n + d break q.append((r - d, (n + d) * 10)) print(*prime_digits_sum(13))
Translate the given VB code snippet into Python without altering its behavior.
Imports System Imports System.Console Imports LI = System.Collections.Generic.SortedSet(Of Integer) Module Module1 Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI If lft = 0 Then res.Add(vlu) ElseIf lft > 0 Then For Each itm As Integer In lst res = unl(res, lst, lft - itm, mul * 10, vlu + itm * mul) Next End If Return res End Function Sub Main(ByVal args As String()) WriteLine(string.Join(" ", unl(new LI From {}, new LI From { 2, 3, 5, 7 }, 13))) End Sub End Module
from collections import deque def prime_digits_sum(r): q = deque([(r, 0)]) while q: r, n = q.popleft() for d in 2, 3, 5, 7: if d >= r: if d == r: yield n + d break q.append((r - d, (n + d) * 10)) print(*prime_digits_sum(13))
Change the programming language of this snippet from VB to Python without modifying what it does.
Imports System Imports System.Console Imports LI = System.Collections.Generic.SortedSet(Of Integer) Module Module1 Function unl(ByVal res As LI, ByVal lst As LI, ByVal lft As Integer, ByVal Optional mul As Integer = 1, ByVal Optional vlu As Integer = 0) As LI If lft = 0 Then res.Add(vlu) ElseIf lft > 0 Then For Each itm As Integer In lst res = unl(res, lst, lft - itm, mul * 10, vlu + itm * mul) Next End If Return res End Function Sub Main(ByVal args As String()) WriteLine(string.Join(" ", unl(new LI From {}, new LI From { 2, 3, 5, 7 }, 13))) End Sub End Module
from collections import deque def prime_digits_sum(r): q = deque([(r, 0)]) while q: r, n = q.popleft() for d in 2, 3, 5, 7: if d >= r: if d == r: yield n + d break q.append((r - d, (n + d) * 10)) print(*prime_digits_sum(13))
Convert this VB block to Python, preserving its control flow and logic.
Imports System.IO Module Notes Function Main(ByVal cmdArgs() As String) As Integer Try If cmdArgs.Length = 0 Then Using sr As New StreamReader("NOTES.TXT") Console.WriteLine(sr.ReadToEnd) End Using Else Using sw As New StreamWriter("NOTES.TXT", True) sw.WriteLine(Date.Now.ToString()) sw.WriteLine("{0}{1}", ControlChars.Tab, String.Join(" ", cmdArgs)) End Using End If Catch End Try End Function End Module
import sys, datetime, shutil if len(sys.argv) == 1: try: with open('notes.txt', 'r') as f: shutil.copyfileobj(f, sys.stdout) except IOError: pass else: with open('notes.txt', 'a') as f: f.write(datetime.datetime.now().isoformat() + '\n') f.write("\t%s\n" % ' '.join(sys.argv[1:]))
Port the following code from VB to Python with equivalent syntax and logic.
Public Function CommonDirectoryPath(ParamArray Paths()) As String Dim v As Variant Dim Path() As String, s As String Dim i As Long, j As Long, k As Long Const PATH_SEPARATOR As String = "/" For Each v In Paths ReDim Preserve Path(0 To i) Path(i) = v i = i + 1 Next v k = 1 Do For i = 0 To UBound(Path) If i Then If InStr(k, Path(i), PATH_SEPARATOR) <> j Then Exit Do ElseIf Left$(Path(i), j) <> Left$(Path(0), j) Then Exit Do End If Else j = InStr(k, Path(i), PATH_SEPARATOR) If j = 0 Then Exit Do End If End If Next i s = Left$(Path(0), j + CLng(k <> 1)) k = j + 1 Loop CommonDirectoryPath = s End Function Sub Main() Debug.Assert CommonDirectoryPath( _ "/home/user1/tmp/coverage/test", _ "/home/user1/tmp/covert/operator", _ "/home/user1/tmp/coven/members") = _ "/home/user1/tmp" Debug.Assert CommonDirectoryPath( _ "/home/user1/tmp/coverage/test", _ "/home/user1/tmp/covert/operator", _ "/home/user1/tmp/coven/members", _ "/home/user1/abc/coven/members") = _ "/home/user1" Debug.Assert CommonDirectoryPath( _ "/home/user1/tmp/coverage/test", _ "/hope/user1/tmp/covert/operator", _ "/home/user1/tmp/coven/members") = _ "/" End Sub
>>> import os >>> os.path.commonpath(['/home/user1/tmp/coverage/test', '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members']) '/home/user1/tmp'
Generate an equivalent C# version of this VB code.
Debug.Print Hex(&HF0F0 And &HFF00) Debug.Print Hex(&HF0F0 Or &HFF00) Debug.Print Hex(&HF0F0 Xor &HFF00) Debug.Print Hex(Not &HF0F0) Debug.Print Hex(&HF0F0 Eqv &HFF00) Debug.Print Hex(&HF0F0 Imp &HFF00)
static void bitwise(int a, int b) { Console.WriteLine("a and b is {0}", a & b); Console.WriteLine("a or b is {0}", a | b); Console.WriteLine("a xor b is {0}", a ^ b); Console.WriteLine("not a is {0}", ~a); Console.WriteLine("a lshift b is {0}", a << b); Console.WriteLine("a arshift b is {0}", a >> b); uint c = (uint)a; Console.WriteLine("c rshift b is {0}", c >> b); }
Port the provided VB code into C# while preserving the original functionality.
option explicit const pi180= 0.01745329251994329576923690768489 const pi=3.1415926535897932384626433832795 class turtle dim fso dim fn dim svg dim iang dim ori dim incr dim pdown dim clr dim x dim y public property let orient(n):ori = n*pi180 :end property public property let iangle(n):iang= n*pi180 :end property public sub pd() : pdown=true: end sub public sub pu() :pdown=FALSE :end sub public sub rt(i) ori=ori - i*iang: end sub public sub lt(i): ori=(ori + i*iang) end sub public sub bw(l) x= x+ cos(ori+pi)*l*incr y= y+ sin(ori+pi)*l*incr end sub public sub fw(l) dim x1,y1 x1=x + cos(ori)*l*incr y1=y + sin(ori)*l*incr if pdown then line x,y,x1,y1 x=x1:y=y1 end sub Private Sub Class_Initialize() setlocale "us" initsvg x=400:y=400:incr=100 ori=90*pi180 iang=90*pi180 clr=0 pdown=true end sub Private Sub Class_Terminate() disply end sub private sub line (x,y,x1,y1) svg.WriteLine "<line x1=""" & x & """ y1= """& y & """ x2=""" & x1& """ y2=""" & y1 & """/>" end sub private sub disply() dim shell svg.WriteLine "</svg></body></html>" svg.close Set shell = CreateObject("Shell.Application") shell.ShellExecute fn,1,False end sub private sub initsvg() dim scriptpath Set fso = CreateObject ("Scripting.Filesystemobject") ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\")) fn=Scriptpath & "SIERP.HTML" Set svg = fso.CreateTextFile(fn,True) if SVG IS nothing then wscript.echo "Can svg.WriteLine "<!DOCTYPE html>" &vbcrlf & "<html>" &vbcrlf & "<head>" svg.writeline "<style>" & vbcrlf & "line {stroke:rgb(255,0,0);stroke-width:.5}" &vbcrlf &"</style>" svg.writeline "</head>"&vbcrlf & "<body>" svg.WriteLine "<svg xmlns=""http://www.w3.org/2000/svg"" width=""800"" height=""800"" viewBox=""0 0 800 800"">" end sub end class sub dragon(st,le,dir) if st=0 then x.fw le: exit sub x.rt dir dragon st-1, le/1.41421 ,1 x.rt dir*2 dragon st-1, le/1.41421 ,-1 x.rt dir end sub dim x set x=new turtle x.iangle=45 x.orient=45 x.incr=1 x.x=200:x.y=200 dragon 12,300,1 set x=nothing
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; public class DragonCurve : Form { private List<int> turns; private double startingAngle, side; public DragonCurve(int iter) { Size = new Size(800, 600); StartPosition = FormStartPosition.CenterScreen; DoubleBuffered = true; BackColor = Color.White; startingAngle = -iter * (Math.PI / 4); side = 400 / Math.Pow(2, iter / 2.0); turns = getSequence(iter); } private List<int> getSequence(int iter) { var turnSequence = new List<int>(); for (int i = 0; i < iter; i++) { var copy = new List<int>(turnSequence); copy.Reverse(); turnSequence.Add(1); foreach (int turn in copy) { turnSequence.Add(-turn); } } return turnSequence; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; double angle = startingAngle; int x1 = 230, y1 = 350; int x2 = x1 + (int)(Math.Cos(angle) * side); int y2 = y1 + (int)(Math.Sin(angle) * side); e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2); x1 = x2; y1 = y2; foreach (int turn in turns) { angle += turn * (Math.PI / 2); x2 = x1 + (int)(Math.Cos(angle) * side); y2 = y1 + (int)(Math.Sin(angle) * side); e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2); x1 = x2; y1 = y2; } } [STAThread] static void Main() { Application.Run(new DragonCurve(14)); } }