Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Port the following code from C# to Python with equivalent syntax and logic.
using System; using System.Reflection; public class MyClass { private int answer = 42; } public class Program { public static void Main() { var myInstance = new MyClass(); var fieldInfo = typeof(MyClass).GetField("answer", BindingFlags.NonPublic | BindingFlags.Instance); var answer = fieldInfo.GetValue(myInstance); Console.WriteLine(answer); } }
>>> class MyClassName: __private = 123 non_private = __private * 2 >>> mine = MyClassName() >>> mine.non_private 246 >>> mine.__private Traceback (most recent call last): File "<pyshell mine.__private AttributeError: 'MyClassName' object has no attribute '__private' >>> mine._MyClassName__private 123 >>>
Change the following C# code into Python without altering its purpose.
using System; using System.Reflection; public class MyClass { private int answer = 42; } public class Program { public static void Main() { var myInstance = new MyClass(); var fieldInfo = typeof(MyClass).GetField("answer", BindingFlags.NonPublic | BindingFlags.Instance); var answer = fieldInfo.GetValue(myInstance); Console.WriteLine(answer); } }
>>> class MyClassName: __private = 123 non_private = __private * 2 >>> mine = MyClassName() >>> mine.non_private 246 >>> mine.__private Traceback (most recent call last): File "<pyshell mine.__private AttributeError: 'MyClassName' object has no attribute '__private' >>> mine._MyClassName__private 123 >>>
Port the following code from C# to Python with equivalent syntax and logic.
using System; using System.IO; using System.Collections.Generic; using System.Runtime.Serialization.Formatters.Binary; namespace Object_serialization { [Serializable] public class Being { public bool Alive { get; set; } } [Serializable] public class Animal: Being { public Animal() { } public Animal(long id, string name, bool alive = true) { Id = id; Name = name; Alive = alive; } public long Id { get; set; } public string Name { get; set; } public void Print() { Console.WriteLine("{0}, id={1} is {2}", Name, Id, Alive ? "alive" : "dead"); } } internal class Program { private static void Main() { string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+"\\objects.dat"; var n = new List<Animal> { new Animal(1, "Fido"), new Animal(2, "Lupo"), new Animal(7, "Wanda"), new Animal(3, "Kiki", alive: false) }; foreach(Animal animal in n) animal.Print(); using(var stream = new FileStream(path, FileMode.Create, FileAccess.Write)) new BinaryFormatter().Serialize(stream, n); n.Clear(); Console.WriteLine("---------------"); List<Animal> m; using(var stream = new FileStream(path, FileMode.Open, FileAccess.Read)) m = (List<Animal>) new BinaryFormatter().Deserialize(stream); foreach(Animal animal in m) animal.Print(); } } }
import pickle class Entity: def __init__(self): self.name = "Entity" def printName(self): print self.name class Person(Entity): def __init__(self): self.name = "Cletus" instance1 = Person() instance1.printName() instance2 = Entity() instance2.printName() target = file("objects.dat", "w") pickle.dump((instance1, instance2), target) target.close() print "Serialized..." target = file("objects.dat") i1, i2 = pickle.load(target) print "Unserialized..." i1.printName() i2.printName()
Rewrite this program in Python while keeping its functionality equivalent to the C# version.
using System; using System.Collections.Generic; namespace Eertree { class Node { public Node(int length) { this.Length = length; this.Edges = new Dictionary<char, int>(); } public Node(int length, Dictionary<char, int> edges, int suffix) { this.Length = length; this.Edges = edges; this.Suffix = suffix; } public int Length { get; set; } public Dictionary<char, int> Edges { get; set; } public int Suffix { get; set; } } class Program { const int EVEN_ROOT = 0; const int ODD_ROOT = 1; static List<Node> Eertree(string s) { List<Node> tree = new List<Node> { new Node(0, new Dictionary<char, int>(), ODD_ROOT), new Node(-1, new Dictionary<char, int>(), ODD_ROOT) }; int suffix = ODD_ROOT; int n, k; for (int i = 0; i < s.Length; i++) { char c = s[i]; for (n = suffix; ; n = tree[n].Suffix) { k = tree[n].Length; int b = i - k - 1; if (b >= 0 && s[b] == c) { break; } } if (tree[n].Edges.ContainsKey(c)) { suffix = tree[n].Edges[c]; continue; } suffix = tree.Count; tree.Add(new Node(k + 2)); tree[n].Edges[c] = suffix; if (tree[suffix].Length == 1) { tree[suffix].Suffix = 0; continue; } while (true) { n = tree[n].Suffix; int b = i - tree[n].Length - 1; if (b >= 0 && s[b] == c) { break; } } tree[suffix].Suffix = tree[n].Edges[c]; } return tree; } static List<string> SubPalindromes(List<Node> tree) { List<string> s = new List<string>(); SubPalindromes_children(0, "", tree, s); foreach (var c in tree[1].Edges.Keys) { int m = tree[1].Edges[c]; string ct = c.ToString(); s.Add(ct); SubPalindromes_children(m, ct, tree, s); } return s; } static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) { foreach (var c in tree[n].Edges.Keys) { int m = tree[n].Edges[c]; string p1 = c + p + c; s.Add(p1); SubPalindromes_children(m, p1, tree, s); } } static void Main(string[] args) { List<Node> tree = Eertree("eertree"); List<string> result = SubPalindromes(tree); string listStr = string.Join(", ", result); Console.WriteLine("[{0}]", listStr); } } }
from __future__ import print_function class Node(object): def __init__(self): self.edges = {} self.link = None self.len = 0 class Eertree(object): def __init__(self): self.nodes = [] self.rto = Node() self.rte = Node() self.rto.link = self.rte.link = self.rto; self.rto.len = -1 self.rte.len = 0 self.S = [0] self.maxSufT = self.rte def get_max_suffix_pal(self, startNode, a): u = startNode i = len(self.S) k = u.len while id(u) != id(self.rto) and self.S[i - k - 1] != a: assert id(u) != id(u.link) u = u.link k = u.len return u def add(self, a): Q = self.get_max_suffix_pal(self.maxSufT, a) createANewNode = not a in Q.edges if createANewNode: P = Node() self.nodes.append(P) P.len = Q.len + 2 if P.len == 1: P.link = self.rte else: P.link = self.get_max_suffix_pal(Q.link, a).edges[a] Q.edges[a] = P self.maxSufT = Q.edges[a] self.S.append(a) return createANewNode def get_sub_palindromes(self, nd, nodesToHere, charsToHere, result): for lnkName in nd.edges: nd2 = nd.edges[lnkName] self.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result) if id(nd) != id(self.rto) and id(nd) != id(self.rte): tmp = "".join(charsToHere) if id(nodesToHere[0]) == id(self.rte): assembled = tmp[::-1] + tmp else: assembled = tmp[::-1] + tmp[1:] result.append(assembled) if __name__=="__main__": st = "eertree" print ("Processing string", st) eertree = Eertree() for ch in st: eertree.add(ch) print ("Number of sub-palindromes:", len(eertree.nodes)) result = [] eertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) eertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) print ("Sub-palindromes:", result)
Write the same code in Python as shown below in C#.
using System; using System.Collections.Generic; namespace Eertree { class Node { public Node(int length) { this.Length = length; this.Edges = new Dictionary<char, int>(); } public Node(int length, Dictionary<char, int> edges, int suffix) { this.Length = length; this.Edges = edges; this.Suffix = suffix; } public int Length { get; set; } public Dictionary<char, int> Edges { get; set; } public int Suffix { get; set; } } class Program { const int EVEN_ROOT = 0; const int ODD_ROOT = 1; static List<Node> Eertree(string s) { List<Node> tree = new List<Node> { new Node(0, new Dictionary<char, int>(), ODD_ROOT), new Node(-1, new Dictionary<char, int>(), ODD_ROOT) }; int suffix = ODD_ROOT; int n, k; for (int i = 0; i < s.Length; i++) { char c = s[i]; for (n = suffix; ; n = tree[n].Suffix) { k = tree[n].Length; int b = i - k - 1; if (b >= 0 && s[b] == c) { break; } } if (tree[n].Edges.ContainsKey(c)) { suffix = tree[n].Edges[c]; continue; } suffix = tree.Count; tree.Add(new Node(k + 2)); tree[n].Edges[c] = suffix; if (tree[suffix].Length == 1) { tree[suffix].Suffix = 0; continue; } while (true) { n = tree[n].Suffix; int b = i - tree[n].Length - 1; if (b >= 0 && s[b] == c) { break; } } tree[suffix].Suffix = tree[n].Edges[c]; } return tree; } static List<string> SubPalindromes(List<Node> tree) { List<string> s = new List<string>(); SubPalindromes_children(0, "", tree, s); foreach (var c in tree[1].Edges.Keys) { int m = tree[1].Edges[c]; string ct = c.ToString(); s.Add(ct); SubPalindromes_children(m, ct, tree, s); } return s; } static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) { foreach (var c in tree[n].Edges.Keys) { int m = tree[n].Edges[c]; string p1 = c + p + c; s.Add(p1); SubPalindromes_children(m, p1, tree, s); } } static void Main(string[] args) { List<Node> tree = Eertree("eertree"); List<string> result = SubPalindromes(tree); string listStr = string.Join(", ", result); Console.WriteLine("[{0}]", listStr); } } }
from __future__ import print_function class Node(object): def __init__(self): self.edges = {} self.link = None self.len = 0 class Eertree(object): def __init__(self): self.nodes = [] self.rto = Node() self.rte = Node() self.rto.link = self.rte.link = self.rto; self.rto.len = -1 self.rte.len = 0 self.S = [0] self.maxSufT = self.rte def get_max_suffix_pal(self, startNode, a): u = startNode i = len(self.S) k = u.len while id(u) != id(self.rto) and self.S[i - k - 1] != a: assert id(u) != id(u.link) u = u.link k = u.len return u def add(self, a): Q = self.get_max_suffix_pal(self.maxSufT, a) createANewNode = not a in Q.edges if createANewNode: P = Node() self.nodes.append(P) P.len = Q.len + 2 if P.len == 1: P.link = self.rte else: P.link = self.get_max_suffix_pal(Q.link, a).edges[a] Q.edges[a] = P self.maxSufT = Q.edges[a] self.S.append(a) return createANewNode def get_sub_palindromes(self, nd, nodesToHere, charsToHere, result): for lnkName in nd.edges: nd2 = nd.edges[lnkName] self.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result) if id(nd) != id(self.rto) and id(nd) != id(self.rte): tmp = "".join(charsToHere) if id(nodesToHere[0]) == id(self.rte): assembled = tmp[::-1] + tmp else: assembled = tmp[::-1] + tmp[1:] result.append(assembled) if __name__=="__main__": st = "eertree" print ("Processing string", st) eertree = Eertree() for ch in st: eertree.add(ch) print ("Number of sub-palindromes:", len(eertree.nodes)) result = [] eertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) eertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) print ("Sub-palindromes:", result)
Ensure the translated Python code behaves exactly like the original C# snippet.
using static System.Console; using System.Collections.Generic; using System.Linq; using System.Globalization; public static class Program { public static void Main() { WriteLine("Long years in the 21st century:"); WriteLine(string.Join(" ", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == 53))); } public static IEnumerable<int> To(this int start, int end) { for (int i = start; i < end; i++) yield return i; } }
from datetime import date def longYear(y): return 52 < date(y, 12, 28).isocalendar()[1] def main(): for year in [ x for x in range(2000, 1 + 2100) if longYear(x) ]: print(year) if __name__ == '__main__': main()
Can you help me rewrite this code in Python instead of C#, keeping it the same logically?
using System; using System.Collections.Generic; using System.Linq; namespace ZumkellerNumbers { class Program { static List<int> GetDivisors(int n) { List<int> divs = new List<int> { 1, n }; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { int j = n / i; divs.Add(i); if (i != j) { divs.Add(j); } } } return divs; } static bool IsPartSum(List<int> divs, int sum) { if (sum == 0) { return true; } var le = divs.Count; if (le == 0) { return false; } var last = divs[le - 1]; List<int> newDivs = new List<int>(); for (int i = 0; i < le - 1; i++) { newDivs.Add(divs[i]); } if (last > sum) { return IsPartSum(newDivs, sum); } return IsPartSum(newDivs, sum) || IsPartSum(newDivs, sum - last); } static bool IsZumkeller(int n) { var divs = GetDivisors(n); var sum = divs.Sum(); if (sum % 2 == 1) { return false; } if (n % 2 == 1) { var abundance = sum - 2 * n; return abundance > 0 && abundance % 2 == 0; } return IsPartSum(divs, sum / 2); } static void Main() { Console.WriteLine("The first 220 Zumkeller numbers are:"); int i = 2; for (int count = 0; count < 220; i++) { if (IsZumkeller(i)) { Console.Write("{0,3} ", i); count++; if (count % 20 == 0) { Console.WriteLine(); } } } Console.WriteLine("\nThe first 40 odd Zumkeller numbers are:"); i = 3; for (int count = 0; count < 40; i += 2) { if (IsZumkeller(i)) { Console.Write("{0,5} ", i); count++; if (count % 10 == 0) { Console.WriteLine(); } } } Console.WriteLine("\nThe first 40 odd Zumkeller numbers which don't end in 5 are:"); i = 3; for (int count = 0; count < 40; i += 2) { if (i % 10 != 5 && IsZumkeller(i)) { Console.Write("{0,7} ", i); count++; if (count % 8 == 0) { Console.WriteLine(); } } } } } }
from sympy import divisors from sympy.combinatorics.subsets import Subset def isZumkeller(n): d = divisors(n) s = sum(d) if not s % 2 and max(d) <= s/2: for x in range(1, 2**len(d)): if sum(Subset.unrank_binary(x, d).subset) == s/2: return True return False def printZumkellers(N, oddonly=False): nprinted = 0 for n in range(1, 10**5): if (oddonly == False or n % 2) and isZumkeller(n): print(f'{n:>8}', end='') nprinted += 1 if nprinted % 10 == 0: print() if nprinted >= N: return print("220 Zumkeller numbers:") printZumkellers(220) print("\n\n40 odd Zumkeller numbers:") printZumkellers(40, True)
Maintain the same structure and functionality when rewriting this code in Python.
using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { var baseData = new Dictionary<string, object> { ["name"] = "Rocket Skates", ["price"] = 12.75, ["color"] = "yellow" }; var updateData = new Dictionary<string, object> { ["price"] = 15.25, ["color"] = "red", ["year"] = 1974 }; var mergedData = new Dictionary<string, object>(); foreach (var entry in baseData.Concat(updateData)) { mergedData[entry.Key] = entry.Value; } foreach (var entry in mergedData) { Console.WriteLine(entry); } } }
base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"} update = {"price":15.25, "color":"red", "year":1974} result = {**base, **update} print(result)
Ensure the translated Python code behaves exactly like the original C# snippet.
using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { var baseData = new Dictionary<string, object> { ["name"] = "Rocket Skates", ["price"] = 12.75, ["color"] = "yellow" }; var updateData = new Dictionary<string, object> { ["price"] = 15.25, ["color"] = "red", ["year"] = 1974 }; var mergedData = new Dictionary<string, object>(); foreach (var entry in baseData.Concat(updateData)) { mergedData[entry.Key] = entry.Value; } foreach (var entry in mergedData) { Console.WriteLine(entry); } } }
base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"} update = {"price":15.25, "color":"red", "year":1974} result = {**base, **update} print(result)
Transform the following C# implementation into Python, maintaining the same output and logic.
using static System.Math; using static System.Console; using BI = System.Numerics.BigInteger; class Program { static BI IntSqRoot(BI v, BI res) { BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1; dl = d; d = term - res; } return term; } static string doOne(int b, int digs) { int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)), bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g); bs += b * BI.Parse('1' + new string('0', digs)); bs >>= 1; bs += 4; string st = bs.ToString(); return string.Format("{0}.{1}", st[0], st.Substring(1, --digs)); } static string divIt(BI a, BI b, int digs) { int al = a.ToString().Length, bl = b.ToString().Length; a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs); string s = (a / b + 5).ToString(); return s[0] + "." + s.Substring(1, --digs); } static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; string res = ""; for (int i = 0; i < x.Length; i++) res += string.Format("{0," + (-wids[i]).ToString() + "} ", x[i]); return res; } static void Main(string[] args) { WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc"); int k; string lt, t = ""; BI n, nm1, on; for (int b = 0; b < 10; b++) { BI[] lst = new BI[15]; lst[0] = lst[1] = 1; for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2]; n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) { lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j; on = n; n = b * n + nm1; nm1 = on; } WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}\n{6,19} {7}", "Pt Au Ag CuSn Cu Ni Al Fe Sn Pb" .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), "", joined(lst)); } n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) { lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j; on = n; n += nm1; nm1 = on; } WriteLine("\nAu to 256 digits:"); WriteLine(t); WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t == doOne(1, 256)); } }
from itertools import count, islice from _pydecimal import getcontext, Decimal def metallic_ratio(b): m, n = 1, 1 while True: yield m, n m, n = m*b + n, m def stable(b, prec): def to_decimal(b): for m,n in metallic_ratio(b): yield Decimal(m)/Decimal(n) getcontext().prec = prec last = 0 for i,x in zip(count(), to_decimal(b)): if x == last: print(f'after {i} iterations:\n\t{x}') break last = x for b in range(4): coefs = [n for _,n in islice(metallic_ratio(b), 15)] print(f'\nb = {b}: {coefs}') stable(b, 32) print(f'\nb = 1 with 256 digits:') stable(1, 256)
Write a version of this C# function in Python with identical behavior.
using static System.Math; using static System.Console; using BI = System.Numerics.BigInteger; class Program { static BI IntSqRoot(BI v, BI res) { BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1; dl = d; d = term - res; } return term; } static string doOne(int b, int digs) { int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)), bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g); bs += b * BI.Parse('1' + new string('0', digs)); bs >>= 1; bs += 4; string st = bs.ToString(); return string.Format("{0}.{1}", st[0], st.Substring(1, --digs)); } static string divIt(BI a, BI b, int digs) { int al = a.ToString().Length, bl = b.ToString().Length; a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs); string s = (a / b + 5).ToString(); return s[0] + "." + s.Substring(1, --digs); } static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; string res = ""; for (int i = 0; i < x.Length; i++) res += string.Format("{0," + (-wids[i]).ToString() + "} ", x[i]); return res; } static void Main(string[] args) { WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc"); int k; string lt, t = ""; BI n, nm1, on; for (int b = 0; b < 10; b++) { BI[] lst = new BI[15]; lst[0] = lst[1] = 1; for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2]; n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) { lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j; on = n; n = b * n + nm1; nm1 = on; } WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}\n{6,19} {7}", "Pt Au Ag CuSn Cu Ni Al Fe Sn Pb" .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), "", joined(lst)); } n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) { lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j; on = n; n += nm1; nm1 = on; } WriteLine("\nAu to 256 digits:"); WriteLine(t); WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t == doOne(1, 256)); } }
from itertools import count, islice from _pydecimal import getcontext, Decimal def metallic_ratio(b): m, n = 1, 1 while True: yield m, n m, n = m*b + n, m def stable(b, prec): def to_decimal(b): for m,n in metallic_ratio(b): yield Decimal(m)/Decimal(n) getcontext().prec = prec last = 0 for i,x in zip(count(), to_decimal(b)): if x == last: print(f'after {i} iterations:\n\t{x}') break last = x for b in range(4): coefs = [n for _,n in islice(metallic_ratio(b), 15)] print(f'\nb = {b}: {coefs}') stable(b, 32) print(f'\nb = 1 with 256 digits:') stable(1, 256)
Rewrite the snippet below in Python so it works the same as the original C# code.
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace MarkovChainTextGenerator { class Program { static string Join(string a, string b) { return a + " " + b; } static string Markov(string filePath, int keySize, int outputSize) { if (keySize < 1) throw new ArgumentException("Key size can't be less than 1"); string body; using (StreamReader sr = new StreamReader(filePath)) { body = sr.ReadToEnd(); } var words = body.Split(); if (outputSize < keySize || words.Length < outputSize) { throw new ArgumentException("Output size is out of range"); } Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>(); for (int i = 0; i < words.Length - keySize; i++) { var key = words.Skip(i).Take(keySize).Aggregate(Join); string value; if (i + keySize < words.Length) { value = words[i + keySize]; } else { value = ""; } if (dict.ContainsKey(key)) { dict[key].Add(value); } else { dict.Add(key, new List<string>() { value }); } } Random rand = new Random(); List<string> output = new List<string>(); int n = 0; int rn = rand.Next(dict.Count); string prefix = dict.Keys.Skip(rn).Take(1).Single(); output.AddRange(prefix.Split()); while (true) { var suffix = dict[prefix]; if (suffix.Count == 1) { if (suffix[0] == "") { return output.Aggregate(Join); } output.Add(suffix[0]); } else { rn = rand.Next(suffix.Count); output.Add(suffix[rn]); } if (output.Count >= outputSize) { return output.Take(outputSize).Aggregate(Join); } n++; prefix = output.Skip(n).Take(keySize).Aggregate(Join); } } static void Main(string[] args) { Console.WriteLine(Markov("alice_oz.txt", 3, 200)); } } }
import random, sys def makerule(data, context): rule = {} words = data.split(' ') index = context for word in words[index:]: key = ' '.join(words[index-context:index]) if key in rule: rule[key].append(word) else: rule[key] = [word] index += 1 return rule def makestring(rule, length): oldwords = random.choice(list(rule.keys())).split(' ') string = ' '.join(oldwords) + ' ' for i in range(length): try: key = ' '.join(oldwords) newword = random.choice(rule[key]) string += newword + ' ' for word in range(len(oldwords)): oldwords[word] = oldwords[(word + 1) % len(oldwords)] oldwords[-1] = newword except KeyError: return string return string if __name__ == '__main__': with open(sys.argv[1], encoding='utf8') as f: data = f.read() rule = makerule(data, int(sys.argv[2])) string = makestring(rule, int(sys.argv[3])) print(string)
Rewrite the snippet below in Python so it works the same as the original C# code.
using static System.Linq.Enumerable; using static System.String; using static System.Console; using System.Collections.Generic; using System; using EdgeList = System.Collections.Generic.List<(int node, double weight)>; public static class Dijkstra { public static void Main() { Graph graph = new Graph(6); Func<char, int> id = c => c - 'a'; Func<int , char> name = i => (char)(i + 'a'); foreach (var (start, end, cost) in new [] { ('a', 'b', 7), ('a', 'c', 9), ('a', 'f', 14), ('b', 'c', 10), ('b', 'd', 15), ('c', 'd', 11), ('c', 'f', 2), ('d', 'e', 6), ('e', 'f', 9), }) { graph.AddEdge(id(start), id(end), cost); } var path = graph.FindPath(id('a')); for (int d = id('b'); d <= id('f'); d++) { WriteLine(Join(" -> ", Path(id('a'), d).Select(p => $"{name(p.node)}({p.distance})").Reverse())); } IEnumerable<(double distance, int node)> Path(int start, int destination) { yield return (path[destination].distance, destination); for (int i = destination; i != start; i = path[i].prev) { yield return (path[path[i].prev].distance, path[i].prev); } } } } sealed class Graph { private readonly List<EdgeList> adjacency; public Graph(int vertexCount) => adjacency = Range(0, vertexCount).Select(v => new EdgeList()).ToList(); public int Count => adjacency.Count; public bool HasEdge(int s, int e) => adjacency[s].Any(p => p.node == e); public bool RemoveEdge(int s, int e) => adjacency[s].RemoveAll(p => p.node == e) > 0; public bool AddEdge(int s, int e, double weight) { if (HasEdge(s, e)) return false; adjacency[s].Add((e, weight)); return true; } public (double distance, int prev)[] FindPath(int start) { var info = Range(0, adjacency.Count).Select(i => (distance: double.PositiveInfinity, prev: i)).ToArray(); info[start].distance = 0; var visited = new System.Collections.BitArray(adjacency.Count); var heap = new Heap<(int node, double distance)>((a, b) => a.distance.CompareTo(b.distance)); heap.Push((start, 0)); while (heap.Count > 0) { var current = heap.Pop(); if (visited[current.node]) continue; var edges = adjacency[current.node]; for (int n = 0; n < edges.Count; n++) { int v = edges[n].node; if (visited[v]) continue; double alt = info[current.node].distance + edges[n].weight; if (alt < info[v].distance) { info[v] = (alt, current.node); heap.Push((v, alt)); } } visited[current.node] = true; } return info; } } sealed class Heap<T> { private readonly IComparer<T> comparer; private readonly List<T> list = new List<T> { default }; public Heap() : this(default(IComparer<T>)) { } public Heap(IComparer<T> comparer) { this.comparer = comparer ?? Comparer<T>.Default; } public Heap(Comparison<T> comparison) : this(Comparer<T>.Create(comparison)) { } public int Count => list.Count - 1; public void Push(T element) { list.Add(element); SiftUp(list.Count - 1); } public T Pop() { T result = list[1]; list[1] = list[list.Count - 1]; list.RemoveAt(list.Count - 1); SiftDown(1); return result; } private static int Parent(int i) => i / 2; private static int Left(int i) => i * 2; private static int Right(int i) => i * 2 + 1; private void SiftUp(int i) { while (i > 1) { int parent = Parent(i); if (comparer.Compare(list[i], list[parent]) > 0) return; (list[parent], list[i]) = (list[i], list[parent]); i = parent; } } private void SiftDown(int i) { for (int left = Left(i); left < list.Count; left = Left(i)) { int smallest = comparer.Compare(list[left], list[i]) <= 0 ? left : i; int right = Right(i); if (right < list.Count && comparer.Compare(list[right], list[smallest]) <= 0) smallest = right; if (smallest == i) return; (list[i], list[smallest]) = (list[smallest], list[i]); i = smallest; } } }
from collections import namedtuple, deque from pprint import pprint as pp inf = float('inf') Edge = namedtuple('Edge', ['start', 'end', 'cost']) class Graph(): def __init__(self, edges): self.edges = [Edge(*edge) for edge in edges] self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges} def dijkstra(self, source, dest): assert source in self.vertices dist = {vertex: inf for vertex in self.vertices} previous = {vertex: None for vertex in self.vertices} dist[source] = 0 q = self.vertices.copy() neighbours = {vertex: set() for vertex in self.vertices} for start, end, cost in self.edges: neighbours[start].add((end, cost)) neighbours[end].add((start, cost)) while q: u = min(q, key=lambda vertex: dist[vertex]) q.remove(u) if dist[u] == inf or u == dest: break for v, cost in neighbours[u]: alt = dist[u] + cost if alt < dist[v]: dist[v] = alt previous[v] = u s, u = deque(), dest while previous[u]: s.appendleft(u) u = previous[u] s.appendleft(u) return s graph = Graph([("a", "b", 7), ("a", "c", 9), ("a", "f", 14), ("b", "c", 10), ("b", "d", 15), ("c", "d", 11), ("c", "f", 2), ("d", "e", 6), ("e", "f", 9)]) pp(graph.dijkstra("a", "e"))
Port the following code from C# to Python with equivalent syntax and logic.
using System; using System.Text; namespace GeometricAlgebra { struct Vector { private readonly double[] dims; public Vector(double[] da) { dims = da; } public static Vector operator -(Vector v) { return v * -1.0; } public static Vector operator +(Vector lhs, Vector rhs) { var result = new double[32]; Array.Copy(lhs.dims, 0, result, 0, lhs.Length); for (int i = 0; i < result.Length; i++) { result[i] = lhs[i] + rhs[i]; } return new Vector(result); } public static Vector operator *(Vector lhs, Vector rhs) { var result = new double[32]; for (int i = 0; i < lhs.Length; i++) { if (lhs[i] != 0.0) { for (int j = 0; j < lhs.Length; j++) { if (rhs[j] != 0.0) { var s = ReorderingSign(i, j) * lhs[i] * rhs[j]; var k = i ^ j; result[k] += s; } } } } return new Vector(result); } public static Vector operator *(Vector v, double scale) { var result = (double[])v.dims.Clone(); for (int i = 0; i < result.Length; i++) { result[i] *= scale; } return new Vector(result); } public double this[int key] { get { return dims[key]; } set { dims[key] = value; } } public int Length { get { return dims.Length; } } public Vector Dot(Vector rhs) { return (this * rhs + rhs * this) * 0.5; } private static int BitCount(int i) { i -= ((i >> 1) & 0x55555555); i = (i & 0x33333333) + ((i >> 2) & 0x33333333); i = (i + (i >> 4)) & 0x0F0F0F0F; i += (i >> 8); i += (i >> 16); return i & 0x0000003F; } private static double ReorderingSign(int i, int j) { int k = i >> 1; int sum = 0; while (k != 0) { sum += BitCount(k & j); k >>= 1; } return ((sum & 1) == 0) ? 1.0 : -1.0; } public override string ToString() { var it = dims.GetEnumerator(); StringBuilder sb = new StringBuilder("["); if (it.MoveNext()) { sb.Append(it.Current); } while (it.MoveNext()) { sb.Append(", "); sb.Append(it.Current); } sb.Append(']'); return sb.ToString(); } } class Program { static double[] DoubleArray(uint size) { double[] result = new double[size]; for (int i = 0; i < size; i++) { result[i] = 0.0; } return result; } static Vector E(int n) { if (n > 4) { throw new ArgumentException("n must be less than 5"); } var result = new Vector(DoubleArray(32)); result[1 << n] = 1.0; return result; } static readonly Random r = new Random(); static Vector RandomVector() { var result = new Vector(DoubleArray(32)); for (int i = 0; i < 5; i++) { var singleton = new double[] { r.NextDouble() }; result += new Vector(singleton) * E(i); } return result; } static Vector RandomMultiVector() { var result = new Vector(DoubleArray(32)); for (int i = 0; i < result.Length; i++) { result[i] = r.NextDouble(); } return result; } static void Main() { for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (i < j) { if (E(i).Dot(E(j))[0] != 0.0) { Console.WriteLine("Unexpected non-null sclar product."); return; } } else if (i == j) { if ((E(i).Dot(E(j)))[0] == 0.0) { Console.WriteLine("Unexpected null sclar product."); } } } } var a = RandomMultiVector(); var b = RandomMultiVector(); var c = RandomMultiVector(); var x = RandomVector(); Console.WriteLine((a * b) * c); Console.WriteLine(a * (b * c)); Console.WriteLine(); Console.WriteLine(a * (b + c)); Console.WriteLine(a * b + a * c); Console.WriteLine(); Console.WriteLine((a + b) * c); Console.WriteLine(a * c + b * c); Console.WriteLine(); Console.WriteLine(x * x); } } }
import copy, random def bitcount(n): return bin(n).count("1") def reoderingSign(i, j): k = i >> 1 sum = 0 while k != 0: sum += bitcount(k & j) k = k >> 1 return 1.0 if ((sum & 1) == 0) else -1.0 class Vector: def __init__(self, da): self.dims = da def dot(self, other): return (self * other + other * self) * 0.5 def __getitem__(self, i): return self.dims[i] def __setitem__(self, i, v): self.dims[i] = v def __neg__(self): return self * -1.0 def __add__(self, other): result = copy.copy(other.dims) for i in xrange(0, len(self.dims)): result[i] += self.dims[i] return Vector(result) def __mul__(self, other): if isinstance(other, Vector): result = [0.0] * 32 for i in xrange(0, len(self.dims)): if self.dims[i] != 0.0: for j in xrange(0, len(self.dims)): if other.dims[j] != 0.0: s = reoderingSign(i, j) * self.dims[i] * other.dims[j] k = i ^ j result[k] += s return Vector(result) else: result = copy.copy(self.dims) for i in xrange(0, len(self.dims)): self.dims[i] *= other return Vector(result) def __str__(self): return str(self.dims) def e(n): assert n <= 4, "n must be less than 5" result = Vector([0.0] * 32) result[1 << n] = 1.0 return result def randomVector(): result = Vector([0.0] * 32) for i in xrange(0, 5): result += Vector([random.uniform(0, 1)]) * e(i) return result def randomMultiVector(): result = Vector([0.0] * 32) for i in xrange(0, 32): result[i] = random.uniform(0, 1) return result def main(): for i in xrange(0, 5): for j in xrange(0, 5): if i < j: if e(i).dot(e(j))[0] != 0.0: print "Unexpected non-null scalar product" return elif i == j: if e(i).dot(e(j))[0] == 0.0: print "Unexpected non-null scalar product" a = randomMultiVector() b = randomMultiVector() c = randomMultiVector() x = randomVector() print (a * b) * c print a * (b * c) print print a * (b + c) print a * b + a * c print print (a + b) * c print a * c + b * c print print x * x main()
Port the provided C# code into Python while preserving the original functionality.
using System; using System.Collections.Generic; namespace SuffixTree { class Node { public string sub; public List<int> ch = new List<int>(); public Node() { sub = ""; } public Node(string sub, params int[] children) { this.sub = sub; ch.AddRange(children); } } class SuffixTree { readonly List<Node> nodes = new List<Node>(); public SuffixTree(string str) { nodes.Add(new Node()); for (int i = 0; i < str.Length; i++) { AddSuffix(str.Substring(i)); } } public void Visualize() { if (nodes.Count == 0) { Console.WriteLine("<empty>"); return; } void f(int n, string pre) { var children = nodes[n].ch; if (children.Count == 0) { Console.WriteLine("- {0}", nodes[n].sub); return; } Console.WriteLine("+ {0}", nodes[n].sub); var it = children.GetEnumerator(); if (it.MoveNext()) { do { var cit = it; if (!cit.MoveNext()) break; Console.Write("{0}+-", pre); f(it.Current, pre + "| "); } while (it.MoveNext()); } Console.Write("{0}+-", pre); f(children[children.Count-1], pre+" "); } f(0, ""); } private void AddSuffix(string suf) { int n = 0; int i = 0; while (i < suf.Length) { char b = suf[i]; int x2 = 0; int n2; while (true) { var children = nodes[n].ch; if (x2 == children.Count) { n2 = nodes.Count; nodes.Add(new Node(suf.Substring(i))); nodes[n].ch.Add(n2); return; } n2 = children[x2]; if (nodes[n2].sub[0] == b) { break; } x2++; } var sub2 = nodes[n2].sub; int j = 0; while (j < sub2.Length) { if (suf[i + j] != sub2[j]) { var n3 = n2; n2 = nodes.Count; nodes.Add(new Node(sub2.Substring(0, j), n3)); nodes[n3].sub = sub2.Substring(j); nodes[n].ch[x2] = n2; break; } j++; } i += j; n = n2; } } } class Program { static void Main() { new SuffixTree("banana$").Visualize(); } } }
class Node: def __init__(self, sub="", children=None): self.sub = sub self.ch = children or [] class SuffixTree: def __init__(self, str): self.nodes = [Node()] for i in range(len(str)): self.addSuffix(str[i:]) def addSuffix(self, suf): n = 0 i = 0 while i < len(suf): b = suf[i] x2 = 0 while True: children = self.nodes[n].ch if x2 == len(children): n2 = len(self.nodes) self.nodes.append(Node(suf[i:], [])) self.nodes[n].ch.append(n2) return n2 = children[x2] if self.nodes[n2].sub[0] == b: break x2 = x2 + 1 sub2 = self.nodes[n2].sub j = 0 while j < len(sub2): if suf[i + j] != sub2[j]: n3 = n2 n2 = len(self.nodes) self.nodes.append(Node(sub2[:j], [n3])) self.nodes[n3].sub = sub2[j:] self.nodes[n].ch[x2] = n2 break j = j + 1 i = i + j n = n2 def visualize(self): if len(self.nodes) == 0: print "<empty>" return def f(n, pre): children = self.nodes[n].ch if len(children) == 0: print "--", self.nodes[n].sub return print "+-", self.nodes[n].sub for c in children[:-1]: print pre, "+-", f(c, pre + " | ") print pre, "+-", f(children[-1], pre + " ") f(0, "") SuffixTree("banana$").visualize()
Maintain the same structure and functionality when rewriting this code in Python.
using System; using System.Collections.Generic; namespace SuffixTree { class Node { public string sub; public List<int> ch = new List<int>(); public Node() { sub = ""; } public Node(string sub, params int[] children) { this.sub = sub; ch.AddRange(children); } } class SuffixTree { readonly List<Node> nodes = new List<Node>(); public SuffixTree(string str) { nodes.Add(new Node()); for (int i = 0; i < str.Length; i++) { AddSuffix(str.Substring(i)); } } public void Visualize() { if (nodes.Count == 0) { Console.WriteLine("<empty>"); return; } void f(int n, string pre) { var children = nodes[n].ch; if (children.Count == 0) { Console.WriteLine("- {0}", nodes[n].sub); return; } Console.WriteLine("+ {0}", nodes[n].sub); var it = children.GetEnumerator(); if (it.MoveNext()) { do { var cit = it; if (!cit.MoveNext()) break; Console.Write("{0}+-", pre); f(it.Current, pre + "| "); } while (it.MoveNext()); } Console.Write("{0}+-", pre); f(children[children.Count-1], pre+" "); } f(0, ""); } private void AddSuffix(string suf) { int n = 0; int i = 0; while (i < suf.Length) { char b = suf[i]; int x2 = 0; int n2; while (true) { var children = nodes[n].ch; if (x2 == children.Count) { n2 = nodes.Count; nodes.Add(new Node(suf.Substring(i))); nodes[n].ch.Add(n2); return; } n2 = children[x2]; if (nodes[n2].sub[0] == b) { break; } x2++; } var sub2 = nodes[n2].sub; int j = 0; while (j < sub2.Length) { if (suf[i + j] != sub2[j]) { var n3 = n2; n2 = nodes.Count; nodes.Add(new Node(sub2.Substring(0, j), n3)); nodes[n3].sub = sub2.Substring(j); nodes[n].ch[x2] = n2; break; } j++; } i += j; n = n2; } } } class Program { static void Main() { new SuffixTree("banana$").Visualize(); } } }
class Node: def __init__(self, sub="", children=None): self.sub = sub self.ch = children or [] class SuffixTree: def __init__(self, str): self.nodes = [Node()] for i in range(len(str)): self.addSuffix(str[i:]) def addSuffix(self, suf): n = 0 i = 0 while i < len(suf): b = suf[i] x2 = 0 while True: children = self.nodes[n].ch if x2 == len(children): n2 = len(self.nodes) self.nodes.append(Node(suf[i:], [])) self.nodes[n].ch.append(n2) return n2 = children[x2] if self.nodes[n2].sub[0] == b: break x2 = x2 + 1 sub2 = self.nodes[n2].sub j = 0 while j < len(sub2): if suf[i + j] != sub2[j]: n3 = n2 n2 = len(self.nodes) self.nodes.append(Node(sub2[:j], [n3])) self.nodes[n3].sub = sub2[j:] self.nodes[n].ch[x2] = n2 break j = j + 1 i = i + j n = n2 def visualize(self): if len(self.nodes) == 0: print "<empty>" return def f(n, pre): children = self.nodes[n].ch if len(children) == 0: print "--", self.nodes[n].sub return print "+-", self.nodes[n].sub for c in children[:-1]: print pre, "+-", f(c, pre + " | ") print pre, "+-", f(children[-1], pre + " ") f(0, "") SuffixTree("banana$").visualize()
Write the same algorithm in Python as shown in this C# implementation.
using System; using System.Collections.Generic; namespace AssocArrays { class Program { static void Main(string[] args) { Dictionary<string,int> assocArray = new Dictionary<string,int>(); assocArray["Hello"] = 1; assocArray.Add("World", 2); assocArray["!"] = 3; foreach (KeyValuePair<string, int> kvp in assocArray) { Console.WriteLine(kvp.Key + " : " + kvp.Value); } foreach (string key in assocArray.Keys) { Console.WriteLine(key); } foreach (int val in assocArray.Values) { Console.WriteLine(val.ToString()); } } } }
myDict = { "hello": 13, "world": 31, "!" : 71 } for key, value in myDict.items(): print ("key = %s, value = %s" % (key, value)) for key in myDict: print ("key = %s" % key) for key in myDict.keys(): print ("key = %s" % key) for value in myDict.values(): print ("value = %s" % value)
Write the same code in Python as shown below in C#.
using System; using System.Globalization; struct LimitedInt : IComparable, IComparable<LimitedInt>, IConvertible, IEquatable<LimitedInt>, IFormattable { const int MIN_VALUE = 1; const int MAX_VALUE = 10; public static readonly LimitedInt MinValue = new LimitedInt(MIN_VALUE); public static readonly LimitedInt MaxValue = new LimitedInt(MAX_VALUE); static bool IsValidValue(int value) => value >= MIN_VALUE && value <= MAX_VALUE; readonly int _value; public int Value => this._value == 0 ? MIN_VALUE : this._value; public LimitedInt(int value) { if (!IsValidValue(value)) throw new ArgumentOutOfRangeException(nameof(value), value, $"Value must be between {MIN_VALUE} and {MAX_VALUE}."); this._value = value; } #region IComparable public int CompareTo(object obj) { if (obj is LimitedInt l) return this.Value.CompareTo(l); throw new ArgumentException("Object must be of type " + nameof(LimitedInt), nameof(obj)); } #endregion #region IComparable<LimitedInt> public int CompareTo(LimitedInt other) => this.Value.CompareTo(other.Value); #endregion #region IConvertible public TypeCode GetTypeCode() => this.Value.GetTypeCode(); bool IConvertible.ToBoolean(IFormatProvider provider) => ((IConvertible)this.Value).ToBoolean(provider); byte IConvertible.ToByte(IFormatProvider provider) => ((IConvertible)this.Value).ToByte(provider); char IConvertible.ToChar(IFormatProvider provider) => ((IConvertible)this.Value).ToChar(provider); DateTime IConvertible.ToDateTime(IFormatProvider provider) => ((IConvertible)this.Value).ToDateTime(provider); decimal IConvertible.ToDecimal(IFormatProvider provider) => ((IConvertible)this.Value).ToDecimal(provider); double IConvertible.ToDouble(IFormatProvider provider) => ((IConvertible)this.Value).ToDouble(provider); short IConvertible.ToInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToInt16(provider); int IConvertible.ToInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToInt32(provider); long IConvertible.ToInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToInt64(provider); sbyte IConvertible.ToSByte(IFormatProvider provider) => ((IConvertible)this.Value).ToSByte(provider); float IConvertible.ToSingle(IFormatProvider provider) => ((IConvertible)this.Value).ToSingle(provider); string IConvertible.ToString(IFormatProvider provider) => this.Value.ToString(provider); object IConvertible.ToType(Type conversionType, IFormatProvider provider) => ((IConvertible)this.Value).ToType(conversionType, provider); ushort IConvertible.ToUInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt16(provider); uint IConvertible.ToUInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt32(provider); ulong IConvertible.ToUInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt64(provider); #endregion #region IEquatable<LimitedInt> public bool Equals(LimitedInt other) => this == other; #endregion #region IFormattable public string ToString(string format, IFormatProvider formatProvider) => this.Value.ToString(format, formatProvider); #endregion #region operators public static bool operator ==(LimitedInt left, LimitedInt right) => left.Value == right.Value; public static bool operator !=(LimitedInt left, LimitedInt right) => left.Value != right.Value; public static bool operator <(LimitedInt left, LimitedInt right) => left.Value < right.Value; public static bool operator >(LimitedInt left, LimitedInt right) => left.Value > right.Value; public static bool operator <=(LimitedInt left, LimitedInt right) => left.Value <= right.Value; public static bool operator >=(LimitedInt left, LimitedInt right) => left.Value >= right.Value; public static LimitedInt operator ++(LimitedInt left) => (LimitedInt)(left.Value + 1); public static LimitedInt operator --(LimitedInt left) => (LimitedInt)(left.Value - 1); public static LimitedInt operator +(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value + right.Value); public static LimitedInt operator -(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value - right.Value); public static LimitedInt operator *(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value * right.Value); public static LimitedInt operator /(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value / right.Value); public static LimitedInt operator %(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value % right.Value); public static LimitedInt operator &(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value & right.Value); public static LimitedInt operator |(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value | right.Value); public static LimitedInt operator ^(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value ^ right.Value); public static LimitedInt operator ~(LimitedInt left) => (LimitedInt)~left.Value; public static LimitedInt operator >>(LimitedInt left, int right) => (LimitedInt)(left.Value >> right); public static LimitedInt operator <<(LimitedInt left, int right) => (LimitedInt)(left.Value << right); public static implicit operator int(LimitedInt value) => value.Value; public static explicit operator LimitedInt(int value) { if (!IsValidValue(value)) throw new OverflowException(); return new LimitedInt(value); } #endregion public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null) => this.Value.TryFormat(destination, out charsWritten, format, provider); public override int GetHashCode() => this.Value.GetHashCode(); public override bool Equals(object obj) => obj is LimitedInt l && this.Equals(l); public override string ToString() => this.Value.ToString(); #region static methods public static bool TryParse(ReadOnlySpan<char> s, out int result) => int.TryParse(s, out result); public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out int result) => int.TryParse(s, style, provider, out result); public static int Parse(string s, IFormatProvider provider) => int.Parse(s, provider); public static int Parse(string s, NumberStyles style, IFormatProvider provider) => int.Parse(s, style, provider); public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, ref int result) => int.TryParse(s, style, provider, out result); public static int Parse(string s) => int.Parse(s); public static int Parse(string s, NumberStyles style) => int.Parse(s, style); public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) => int.Parse(s, style, provider); public static bool TryParse(string s, ref int result) => int.TryParse(s, out result); #endregion }
>>> class num(int): def __init__(self, b): if 1 <= b <= 10: return int.__init__(self+0) else: raise ValueError,"Value %s should be >=0 and <= 10" % b >>> x = num(3) >>> x = num(11) Traceback (most recent call last): File "<pyshell x = num(11) File "<pyshell raise ValueError,"Value %s should be >=0 and <= 10" % b ValueError: Value 11 should be >=0 and <= 10 >>> x 3 >>> type(x) <class '__main__.num'> >>>
Convert this C# snippet to Python and keep its semantics consistent.
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)}; private (int dx, int dy)[] moves; public static void Main() { var knightSolver = new Solver(knightMoves); Print(knightSolver.Solve(true, ".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000..")); Print(knightSolver.Solve(true, ".....0.0.....", ".....0.0.....", "....00000....", ".....000.....", "..0..0.0..0..", "00000...00000", "..00.....00..", "00000...00000", "..0..0.0..0..", ".....000.....", "....00000....", ".....0.0.....", ".....0.0....." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!") find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
Port the provided C# code into Python while preserving the original functionality.
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)}; private (int dx, int dy)[] moves; public static void Main() { var knightSolver = new Solver(knightMoves); Print(knightSolver.Solve(true, ".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000..")); Print(knightSolver.Solve(true, ".....0.0.....", ".....0.0.....", "....00000....", ".....000.....", "..0..0.0..0..", "00000...00000", "..00.....00..", "00000...00000", "..0..0.0..0..", ".....000.....", "....00000....", ".....0.0.....", ".....0.0....." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ] def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1 for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0 return 0 def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1 if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!") find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)
Generate a Python translation of this C# snippet without changing its computational steps.
using System; using System.Collections.Generic; using System.Linq; namespace HashJoin { public class AgeName { public AgeName(byte age, string name) { Age = age; Name = name; } public byte Age { get; private set; } public string Name { get; private set; } } public class NameNemesis { public NameNemesis(string name, string nemesis) { Name = name; Nemesis = nemesis; } public string Name { get; private set; } public string Nemesis { get; private set; } } public class DataContext { public DataContext() { AgeName = new List<AgeName>(); NameNemesis = new List<NameNemesis>(); } public List<AgeName> AgeName { get; set; } public List<NameNemesis> NameNemesis { get; set; } } public class AgeNameNemesis { public AgeNameNemesis(byte age, string name, string nemesis) { Age = age; Name = name; Nemesis = nemesis; } public byte Age { get; private set; } public string Name { get; private set; } public string Nemesis { get; private set; } } class Program { public static void Main() { var data = GetData(); var result = ExecuteHashJoin(data); WriteResultToConsole(result); } private static void WriteResultToConsole(List<AgeNameNemesis> result) { result.ForEach(ageNameNemesis => Console.WriteLine("Age: {0}, Name: {1}, Nemesis: {2}", ageNameNemesis.Age, ageNameNemesis.Name, ageNameNemesis.Nemesis)); } private static List<AgeNameNemesis> ExecuteHashJoin(DataContext data) { return (data.AgeName.Join(data.NameNemesis, ageName => ageName.Name, nameNemesis => nameNemesis.Name, (ageName, nameNemesis) => new AgeNameNemesis(ageName.Age, ageName.Name, nameNemesis.Nemesis))) .ToList(); } private static DataContext GetData() { var context = new DataContext(); context.AgeName.AddRange(new [] { new AgeName(27, "Jonah"), new AgeName(18, "Alan"), new AgeName(28, "Glory"), new AgeName(18, "Popeye"), new AgeName(28, "Alan") }); context.NameNemesis.AddRange(new[] { new NameNemesis("Jonah", "Whales"), new NameNemesis("Jonah", "Spiders"), new NameNemesis("Alan", "Ghosts"), new NameNemesis("Alan", "Zombies"), new NameNemesis("Glory", "Buffy") }); return context; } } }
from collections import defaultdict def hashJoin(table1, index1, table2, index2): h = defaultdict(list) for s in table1: h[s[index1]].append(s) return [(s, r) for r in table2 for s in h[r[index2]]] table1 = [(27, "Jonah"), (18, "Alan"), (28, "Glory"), (18, "Popeye"), (28, "Alan")] table2 = [("Jonah", "Whales"), ("Jonah", "Spiders"), ("Alan", "Ghosts"), ("Alan", "Zombies"), ("Glory", "Buffy")] for row in hashJoin(table1, 1, table2, 0): print(row)
Convert this C# snippet to Python and keep its semantics consistent.
using System; using static System.Console; using System.Collections; using System.Linq; using System.Collections.Generic; class Program { static void Main(string[] args) { int lmt = 1000, amt, c = 0, sr = (int)Math.Sqrt(lmt), lm2; var res = new List<int>(); var pr = PG.Primes(lmt / 3 + 5).ToArray(); lm2 = pr.OrderBy(i => Math.Abs(sr - i)).First(); lm2 = Array.IndexOf(pr, lm2); for (var p = 0; p < lm2; p++) { amt = 0; for (var q = p + 1; amt < lmt; q++) res.Add(amt = pr[p] * pr[q]); } res.Sort(); foreach(var item in res.TakeWhile(x => x < lmt)) Write("{0,4} {1}", item, ++c % 20 == 0 ? "\n" : ""); Write("\n\nCounted {0} odd squarefree semiprimes under {1}", c, lmt); } } class PG { public static IEnumerable<int> Primes(int lim) { var flags = new bool[lim + 1]; int j = 3; for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8) if (!flags[j]) { yield return j; for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; } for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': for p in range(3, 999): if not isPrime(p): continue for q in range(p+1, 1000//p): if not isPrime(q): continue print(p*q, end = " ");
Can you help me rewrite this code in Python instead of C#, keeping it the same logically?
using System; using static System.Console; using System.Collections; using System.Linq; using System.Collections.Generic; class Program { static void Main(string[] args) { int lmt = 1000, amt, c = 0, sr = (int)Math.Sqrt(lmt), lm2; var res = new List<int>(); var pr = PG.Primes(lmt / 3 + 5).ToArray(); lm2 = pr.OrderBy(i => Math.Abs(sr - i)).First(); lm2 = Array.IndexOf(pr, lm2); for (var p = 0; p < lm2; p++) { amt = 0; for (var q = p + 1; amt < lmt; q++) res.Add(amt = pr[p] * pr[q]); } res.Sort(); foreach(var item in res.TakeWhile(x => x < lmt)) Write("{0,4} {1}", item, ++c % 20 == 0 ? "\n" : ""); Write("\n\nCounted {0} odd squarefree semiprimes under {1}", c, lmt); } } class PG { public static IEnumerable<int> Primes(int lim) { var flags = new bool[lim + 1]; int j = 3; for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8) if (!flags[j]) { yield return j; for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; } for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True if __name__ == '__main__': for p in range(3, 999): if not isPrime(p): continue for q in range(p+1, 1000//p): if not isPrime(q): continue print(p*q, end = " ");
Write a version of this C# function in Python with identical behavior.
using System; using System.Collections.Generic; using System.Linq; namespace SyntheticDivision { class Program { static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor) { List<int> output = dividend.ToList(); int normalizer = divisor[0]; for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++) { output[i] /= normalizer; int coef = output[i]; if (coef != 0) { for (int j = 1; j < divisor.Count(); j++) output[i + j] += -divisor[j] * coef; } } int separator = output.Count() - (divisor.Count() - 1); return ( output.GetRange(0, separator), output.GetRange(separator, output.Count() - separator) ); } static void Main(string[] args) { List<int> N = new List<int>{ 1, -12, 0, -42 }; List<int> D = new List<int> { 1, -3 }; var (quotient, remainder) = extendedSyntheticDivision(N, D); Console.WriteLine("[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]" , string.Join(",", N), string.Join(",", D), string.Join(",", quotient), string.Join(",", remainder) ); } } }
from __future__ import print_function from __future__ import division def extended_synthetic_division(dividend, divisor): out = list(dividend) normalizer = divisor[0] for i in xrange(len(dividend)-(len(divisor)-1)): out[i] /= normalizer coef = out[i] if coef != 0: for j in xrange(1, len(divisor)): out[i + j] += -divisor[j] * coef separator = -(len(divisor)-1) return out[:separator], out[separator:] if __name__ == '__main__': print("POLYNOMIAL SYNTHETIC DIVISION") N = [1, -12, 0, -42] D = [1, -3] print(" %s / %s =" % (N,D), " %s remainder %s" % extended_synthetic_division(N, D))
Produce a functionally identical Python code for the snippet given in C#.
using System; using System.Collections.Generic; using System.Linq; namespace SyntheticDivision { class Program { static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor) { List<int> output = dividend.ToList(); int normalizer = divisor[0]; for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++) { output[i] /= normalizer; int coef = output[i]; if (coef != 0) { for (int j = 1; j < divisor.Count(); j++) output[i + j] += -divisor[j] * coef; } } int separator = output.Count() - (divisor.Count() - 1); return ( output.GetRange(0, separator), output.GetRange(separator, output.Count() - separator) ); } static void Main(string[] args) { List<int> N = new List<int>{ 1, -12, 0, -42 }; List<int> D = new List<int> { 1, -3 }; var (quotient, remainder) = extendedSyntheticDivision(N, D); Console.WriteLine("[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]" , string.Join(",", N), string.Join(",", D), string.Join(",", quotient), string.Join(",", remainder) ); } } }
from __future__ import print_function from __future__ import division def extended_synthetic_division(dividend, divisor): out = list(dividend) normalizer = divisor[0] for i in xrange(len(dividend)-(len(divisor)-1)): out[i] /= normalizer coef = out[i] if coef != 0: for j in xrange(1, len(divisor)): out[i + j] += -divisor[j] * coef separator = -(len(divisor)-1) return out[:separator], out[separator:] if __name__ == '__main__': print("POLYNOMIAL SYNTHETIC DIVISION") N = [1, -12, 0, -42] D = [1, -3] print(" %s / %s =" % (N,D), " %s remainder %s" % extended_synthetic_division(N, D))
Please provide an equivalent version of this C# code in Python.
using System; using System.Collections.Generic; using System.Linq; namespace SyntheticDivision { class Program { static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor) { List<int> output = dividend.ToList(); int normalizer = divisor[0]; for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++) { output[i] /= normalizer; int coef = output[i]; if (coef != 0) { for (int j = 1; j < divisor.Count(); j++) output[i + j] += -divisor[j] * coef; } } int separator = output.Count() - (divisor.Count() - 1); return ( output.GetRange(0, separator), output.GetRange(separator, output.Count() - separator) ); } static void Main(string[] args) { List<int> N = new List<int>{ 1, -12, 0, -42 }; List<int> D = new List<int> { 1, -3 }; var (quotient, remainder) = extendedSyntheticDivision(N, D); Console.WriteLine("[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]" , string.Join(",", N), string.Join(",", D), string.Join(",", quotient), string.Join(",", remainder) ); } } }
from __future__ import print_function from __future__ import division def extended_synthetic_division(dividend, divisor): out = list(dividend) normalizer = divisor[0] for i in xrange(len(dividend)-(len(divisor)-1)): out[i] /= normalizer coef = out[i] if coef != 0: for j in xrange(1, len(divisor)): out[i + j] += -divisor[j] * coef separator = -(len(divisor)-1) return out[:separator], out[separator:] if __name__ == '__main__': print("POLYNOMIAL SYNTHETIC DIVISION") N = [1, -12, 0, -42] D = [1, -3] print(" %s / %s =" % (N,D), " %s remainder %s" % extended_synthetic_division(N, D))
Ensure the translated Python code behaves exactly like the original C# snippet.
using System; using System.Dynamic; class Example : DynamicObject { public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { result = null; Console.WriteLine("This is {0}.", binder.Name); return true; } } class Program { static void Main(string[] args) { dynamic ex = new Example(); ex.Foo(); ex.Bar(); } }
class Example(object): def foo(self): print("this is foo") def bar(self): print("this is bar") def __getattr__(self, name): def method(*args): print("tried to handle unknown method " + name) if args: print("it had arguments: " + str(args)) return method example = Example() example.foo() example.bar() example.grill() example.ding("dong")
Transform the following C# implementation into Python, maintaining the same output and logic.
using System; using System.Collections.Generic; using System.Linq; namespace LatinSquares { using matrix = List<List<int>>; class Program { static void Swap<T>(ref T a, ref T b) { var t = a; a = b; b = t; } static matrix DList(int n, int start) { start--; var a = Enumerable.Range(0, n).ToArray(); a[start] = a[0]; a[0] = start; Array.Sort(a, 1, a.Length - 1); var first = a[1]; matrix r = new matrix(); void recurse(int last) { if (last == first) { for (int j = 1; j < a.Length; j++) { var v = a[j]; if (j == v) { return; } } var b = a.Select(v => v + 1).ToArray(); r.Add(b.ToList()); return; } for (int i = last; i >= 1; i--) { Swap(ref a[i], ref a[last]); recurse(last - 1); Swap(ref a[i], ref a[last]); } } recurse(n - 1); return r; } static ulong ReducedLatinSquares(int n, bool echo) { if (n <= 0) { if (echo) { Console.WriteLine("[]\n"); } return 0; } else if (n == 1) { if (echo) { Console.WriteLine("[1]\n"); } return 1; } matrix rlatin = new matrix(); for (int i = 0; i < n; i++) { rlatin.Add(new List<int>()); for (int j = 0; j < n; j++) { rlatin[i].Add(0); } } for (int j = 0; j < n; j++) { rlatin[0][j] = j + 1; } ulong count = 0; void recurse(int i) { var rows = DList(n, i); for (int r = 0; r < rows.Count; r++) { rlatin[i - 1] = rows[r]; for (int k = 0; k < i - 1; k++) { for (int j = 1; j < n; j++) { if (rlatin[k][j] == rlatin[i - 1][j]) { if (r < rows.Count - 1) { goto outer; } if (i > 2) { return; } } } } if (i < n) { recurse(i + 1); } else { count++; if (echo) { PrintSquare(rlatin, n); } } outer: { } } } recurse(2); return count; } static void PrintSquare(matrix latin, int n) { foreach (var row in latin) { var it = row.GetEnumerator(); Console.Write("["); if (it.MoveNext()) { Console.Write(it.Current); } while (it.MoveNext()) { Console.Write(", {0}", it.Current); } Console.WriteLine("]"); } Console.WriteLine(); } static ulong Factorial(ulong n) { if (n <= 0) { return 1; } ulong prod = 1; for (ulong i = 2; i < n + 1; i++) { prod *= i; } return prod; } static void Main() { Console.WriteLine("The four reduced latin squares of order 4 are:\n"); ReducedLatinSquares(4, true); Console.WriteLine("The size of the set of reduced latin squares for the following orders"); Console.WriteLine("and hence the total number of latin squares of these orders are:\n"); for (int n = 1; n < 7; n++) { ulong nu = (ulong)n; var size = ReducedLatinSquares(n, false); var f = Factorial(nu - 1); f *= f * nu * size; Console.WriteLine("Order {0}: Size {1} x {2}! x {3}! => Total {4}", n, size, n, n - 1, f); } } } }
def dList(n, start): start -= 1 a = range(n) a[start] = a[0] a[0] = start a[1:] = sorted(a[1:]) first = a[1] r = [] def recurse(last): if (last == first): for j,v in enumerate(a[1:]): if j + 1 == v: return b = [x + 1 for x in a] r.append(b) return for i in xrange(last, 0, -1): a[i], a[last] = a[last], a[i] recurse(last - 1) a[i], a[last] = a[last], a[i] recurse(n - 1) return r def printSquare(latin,n): for row in latin: print row print def reducedLatinSquares(n,echo): if n <= 0: if echo: print [] return 0 elif n == 1: if echo: print [1] return 1 rlatin = [None] * n for i in xrange(n): rlatin[i] = [None] * n for j in xrange(0, n): rlatin[0][j] = j + 1 class OuterScope: count = 0 def recurse(i): rows = dList(n, i) for r in xrange(len(rows)): rlatin[i - 1] = rows[r] justContinue = False k = 0 while not justContinue and k < i - 1: for j in xrange(1, n): if rlatin[k][j] == rlatin[i - 1][j]: if r < len(rows) - 1: justContinue = True break if i > 2: return k += 1 if not justContinue: if i < n: recurse(i + 1) else: OuterScope.count += 1 if echo: printSquare(rlatin, n) recurse(2) return OuterScope.count def factorial(n): if n == 0: return 1 prod = 1 for i in xrange(2, n + 1): prod *= i return prod print "The four reduced latin squares of order 4 are:\n" reducedLatinSquares(4,True) print "The size of the set of reduced latin squares for the following orders" print "and hence the total number of latin squares of these orders are:\n" for n in xrange(1, 7): size = reducedLatinSquares(n, False) f = factorial(n - 1) f *= f * n * size print "Order %d: Size %-4d x %d! x %d! => Total %d" % (n, size, n, n - 1, f)
Port the following code from C# to Python with equivalent syntax and logic.
class Segment { public Segment(PointF p1, PointF p2) { P1 = p1; P2 = p2; } public readonly PointF P1; public readonly PointF P2; public float Length() { return (float)Math.Sqrt(LengthSquared()); } public float LengthSquared() { return (P1.X - P2.X) * (P1.X - P2.X) + (P1.Y - P2.Y) * (P1.Y - P2.Y); } }
from random import randint, randrange from operator import itemgetter, attrgetter infinity = float('inf') def bruteForceClosestPair(point): numPoints = len(point) if numPoints < 2: return infinity, (None, None) return min( ((abs(point[i] - point[j]), (point[i], point[j])) for i in range(numPoints-1) for j in range(i+1,numPoints)), key=itemgetter(0)) def closestPair(point): xP = sorted(point, key= attrgetter('real')) yP = sorted(point, key= attrgetter('imag')) return _closestPair(xP, yP) def _closestPair(xP, yP): numPoints = len(xP) if numPoints <= 3: return bruteForceClosestPair(xP) Pl = xP[:numPoints/2] Pr = xP[numPoints/2:] Yl, Yr = [], [] xDivider = Pl[-1].real for p in yP: if p.real <= xDivider: Yl.append(p) else: Yr.append(p) dl, pairl = _closestPair(Pl, Yl) dr, pairr = _closestPair(Pr, Yr) dm, pairm = (dl, pairl) if dl < dr else (dr, pairr) closeY = [p for p in yP if abs(p.real - xDivider) < dm] numCloseY = len(closeY) if numCloseY > 1: closestY = min( ((abs(closeY[i] - closeY[j]), (closeY[i], closeY[j])) for i in range(numCloseY-1) for j in range(i+1,min(i+8, numCloseY))), key=itemgetter(0)) return (dm, pairm) if dm <= closestY[0] else closestY else: return dm, pairm def times(): import timeit functions = [bruteForceClosestPair, closestPair] for f in functions: print 'Time for', f.__name__, timeit.Timer( '%s(pointList)' % f.__name__, 'from closestpair import %s, pointList' % f.__name__).timeit(number=1) pointList = [randint(0,1000)+1j*randint(0,1000) for i in range(2000)] if __name__ == '__main__': pointList = [(5+9j), (9+3j), (2+0j), (8+4j), (7+4j), (9+10j), (1+9j), (8+2j), 10j, (9+6j)] print pointList print ' bruteForceClosestPair:', bruteForceClosestPair(pointList) print ' closestPair:', closestPair(pointList) for i in range(10): pointList = [randrange(11)+1j*randrange(11) for i in range(10)] print '\n', pointList print ' bruteForceClosestPair:', bruteForceClosestPair(pointList) print ' closestPair:', closestPair(pointList) print '\n' times() times() times()
Rewrite this program in Python while keeping its functionality equivalent to the C# version.
int i = 5; int* p = &i;
var num = 12 var pointer = ptr(num) print pointer @unsafe pointer.addr = 0xFFFE
Write the same algorithm in Python as shown in this C# implementation.
class Animal { } class Dog : Animal { } class Lab : Dog { } class Collie : Dog { } class Cat : Animal { }
class Animal: pass class Dog(Animal): pass class Cat(Animal): pass class Lab(Dog): pass class Collie(Dog): pass
Produce a language-to-language conversion: from C# to Python, same semantics.
System.Collections.HashTable map = new System.Collections.HashTable(); map["key1"] = "foo";
hash = dict() hash = dict(red="FF0000", green="00FF00", blue="0000FF") hash = { 'key1':1, 'key2':2, } value = hash[key]
Write the same code in Python as shown below in C#.
public MainWindow() { InitializeComponent(); RenderOptions.SetBitmapScalingMode(imgMain, BitmapScalingMode.HighQuality); imgMain.Source = new WriteableBitmap(480, 480, 96, 96, PixelFormats.Bgr32, null); DrawHue(100); } void DrawHue(int saturation) { var bmp = (WriteableBitmap)imgMain.Source; int centerX = (int)bmp.Width / 2; int centerY = (int)bmp.Height / 2; int radius = Math.Min(centerX, centerY); int radius2 = radius - 40; bmp.Lock(); unsafe{ var buf = bmp.BackBuffer; IntPtr pixLineStart; for(int y=0; y < bmp.Height; y++){ pixLineStart = buf + bmp.BackBufferStride * y; double dy = (y - centerY); for(int x=0; x < bmp.Width; x++){ double dx = (x - centerX); double dist = Math.Sqrt(dx * dx + dy * dy); if (radius2 <= dist && dist <= radius) { double theta = Math.Atan2(dy, dx); double hue = (theta + Math.PI) / (2.0 * Math.PI); *((int*)(pixLineStart + x * 4)) = HSB_to_RGB((int)(hue * 360), saturation, 100); } } } } bmp.AddDirtyRect(new Int32Rect(0, 0, 480, 480)); bmp.Unlock(); } static int HSB_to_RGB(int h, int s, int v) { var rgb = new int[3]; var baseColor = (h + 60) % 360 / 120; var shift = (h + 60) % 360 - (120 * baseColor + 60 ); var secondaryColor = (baseColor + (shift >= 0 ? 1 : -1) + 3) % 3; rgb[baseColor] = 255; rgb[secondaryColor] = (int) ((Math.Abs(shift) / 60.0f) * 255.0f); for (var i = 0; i < 3; i++) rgb[i] += (int) ((255 - rgb[i]) * ((100 - s) / 100.0f)); for (var i = 0; i < 3; i++) rgb[i] -= (int) (rgb[i] * (100-v) / 100.0f); return RGB2int(rgb[0], rgb[1], rgb[2]); } public static int RGB2int(int r, int g, int b) => r << 16 | g << 8 | b;
size(300, 300) background(0) radius = min(width, height) / 2.0 cx, cy = width / 2, width / 2 for x in range(width): for y in range(height): rx = x - cx ry = y - cy s = sqrt(rx ** 2 + ry ** 2) / radius if s <= 1.0: h = ((atan2(ry, rx) / PI) + 1.0) / 2.0 colorMode(HSB) c = color(int(h * 255), int(s * 255), 255) set(x, y, c)
Produce a language-to-language conversion: from C# to Python, same semantics.
using System; class Point { protected int x, y; public Point() : this(0) {} public Point(int x) : this(x,0) {} public Point(int x, int y) { this.x = x; this.y = y; } public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } public virtual void print() { System.Console.WriteLine("Point"); } } public class Circle : Point { private int r; public Circle(Point p) : this(p,0) { } public Circle(Point p, int r) : base(p) { this.r = r; } public Circle() : this(0) { } public Circle(int x) : this(x,0) { } public Circle(int x, int y) : this(x,y,0) { } public Circle(int x, int y, int r) : base(x,y) { this.r = r; } public int R { get { return r; } set { r = value; } } public override void print() { System.Console.WriteLine("Circle"); } public static void main(String args[]) { Point p = new Point(); Point c = new Circle(); p.print(); c.print(); } }
class Point(object): def __init__(self, x=0.0, y=0.0): self.x = x self.y = y def __repr__(self): return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y) class Circle(object): def __init__(self, center=None, radius=1.0): self.center = center or Point() self.radius = radius def __repr__(self): return '<Circle 0x%x x: %f y: %f radius: %f>' % ( id(self), self.center.x, self.center.y, self.radius)
Rewrite this program in Python while keeping its functionality equivalent to the C# version.
using System; class Point { protected int x, y; public Point() : this(0) {} public Point(int x) : this(x,0) {} public Point(int x, int y) { this.x = x; this.y = y; } public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } public virtual void print() { System.Console.WriteLine("Point"); } } public class Circle : Point { private int r; public Circle(Point p) : this(p,0) { } public Circle(Point p, int r) : base(p) { this.r = r; } public Circle() : this(0) { } public Circle(int x) : this(x,0) { } public Circle(int x, int y) : this(x,y,0) { } public Circle(int x, int y, int r) : base(x,y) { this.r = r; } public int R { get { return r; } set { r = value; } } public override void print() { System.Console.WriteLine("Circle"); } public static void main(String args[]) { Point p = new Point(); Point c = new Circle(); p.print(); c.print(); } }
class Point(object): def __init__(self, x=0.0, y=0.0): self.x = x self.y = y def __repr__(self): return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y) class Circle(object): def __init__(self, center=None, radius=1.0): self.center = center or Point() self.radius = radius def __repr__(self): return '<Circle 0x%x x: %f y: %f radius: %f>' % ( id(self), self.center.x, self.center.y, self.radius)
Convert the following code from C# to Python, ensuring the logic remains intact.
using System; using System.Collections.Generic; using System.Linq; using static System.Console; using UI = System.UInt64; using LST = System.Collections.Generic.List<System.Collections.Generic.List<sbyte>>; using Lst = System.Collections.Generic.List<sbyte>; using DT = System.DateTime; class Program { const sbyte MxD = 19; public struct term { public UI coeff; public sbyte a, b; public term(UI c, int a_, int b_) { coeff = c; a = (sbyte)a_; b = (sbyte)b_; } } static int[] digs; static List<UI> res; static sbyte count = 0; static DT st; static List<List<term>> tLst; static List<LST> lists; static Dictionary<int, LST> fml, dmd; static Lst dl, zl, el, ol, il; static bool odd; static int nd, nd2; static LST ixs; static int[] cnd, di; static LST dis; static UI Dif; static UI ToDif() { UI r = 0; for (int i = 0; i < digs.Length; i++) r = r * 10 + (uint)digs[i]; return r; } static UI ToSum() { UI r = 0; for (int i = digs.Length - 1; i >= 0; i--) r = r * 10 + (uint)digs[i]; return Dif + (r << 1); } static bool IsSquare(UI nmbr) { if ((0x202021202030213 & (1 << (int)(nmbr & 63))) != 0) { UI r = (UI)Math.Sqrt((double)nmbr); return r * r == nmbr; } return false; } static Lst Seq(sbyte from, int to, sbyte stp = 1) { Lst res = new Lst(); for (sbyte item = from; item <= to; item += stp) res.Add(item); return res; } static void Fnpr(int lev) { if (lev == dis.Count) { digs[ixs[0][0]] = fml[cnd[0]][di[0]][0]; digs[ixs[0][1]] = fml[cnd[0]][di[0]][1]; int le = di.Length, i = 1; if (odd) digs[nd >> 1] = di[--le]; foreach (sbyte d in di.Skip(1).Take(le - 1)) { digs[ixs[i][0]] = dmd[cnd[i]][d][0]; digs[ixs[i][1]] = dmd[cnd[i++]][d][1]; } if (!IsSquare(ToSum())) return; res.Add(ToDif()); WriteLine("{0,16:n0}{1,4} ({2:n0})", (DT.Now - st).TotalMilliseconds, ++count, res.Last()); } else foreach (var n in dis[lev]) { di[lev] = n; Fnpr(lev + 1); } } static void Fnmr (LST list, int lev) { if (lev == list.Count) { Dif = 0; sbyte i = 0; foreach (var t in tLst[nd2]) { if (cnd[i] < 0) Dif -= t.coeff * (UI)(-cnd[i++]); else Dif += t.coeff * (UI)cnd[i++]; } if (Dif <= 0 || !IsSquare(Dif)) return; dis = new LST { Seq(0, fml[cnd[0]].Count - 1) }; foreach (int ii in cnd.Skip(1)) dis.Add(Seq(0, dmd[ii].Count - 1)); if (odd) dis.Add(il); di = new int[dis.Count]; Fnpr(0); } else foreach(sbyte n in list[lev]) { cnd[lev] = n; Fnmr(list, lev + 1); } } static void init() { UI pow = 1; tLst = new List<List<term>>(); foreach (int r in Seq(2, MxD)) { List<term> terms = new List<term>(); pow *= 10; UI p1 = pow, p2 = 1; for (int i1 = 0, i2 = r - 1; i1 < i2; i1++, i2--) { terms.Add(new term(p1 - p2, i1, i2)); p1 /= 10; p2 *= 10; } tLst.Add(terms); } fml = new Dictionary<int, LST> { [0] = new LST { new Lst { 2, 2 }, new Lst { 8, 8 } }, [1] = new LST { new Lst { 6, 5 }, new Lst { 8, 7 } }, [4] = new LST { new Lst { 4, 0 } }, [6] = new LST { new Lst { 6, 0 }, new Lst { 8, 2 } } }; dmd = new Dictionary<int, LST>(); for (sbyte i = 0; i < 10; i++) for (sbyte j = 0, d = i; j < 10; j++, d--) { if (dmd.ContainsKey(d)) dmd[d].Add(new Lst { i, j }); else dmd[d] = new LST { new Lst { i, j } }; } dl = Seq(-9, 9); zl = Seq( 0, 0); el = Seq(-8, 8, 2); ol = Seq(-9, 9, 2); il = Seq( 0, 9); lists = new List<LST>(); foreach (sbyte f in fml.Keys) lists.Add(new LST { new Lst { f } }); } static void Main(string[] args) { init(); res = new List<UI>(); st = DT.Now; count = 0; WriteLine("{0,5}{1,12}{2,4}{3,14}", "digs", "elapsed(ms)", "R/N", "Unordered Rare Numbers"); for (nd = 2, nd2 = 0, odd = false; nd <= MxD; nd++, nd2++, odd = !odd) { digs = new int[nd]; if (nd == 4) { lists[0].Add(zl); lists[1].Add(ol); lists[2].Add(el); lists[3].Add(ol); } else if (tLst[nd2].Count > lists[0].Count) foreach (LST list in lists) list.Add(dl); ixs = new LST(); foreach (term t in tLst[nd2]) ixs.Add(new Lst { t.a, t.b }); foreach (LST list in lists) { cnd = new int[list.Count]; Fnmr(list, 0); } WriteLine(" {0,2} {1,10:n0}", nd, (DT.Now - st).TotalMilliseconds); } res.Sort(); WriteLine("\nThe {0} rare numbers with up to {1} digits are:", res.Count, MxD); count = 0; foreach (var rare in res) WriteLine("{0,2}:{1,27:n0}", ++count, rare); if (System.Diagnostics.Debugger.IsAttached) ReadKey(); } }
from math import floor, sqrt from datetime import datetime def main(): start = datetime.now() for i in xrange(1, 10 ** 11): if rare(i): print "found a rare:", i end = datetime.now() print "time elapsed:", end - start def is_square(n): s = floor(sqrt(n + 0.5)) return s * s == n def reverse(n): return int(str(n)[::-1]) def is_palindrome(n): return n == reverse(n) def rare(n): r = reverse(n) return ( not is_palindrome(n) and n > r and is_square(n+r) and is_square(n-r) ) if __name__ == '__main__': main()
Keep all operations the same but rewrite the snippet in Python.
using System; using System.Drawing; using System.Windows.Forms; class MineFieldModel { public int RemainingMinesCount{ get{ var count = 0; ForEachCell((i,j)=>{ if (Mines[i,j] && !Marked[i,j]) count++; }); return count; } } public bool[,] Mines{get; private set;} public bool[,] Opened{get;private set;} public bool[,] Marked{get; private set;} public int[,] Values{get;private set; } public int Width{ get{return Mines.GetLength(1);} } public int Height{ get{return Mines.GetLength(0);} } public MineFieldModel(bool[,] mines) { this.Mines = mines; this.Opened = new bool[Height, Width]; this.Marked = new bool[Height, Width]; this.Values = CalculateValues(); } private int[,] CalculateValues() { int[,] values = new int[Height, Width]; ForEachCell((i,j) =>{ var value = 0; ForEachNeighbor(i,j, (i1,j1)=>{ if (Mines[i1,j1]) value++; }); values[i,j] = value; }); return values; } public void ForEachCell(Action<int,int> action) { for (var i = 0; i < Height; i++) for (var j = 0; j < Width; j++) action(i,j); } public void ForEachNeighbor(int i, int j, Action<int,int> action) { for (var i1 = i-1; i1 <= i+1; i1++) for (var j1 = j-1; j1 <= j+1; j1++) if (InBounds(j1, i1) && !(i1==i && j1 ==j)) action(i1, j1); } private bool InBounds(int x, int y) { return y >= 0 && y < Height && x >=0 && x < Width; } public event Action Exploded = delegate{}; public event Action Win = delegate{}; public event Action Updated = delegate{}; public void OpenCell(int i, int j){ if(!Opened[i,j]){ if (Mines[i,j]) Exploded(); else{ OpenCellsStartingFrom(i,j); Updated(); CheckForVictory(); } } } void OpenCellsStartingFrom(int i, int j) { Opened[i,j] = true; ForEachNeighbor(i,j, (i1,j1)=>{ if (!Mines[i1,j1] && !Opened[i1,j1] && !Marked[i1,j1]) OpenCellsStartingFrom(i1, j1); }); } void CheckForVictory(){ int notMarked = 0; int wrongMarked = 0; ForEachCell((i,j)=>{ if (Mines[i,j] && !Marked[i,j]) notMarked++; if (!Mines[i,j] && Marked[i,j]) wrongMarked++; }); if (notMarked == 0 && wrongMarked == 0) Win(); } public void Mark(int i, int j){ if (!Opened[i,j]) Marked[i,j] = true; Updated(); CheckForVictory(); } } class MineFieldView: UserControl{ public const int CellSize = 40; MineFieldModel _model; public MineFieldModel Model{ get{ return _model; } set { _model = value; this.Size = new Size(_model.Width * CellSize+1, _model.Height * CellSize+2); } } public MineFieldView(){ this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer,true); this.Font = new Font(FontFamily.GenericSansSerif, 14, FontStyle.Bold); this.MouseUp += (o,e)=>{ Point cellCoords = GetCell(e.Location); if (Model != null) { if (e.Button == MouseButtons.Left) Model.OpenCell(cellCoords.Y, cellCoords.X); else if (e.Button == MouseButtons.Right) Model.Mark(cellCoords.Y, cellCoords.X); } }; } Point GetCell(Point coords) { var rgn = ClientRectangle; var x = (coords.X - rgn.X)/CellSize; var y = (coords.Y - rgn.Y)/CellSize; return new Point(x,y); } static readonly Brush MarkBrush = new SolidBrush(Color.Blue); static readonly Brush ValueBrush = new SolidBrush(Color.Black); static readonly Brush UnexploredBrush = new SolidBrush(SystemColors.Control); static readonly Brush OpenBrush = new SolidBrush(SystemColors.ControlDark); protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); var g = e.Graphics; if (Model != null) { Model.ForEachCell((i,j)=> { var bounds = new Rectangle(j * CellSize, i * CellSize, CellSize, CellSize); if (Model.Opened[i,j]) { g.FillRectangle(OpenBrush, bounds); if (Model.Values[i,j] > 0) { DrawStringInCenter(g, Model.Values[i,j].ToString(), ValueBrush, bounds); } } else { g.FillRectangle(UnexploredBrush, bounds); if (Model.Marked[i,j]) { DrawStringInCenter(g, "?", MarkBrush, bounds); } var outlineOffset = 1; var outline = new Rectangle(bounds.X+outlineOffset, bounds.Y+outlineOffset, bounds.Width-2*outlineOffset, bounds.Height-2*outlineOffset); g.DrawRectangle(Pens.Gray, outline); } g.DrawRectangle(Pens.Black, bounds); }); } } static readonly StringFormat FormatCenter = new StringFormat { LineAlignment = StringAlignment.Center, Alignment=StringAlignment.Center }; void DrawStringInCenter(Graphics g, string s, Brush brush, Rectangle bounds) { PointF center = new PointF(bounds.X + bounds.Width/2, bounds.Y + bounds.Height/2); g.DrawString(s, this.Font, brush, center, FormatCenter); } } class MineSweepForm: Form { MineFieldModel CreateField(int width, int height) { var field = new bool[height, width]; int mineCount = (int)(0.2 * height * width); var rnd = new Random(); while(mineCount > 0) { var x = rnd.Next(width); var y = rnd.Next(height); if (!field[y,x]) { field[y,x] = true; mineCount--; } } return new MineFieldModel(field); } public MineSweepForm() { var model = CreateField(6, 4); var counter = new Label{ }; counter.Text = model.RemainingMinesCount.ToString(); var view = new MineFieldView { Model = model, BorderStyle = BorderStyle.FixedSingle, }; var stackPanel = new FlowLayoutPanel { Dock = DockStyle.Fill, FlowDirection = FlowDirection.TopDown, Controls = {counter, view} }; this.Controls.Add(stackPanel); model.Updated += delegate{ view.Invalidate(); counter.Text = model.RemainingMinesCount.ToString(); }; model.Exploded += delegate { MessageBox.Show("FAIL!"); Close(); }; model.Win += delegate { MessageBox.Show("WIN!"); view.Enabled = false; }; } } class Program { static void Main() { Application.Run(new MineSweepForm()); } }
gridsize = (6, 4) minerange = (0.2, 0.6) try: raw_input except: raw_input = input import random from itertools import product from pprint import pprint as pp def gridandmines(gridsize=gridsize, minerange=minerange): xgrid, ygrid = gridsize minmines, maxmines = minerange minecount = xgrid * ygrid minecount = random.randint(int(minecount*minmines), int(minecount*maxmines)) grid = set(product(range(xgrid), range(ygrid))) mines = set(random.sample(grid, minecount)) show = {xy:'.' for xy in grid} return grid, mines, show def printgrid(show, gridsize=gridsize): xgrid, ygrid = gridsize grid = '\n'.join(''.join(show[(x,y)] for x in range(xgrid)) for y in range(ygrid)) print( grid ) def resign(showgrid, mines, markedmines): for m in mines: showgrid[m] = 'Y' if m in markedmines else 'N' def clear(x,y, showgrid, grid, mines, markedmines): if showgrid[(x, y)] == '.': xychar = str(sum(1 for xx in (x-1, x, x+1) for yy in (y-1, y, y+1) if (xx, yy) in mines )) if xychar == '0': xychar = '.' showgrid[(x,y)] = xychar for xx in (x-1, x, x+1): for yy in (y-1, y, y+1): xxyy = (xx, yy) if ( xxyy != (x, y) and xxyy in grid and xxyy not in mines | markedmines ): clear(xx, yy, showgrid, grid, mines, markedmines) if __name__ == '__main__': grid, mines, showgrid = gridandmines() markedmines = set([]) print( __doc__ ) print( '\nThere are %i true mines of fixed position in the grid\n' % len(mines) ) printgrid(showgrid) while markedmines != mines: inp = raw_input('m x y/c x y/p/r: ').strip().split() if inp: if inp[0] == 'm': x, y = [int(i)-1 for i in inp[1:3]] if (x,y) in markedmines: markedmines.remove((x,y)) showgrid[(x,y)] = '.' else: markedmines.add((x,y)) showgrid[(x,y)] = '?' elif inp[0] == 'p': printgrid(showgrid) elif inp[0] == 'c': x, y = [int(i)-1 for i in inp[1:3]] if (x,y) in mines | markedmines: print( '\nKLABOOM!! You hit a mine.\n' ) resign(showgrid, mines, markedmines) printgrid(showgrid) break clear(x,y, showgrid, grid, mines, markedmines) printgrid(showgrid) elif inp[0] == 'r': print( '\nResigning!\n' ) resign(showgrid, mines, markedmines) printgrid(showgrid) break print( '\nYou got %i and missed %i of the %i mines' % (len(mines.intersection(markedmines)), len(markedmines.difference(mines)), len(mines)) )
Write the same algorithm in Python as shown in this C# implementation.
using System.Linq; using System.Collections.Generic; using static System.Console; using static System.Math; class Program { static int ba; static string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; static string from10(int b) { string res = ""; int re; while (b > 0) { b = DivRem(b, ba, out re); res = chars[(byte)re] + res; } return res; } static int to10(string s) { int res = 0; foreach (char i in s) res = res * ba + chars.IndexOf(i); return res; } static bool nd(string s) { if (s.Length < 2) return true; char l = s[0]; for (int i = 1; i < s.Length; i++) if (chars.IndexOf(l) > chars.IndexOf(s[i])) return false; else l = s[i] ; return true; } static void Main(string[] args) { int c, lim = 1000; string s; foreach (var b in new List<int>{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }) { ba = b; c = 0; foreach (var a in PG.Primes(lim)) if (nd(s = from10(a))) Write("{0,4} {1}", s, ++c % 20 == 0 ? "\n" : ""); WriteLine("\nBase {0}: found {1} non-decreasing primes under {2:n0}\n", b, c, from10(lim)); } } } class PG { public static IEnumerable<int> Primes(int lim) { var flags = new bool[lim + 1]; int j; yield return 2; for (j = 4; j <= lim; j += 2) flags[j] = true; j = 3; for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8) if (!flags[j]) { yield return j; for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; } for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }
from operator import le from itertools import takewhile def monotonicDigits(base): def go(n): return monotonic(le)( showIntAtBase(base)(digitFromInt)(n)('') ) return go def monotonic(op): def go(xs): return all(map(op, xs, xs[1:])) return go def main(): xs = [ str(n) for n in takewhile( lambda n: 1000 > n, filter(monotonicDigits(10), primes()) ) ] w = len(xs[-1]) print(f'{len(xs)} matches for base 10:\n') print('\n'.join( ' '.join(row) for row in chunksOf(10)([ x.rjust(w, ' ') for x in xs ]) )) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go def digitFromInt(n): return '0123456789abcdefghijklmnopqrstuvwxyz'[n] if ( 0 <= n < 36 ) else '?' def primes(): n = 2 dct = {} while True: if n in dct: for p in dct[n]: dct.setdefault(n + p, []).append(p) del dct[n] else: yield n dct[n * n] = [n] n = 1 + n def showIntAtBase(base): def wrap(toChr, n, rs): def go(nd, r): n, d = nd r_ = toChr(d) + r return go(divmod(n, base), r_) if 0 != n else r_ return 'unsupported base' if 1 >= base else ( 'negative number' if 0 > n else ( go(divmod(n, base), rs)) ) return lambda toChr: lambda n: lambda rs: ( wrap(toChr, n, rs) ) if __name__ == '__main__': main()
Change the programming language of this snippet from C# to Python without modifying what it does.
using System.Linq; using System.Collections.Generic; using static System.Console; using static System.Math; class Program { static int ba; static string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; static string from10(int b) { string res = ""; int re; while (b > 0) { b = DivRem(b, ba, out re); res = chars[(byte)re] + res; } return res; } static int to10(string s) { int res = 0; foreach (char i in s) res = res * ba + chars.IndexOf(i); return res; } static bool nd(string s) { if (s.Length < 2) return true; char l = s[0]; for (int i = 1; i < s.Length; i++) if (chars.IndexOf(l) > chars.IndexOf(s[i])) return false; else l = s[i] ; return true; } static void Main(string[] args) { int c, lim = 1000; string s; foreach (var b in new List<int>{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 16, 17, 27, 31, 62 }) { ba = b; c = 0; foreach (var a in PG.Primes(lim)) if (nd(s = from10(a))) Write("{0,4} {1}", s, ++c % 20 == 0 ? "\n" : ""); WriteLine("\nBase {0}: found {1} non-decreasing primes under {2:n0}\n", b, c, from10(lim)); } } } class PG { public static IEnumerable<int> Primes(int lim) { var flags = new bool[lim + 1]; int j; yield return 2; for (j = 4; j <= lim; j += 2) flags[j] = true; j = 3; for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8) if (!flags[j]) { yield return j; for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; } for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }
from operator import le from itertools import takewhile def monotonicDigits(base): def go(n): return monotonic(le)( showIntAtBase(base)(digitFromInt)(n)('') ) return go def monotonic(op): def go(xs): return all(map(op, xs, xs[1:])) return go def main(): xs = [ str(n) for n in takewhile( lambda n: 1000 > n, filter(monotonicDigits(10), primes()) ) ] w = len(xs[-1]) print(f'{len(xs)} matches for base 10:\n') print('\n'.join( ' '.join(row) for row in chunksOf(10)([ x.rjust(w, ' ') for x in xs ]) )) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go def digitFromInt(n): return '0123456789abcdefghijklmnopqrstuvwxyz'[n] if ( 0 <= n < 36 ) else '?' def primes(): n = 2 dct = {} while True: if n in dct: for p in dct[n]: dct.setdefault(n + p, []).append(p) del dct[n] else: yield n dct[n * n] = [n] n = 1 + n def showIntAtBase(base): def wrap(toChr, n, rs): def go(nd, r): n, d = nd r_ = toChr(d) + r return go(divmod(n, base), r_) if 0 != n else r_ return 'unsupported base' if 1 >= base else ( 'negative number' if 0 > n else ( go(divmod(n, base), rs)) ) return lambda toChr: lambda n: lambda rs: ( wrap(toChr, n, rs) ) if __name__ == '__main__': main()
Convert this C# block to Python, preserving its control flow and logic.
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; public static class Reflection { public static void Main() { var t = new TestClass(); var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; foreach (var prop in GetPropertyValues(t, flags)) { Console.WriteLine(prop); } foreach (var field in GetFieldValues(t, flags)) { Console.WriteLine(field); } } public static IEnumerable<(string name, object value)> GetPropertyValues<T>(T obj, BindingFlags flags) => from p in typeof(T).GetProperties(flags) where p.GetIndexParameters().Length == 0 select (p.Name, p.GetValue(obj, null)); public static IEnumerable<(string name, object value)> GetFieldValues<T>(T obj, BindingFlags flags) => typeof(T).GetFields(flags).Select(f => (f.Name, f.GetValue(obj))); class TestClass { private int privateField = 7; public int PublicNumber { get; } = 4; private int PrivateNumber { get; } = 2; } }
class Parent(object): __priv = 'private' def __init__(self, name): self.name = name def __repr__(self): return '%s(%s)' % (type(self).__name__, self.name) def doNothing(self): pass import re class Child(Parent): __rePrivate = re.compile('^_(Child|Parent)__') __reBleh = re.compile('\Wbleh$') @property def reBleh(self): return self.__reBleh def __init__(self, name, *args): super(Child, self).__init__(name) self.args = args def __dir__(self): myDir = filter( lambda p: not self.__rePrivate.match(p), list(set( \ sum([dir(base) for base in type(self).__bases__], []) \ + type(self).__dict__.keys() \ + self.__dict__.keys() \ ))) return myDir + map( lambda p: p + '_bleh', filter( lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)), myDir)) def __getattr__(self, name): if name[-5:] == '_bleh': return str(getattr(self, name[:-5])) + ' bleh' if hasattr(super(Child, chld), '__getattr__'): return super(Child, self).__getattr__(name) raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name)) def __setattr__(self, name, value): if name[-5:] == '_bleh': if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))): setattr(self, name[:-5], self.reBleh.sub('', value)) elif hasattr(super(Child, self), '__setattr__'): super(Child, self).__setattr__(name, value) elif hasattr(self, '__dict__'): self.__dict__[name] = value def __repr__(self): return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()')) def doStuff(self): return (1+1.0/1e6) ** 1e6 par = Parent('par') par.parent = True dir(par) inspect.getmembers(par) chld = Child('chld', 0, 'I', 'two') chld.own = "chld's own" dir(chld) inspect.getmembers(chld)
Generate an equivalent Python version of this C# code.
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; public static class Reflection { public static void Main() { var t = new TestClass(); var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; foreach (var prop in GetPropertyValues(t, flags)) { Console.WriteLine(prop); } foreach (var field in GetFieldValues(t, flags)) { Console.WriteLine(field); } } public static IEnumerable<(string name, object value)> GetPropertyValues<T>(T obj, BindingFlags flags) => from p in typeof(T).GetProperties(flags) where p.GetIndexParameters().Length == 0 select (p.Name, p.GetValue(obj, null)); public static IEnumerable<(string name, object value)> GetFieldValues<T>(T obj, BindingFlags flags) => typeof(T).GetFields(flags).Select(f => (f.Name, f.GetValue(obj))); class TestClass { private int privateField = 7; public int PublicNumber { get; } = 4; private int PrivateNumber { get; } = 2; } }
class Parent(object): __priv = 'private' def __init__(self, name): self.name = name def __repr__(self): return '%s(%s)' % (type(self).__name__, self.name) def doNothing(self): pass import re class Child(Parent): __rePrivate = re.compile('^_(Child|Parent)__') __reBleh = re.compile('\Wbleh$') @property def reBleh(self): return self.__reBleh def __init__(self, name, *args): super(Child, self).__init__(name) self.args = args def __dir__(self): myDir = filter( lambda p: not self.__rePrivate.match(p), list(set( \ sum([dir(base) for base in type(self).__bases__], []) \ + type(self).__dict__.keys() \ + self.__dict__.keys() \ ))) return myDir + map( lambda p: p + '_bleh', filter( lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)), myDir)) def __getattr__(self, name): if name[-5:] == '_bleh': return str(getattr(self, name[:-5])) + ' bleh' if hasattr(super(Child, chld), '__getattr__'): return super(Child, self).__getattr__(name) raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name)) def __setattr__(self, name, value): if name[-5:] == '_bleh': if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))): setattr(self, name[:-5], self.reBleh.sub('', value)) elif hasattr(super(Child, self), '__setattr__'): super(Child, self).__setattr__(name, value) elif hasattr(self, '__dict__'): self.__dict__[name] = value def __repr__(self): return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()')) def doStuff(self): return (1+1.0/1e6) ** 1e6 par = Parent('par') par.parent = True dir(par) inspect.getmembers(par) chld = Child('chld', 0, 'I', 'two') chld.own = "chld's own" dir(chld) inspect.getmembers(chld)
Transform the following C# implementation into Python, maintaining the same output and logic.
using System; using System.Collections.Generic; using System.Linq; public static class MinimalSteps { public static void Main() { var (divisors, subtractors) = (new int[] { 2, 3 }, new [] { 1 }); var lookup = CreateLookup(2_000, divisors, subtractors); Console.WriteLine($"Divisors: [{divisors.Delimit()}], Subtractors: [{subtractors.Delimit()}]"); PrintRange(lookup, 10); PrintMaxMins(lookup); lookup = CreateLookup(20_000, divisors, subtractors); PrintMaxMins(lookup); Console.WriteLine(); subtractors = new [] { 2 }; lookup = CreateLookup(2_000, divisors, subtractors); Console.WriteLine($"Divisors: [{divisors.Delimit()}], Subtractors: [{subtractors.Delimit()}]"); PrintRange(lookup, 10); PrintMaxMins(lookup); lookup = CreateLookup(20_000, divisors, subtractors); PrintMaxMins(lookup); } private static void PrintRange((char op, int param, int steps)[] lookup, int limit) { for (int goal = 1; goal <= limit; goal++) { var x = lookup[goal]; if (x.param == 0) { Console.WriteLine($"{goal} cannot be reached with these numbers."); continue; } Console.Write($"{goal} takes {x.steps} {(x.steps == 1 ? "step" : "steps")}: "); for (int n = goal; n > 1; ) { Console.Write($"{n},{x.op}{x.param}=> "); n = x.op == '/' ? n / x.param : n - x.param; x = lookup[n]; } Console.WriteLine("1"); } } private static void PrintMaxMins((char op, int param, int steps)[] lookup) { var maxSteps = lookup.Max(x => x.steps); var items = lookup.Select((x, i) => (i, x)).Where(t => t.x.steps == maxSteps).ToList(); Console.WriteLine(items.Count == 1 ? $"There is one number below {lookup.Length-1} that requires {maxSteps} steps: {items[0].i}" : $"There are {items.Count} numbers below {lookup.Length-1} that require {maxSteps} steps: {items.Select(t => t.i).Delimit()}" ); } private static (char op, int param, int steps)[] CreateLookup(int goal, int[] divisors, int[] subtractors) { var lookup = new (char op, int param, int steps)[goal+1]; lookup[1] = ('/', 1, 0); for (int n = 1; n < lookup.Length; n++) { var ln = lookup[n]; if (ln.param == 0) continue; for (int d = 0; d < divisors.Length; d++) { int target = n * divisors[d]; if (target > goal) break; if (lookup[target].steps == 0 || lookup[target].steps > ln.steps) lookup[target] = ('/', divisors[d], ln.steps + 1); } for (int s = 0; s < subtractors.Length; s++) { int target = n + subtractors[s]; if (target > goal) break; if (lookup[target].steps == 0 || lookup[target].steps > ln.steps) lookup[target] = ('-', subtractors[s], ln.steps + 1); } } return lookup; } private static string Delimit<T>(this IEnumerable<T> source) => string.Join(", ", source); }
from functools import lru_cache DIVS = {2, 3} SUBS = {1} class Minrec(): "Recursive, memoised minimised steps to 1" def __init__(self, divs=DIVS, subs=SUBS): self.divs, self.subs = divs, subs @lru_cache(maxsize=None) def _minrec(self, n): "Recursive, memoised" if n == 1: return 0, ['=1'] possibles = {} for d in self.divs: if n % d == 0: possibles[f'/{d}=>{n // d:2}'] = self._minrec(n // d) for s in self.subs: if n > s: possibles[f'-{s}=>{n - s:2}'] = self._minrec(n - s) thiskind, (count, otherkinds) = min(possibles.items(), key=lambda x: x[1]) ret = 1 + count, [thiskind] + otherkinds return ret def __call__(self, n): "Recursive, memoised" ans = self._minrec(n)[1][:-1] return len(ans), ans if __name__ == '__main__': for DIVS, SUBS in [({2, 3}, {1}), ({2, 3}, {2})]: minrec = Minrec(DIVS, SUBS) print('\nMINIMUM STEPS TO 1: Recursive algorithm') print(' Possible divisors: ', DIVS) print(' Possible decrements:', SUBS) for n in range(1, 11): steps, how = minrec(n) print(f' minrec({n:2}) in {steps:2} by: ', ', '.join(how)) upto = 2000 print(f'\n Those numbers up to {upto} that take the maximum, "minimal steps down to 1":') stepn = sorted((minrec(n)[0], n) for n in range(upto, 0, -1)) mx = stepn[-1][0] ans = [x[1] for x in stepn if x[0] == mx] print(' Taking', mx, f'steps is/are the {len(ans)} numbers:', ', '.join(str(n) for n in sorted(ans))) print()
Generate a Python translation of this C# snippet without changing its computational steps.
using System; class ColumnAlignerProgram { delegate string Justification(string s, int width); static string[] AlignColumns(string[] lines, Justification justification) { const char Separator = '$'; string[][] table = new string[lines.Length][]; int columns = 0; for (int i = 0; i < lines.Length; i++) { string[] row = lines[i].TrimEnd(Separator).Split(Separator); if (columns < row.Length) columns = row.Length; table[i] = row; } string[][] formattedTable = new string[table.Length][]; for (int i = 0; i < formattedTable.Length; i++) { formattedTable[i] = new string[columns]; } for (int j = 0; j < columns; j++) { int columnWidth = 0; for (int i = 0; i < table.Length; i++) { if (j < table[i].Length && columnWidth < table[i][j].Length) columnWidth = table[i][j].Length; } for (int i = 0; i < formattedTable.Length; i++) { if (j < table[i].Length) formattedTable[i][j] = justification(table[i][j], columnWidth); else formattedTable[i][j] = new String(' ', columnWidth); } } string[] result = new string[formattedTable.Length]; for (int i = 0; i < result.Length; i++) { result[i] = String.Join(" ", formattedTable[i]); } return result; } static string JustifyLeft(string s, int width) { return s.PadRight(width); } static string JustifyRight(string s, int width) { return s.PadLeft(width); } static string JustifyCenter(string s, int width) { return s.PadLeft((width + s.Length) / 2).PadRight(width); } static void Main() { string[] input = { "Given$a$text$file$of$many$lines,$where$fields$within$a$line$", "are$delineated$by$a$single$'dollar'$character,$write$a$program", "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$", "column$are$separated$by$at$least$one$space.", "Further,$allow$for$each$word$in$a$column$to$be$either$left$", "justified,$right$justified,$or$center$justified$within$its$column.", }; foreach (string line in AlignColumns(input, JustifyCenter)) { Console.WriteLine(line); } } }
from itertools import zip_longest txt = parts = [line.rstrip("$").split("$") for line in txt.splitlines()] widths = [max(len(word) for word in col) for col in zip_longest(*parts, fillvalue='')] for justify in "<_Left ^_Center >_Right".split(): j, jtext = justify.split('_') print(f"{jtext} column-aligned output:\n") for line in parts: print(' '.join(f"{wrd:{j}{wdth}}" for wdth, wrd in zip(widths, line))) print("- " * 52)
Translate the given C# code snippet into Python without altering its behavior.
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Can you help me rewrite this code in Python instead of C#, keeping it the same logically?
using System; namespace RosettaUrlParse { class Program { static void ParseUrl(string url) { var u = new Uri(url); Console.WriteLine("URL: {0}", u.AbsoluteUri); Console.WriteLine("Scheme: {0}", u.Scheme); Console.WriteLine("Host: {0}", u.DnsSafeHost); Console.WriteLine("Port: {0}", u.Port); Console.WriteLine("Path: {0}", u.LocalPath); Console.WriteLine("Query: {0}", u.Query); Console.WriteLine("Fragment: {0}", u.Fragment); Console.WriteLine(); } static void Main(string[] args) { ParseUrl("foo: ParseUrl("urn:example:animal:ferret:nose"); ParseUrl("jdbc:mysql: ParseUrl("ftp: ParseUrl("http: ParseUrl("ldap: ParseUrl("mailto:John.Doe@example.com"); ParseUrl("news:comp.infosystems.www.servers.unix"); ParseUrl("tel:+1-816-555-1212"); ParseUrl("telnet: ParseUrl("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"); } } }
import urllib.parse as up url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1 print('url.scheme = ', url.scheme) print('url.netloc = ', url.netloc) print('url.hostname = ', url.hostname) print('url.port = ', url.port) print('url.path = ', url.path) print('url.params = ', url.params) print('url.query = ', url.query) print('url.fragment = ', url.fragment) print('url.username = ', url.username) print('url.password = ', url.password)
Preserve the algorithm and functionality while converting the code from C# to Python.
using System; class Program { static void Main(string[] args) { var sw = System.Diagnostics.Stopwatch.StartNew(); int a, b, c, i, n, s3, ab; var res = new int[65]; for (n = 1, i = 0; n < 1850; n++) { bool found = true; for (a = 1; a < n; a++) for (b = a + 1, ab = a * b + a + b; b < n; b++, ab += a + 1) { if (ab > n) break; for (c = b + 1, s3 = ab + (b + a) * b; c < n; c++, s3 += b + a) { if (s3 == n) found = false; if (s3 >= n) break; } } if (found) res[i++] = n; } sw.Stop(); Console.WriteLine("The 65 known Idoneal numbers:"); for (i = 0; i < res.Length; i++) Console.Write("{0,5}{1}", res[i], i % 13 == 12 ? "\n" : ""); Console.Write("Calculations took {0} ms", sw.Elapsed.TotalMilliseconds); } }
def is_idoneal(num): for a in range(1, num): for b in range(a + 1, num): if a * b + a + b > num: break for c in range(b + 1, num): sum3 = a * b + b * c + a * c if sum3 == num: return False if sum3 > num: break return True row = 0 for n in range(1, 2000): if is_idoneal(n): row += 1 print(f'{n:5}', end='\n' if row % 13 == 0 else '')
Write a version of this C# function in Python with identical behavior.
using System; using System.Collections.Generic; using System.Numerics; using System.Text; namespace Base58CheckEncoding { class Program { const string ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; static BigInteger ToBigInteger(string value, int @base) { const string HEX = "0123456789ABCDEF"; if (@base < 1 || @base > HEX.Length) { throw new ArgumentException("Base is out of range."); } BigInteger bi = BigInteger.Zero; foreach (char c in value) { char c2 = Char.ToUpper(c); int idx = HEX.IndexOf(c2); if (idx == -1 || idx >= @base) { throw new ArgumentOutOfRangeException("Illegal character encountered."); } bi = bi * @base + idx; } return bi; } static string ConvertToBase58(string hash, int @base = 16) { BigInteger x; if (@base == 16 && hash.Substring(0, 2) == "0x") { x = ToBigInteger(hash.Substring(2), @base); } else { x = ToBigInteger(hash, @base); } StringBuilder sb = new StringBuilder(); while (x > 0) { BigInteger r = x % 58; sb.Append(ALPHABET[(int)r]); x = x / 58; } char[] ca = sb.ToString().ToCharArray(); Array.Reverse(ca); return new string(ca); } static void Main(string[] args) { string s = "25420294593250030202636073700053352635053786165627414518"; string b = ConvertToBase58(s, 10); Console.WriteLine("{0} -> {1}", s, b); List<string> hashes = new List<string>() { "0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e", }; foreach (string hash in hashes) { string b58 = ConvertToBase58(hash); Console.WriteLine("{0,-56} -> {1}", hash, b58); } } } }
ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" def convertToBase58(num): sb = '' while (num > 0): r = num % 58 sb = sb + ALPHABET[r] num = num // 58; return sb[::-1] s = 25420294593250030202636073700053352635053786165627414518 b = convertToBase58(s) print("%-56d -> %s" % (s, b)) hash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e] for num in hash_arr: b = convertToBase58(num) print("0x%-54x -> %s" % (num, b))
Transform the following C# implementation into Python, maintaining the same output and logic.
using System; using System.Collections.Generic; using System.Numerics; using System.Text; namespace Base58CheckEncoding { class Program { const string ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; static BigInteger ToBigInteger(string value, int @base) { const string HEX = "0123456789ABCDEF"; if (@base < 1 || @base > HEX.Length) { throw new ArgumentException("Base is out of range."); } BigInteger bi = BigInteger.Zero; foreach (char c in value) { char c2 = Char.ToUpper(c); int idx = HEX.IndexOf(c2); if (idx == -1 || idx >= @base) { throw new ArgumentOutOfRangeException("Illegal character encountered."); } bi = bi * @base + idx; } return bi; } static string ConvertToBase58(string hash, int @base = 16) { BigInteger x; if (@base == 16 && hash.Substring(0, 2) == "0x") { x = ToBigInteger(hash.Substring(2), @base); } else { x = ToBigInteger(hash, @base); } StringBuilder sb = new StringBuilder(); while (x > 0) { BigInteger r = x % 58; sb.Append(ALPHABET[(int)r]); x = x / 58; } char[] ca = sb.ToString().ToCharArray(); Array.Reverse(ca); return new string(ca); } static void Main(string[] args) { string s = "25420294593250030202636073700053352635053786165627414518"; string b = ConvertToBase58(s, 10); Console.WriteLine("{0} -> {1}", s, b); List<string> hashes = new List<string>() { "0x61", "0x626262", "0x636363", "0x73696d706c792061206c6f6e6720737472696e67", "0x516b6fcd0f", "0xbf4f89001e670274dd", "0x572e4794", "0xecac89cad93923c02321", "0x10c8511e", }; foreach (string hash in hashes) { string b58 = ConvertToBase58(hash); Console.WriteLine("{0,-56} -> {1}", hash, b58); } } } }
ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" def convertToBase58(num): sb = '' while (num > 0): r = num % 58 sb = sb + ALPHABET[r] num = num // 58; return sb[::-1] s = 25420294593250030202636073700053352635053786165627414518 b = convertToBase58(s) print("%-56d -> %s" % (s, b)) hash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e] for num in hash_arr: b = convertToBase58(num) print("0x%-54x -> %s" % (num, b))
Produce a language-to-language conversion: from C# to Python, same semantics.
using System; using System.Dynamic; using System.Collections.Generic; public class Program { public static void Main() { string varname = Console.ReadLine(); dynamic expando = new ExpandoObject(); var map = expando as IDictionary<string, object>; map.Add(varname, "Hello world!"); Console.WriteLine(expando.foo); } }
>>> name = raw_input("Enter a variable name: ") Enter a variable name: X >>> globals()[name] = 42 >>> X 42
Translate the given C# code snippet into Python without altering its behavior.
using System; using System.IO; using System.Numerics; using System.Threading; using System.Diagnostics; using System.Globalization; namespace Fibonacci { class Program { private static readonly BigInteger[,] F = { { BigInteger.One, BigInteger.One }, { BigInteger.One, BigInteger.Zero } }; private static NumberFormatInfo nfi = new NumberFormatInfo { NumberGroupSeparator = "_" }; private static BigInteger[,] Multiply(in BigInteger[,] A, in BigInteger[,] B) { if (A.GetLength(1) != B.GetLength(0)) { throw new ArgumentException("Illegal matrix dimensions for multiplication."); } var C = new BigInteger[A.GetLength(0), B.GetLength(1)]; for (int i = 0; i < A.GetLength(0); ++i) { for (int j = 0; j < B.GetLength(1); ++j) { for (int k = 0; k < A.GetLength(1); ++k) { C[i, j] += A[i, k] * B[k, j]; } } } return C; } private static BigInteger[,] Power(in BigInteger[,] A, ulong n) { if (A.GetLength(1) != A.GetLength(0)) { throw new ArgumentException("Not a square matrix."); } var C = new BigInteger[A.GetLength(0), A.GetLength(1)]; for (int i = 0; i < A.GetLength(0); ++i) { C[i, i] = BigInteger.One; } if (0 == n) return C; var S = new BigInteger[A.GetLength(0), A.GetLength(1)]; for (int i = 0; i < A.GetLength(0); ++i) { for (int j = 0; j < A.GetLength(1); ++j) { S[i, j] = A[i, j]; } } while (0 < n) { if (1 == n % 2) C = Multiply(C, S); S = Multiply(S,S); n /= 2; } return C; } public static BigInteger Fib(in ulong n) { var C = Power(F, n); return C[0, 1]; } public static void Task(in ulong p) { var ans = Fib(p).ToString(); var sp = p.ToString("N0", nfi); if (ans.Length <= 40) { Console.WriteLine("Fibonacci({0}) = {1}", sp, ans); } else { Console.WriteLine("Fibonacci({0}) = {1} ... {2}", sp, ans[0..19], ans[^20..]); } } public static void Main() { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); for (ulong p = 10; p <= 10_000_000; p *= 10) { Task(p); } stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine("Took " + elapsedTime); } } }
class Head(): def __init__(self, lo, hi=None, shift=0): if hi is None: hi = lo d = hi - lo ds, ls, hs = str(d), str(lo), str(hi) if d and len(ls) > len(ds): assert(len(ls) - len(ds) + 1 > 21) lo = int(str(lo)[:len(ls) - len(ds) + 1]) hi = int(str(hi)[:len(hs) - len(ds) + 1]) + 1 shift += len(ds) - 1 elif len(ls) > 100: lo = int(str(ls)[:100]) hi = lo + 1 shift = len(ls) - 100 self.lo, self.hi, self.shift = lo, hi, shift def __mul__(self, other): lo = self.lo*other.lo hi = self.hi*other.hi shift = self.shift + other.shift return Head(lo, hi, shift) def __add__(self, other): if self.shift < other.shift: return other + self sh = self.shift - other.shift if sh >= len(str(other.hi)): return Head(self.lo, self.hi, self.shift) ls = str(other.lo) hs = str(other.hi) lo = self.lo + int(ls[:len(ls)-sh]) hi = self.hi + int(hs[:len(hs)-sh]) return Head(lo, hi, self.shift) def __repr__(self): return str(self.hi)[:20] class Tail(): def __init__(self, v): self.v = int(f'{v:020d}'[-20:]) def __add__(self, other): return Tail(self.v + other.v) def __mul__(self, other): return Tail(self.v*other.v) def __repr__(self): return f'{self.v:020d}'[-20:] def mul(a, b): return a[0]*b[0] + a[1]*b[1], a[0]*b[1] + a[1]*b[2], a[1]*b[1] + a[2]*b[2] def fibo(n, cls): n -= 1 zero, one = cls(0), cls(1) m = (one, one, zero) e = (one, zero, one) while n: if n&1: e = mul(m, e) m = mul(m, m) n >>= 1 return f'{e[0]}' for i in range(2, 10): n = 10**i print(f'10^{i} :', fibo(n, Head), '...', fibo(n, Tail)) for i in range(3, 8): n = 2**i s = f'2^{n}' print(f'{s:5s}:', fibo(2**n, Head), '...', fibo(2**n, Tail))
Translate the given C# code snippet into Python without altering its behavior.
using System; using System.IO; using System.Numerics; using System.Threading; using System.Diagnostics; using System.Globalization; namespace Fibonacci { class Program { private static readonly BigInteger[,] F = { { BigInteger.One, BigInteger.One }, { BigInteger.One, BigInteger.Zero } }; private static NumberFormatInfo nfi = new NumberFormatInfo { NumberGroupSeparator = "_" }; private static BigInteger[,] Multiply(in BigInteger[,] A, in BigInteger[,] B) { if (A.GetLength(1) != B.GetLength(0)) { throw new ArgumentException("Illegal matrix dimensions for multiplication."); } var C = new BigInteger[A.GetLength(0), B.GetLength(1)]; for (int i = 0; i < A.GetLength(0); ++i) { for (int j = 0; j < B.GetLength(1); ++j) { for (int k = 0; k < A.GetLength(1); ++k) { C[i, j] += A[i, k] * B[k, j]; } } } return C; } private static BigInteger[,] Power(in BigInteger[,] A, ulong n) { if (A.GetLength(1) != A.GetLength(0)) { throw new ArgumentException("Not a square matrix."); } var C = new BigInteger[A.GetLength(0), A.GetLength(1)]; for (int i = 0; i < A.GetLength(0); ++i) { C[i, i] = BigInteger.One; } if (0 == n) return C; var S = new BigInteger[A.GetLength(0), A.GetLength(1)]; for (int i = 0; i < A.GetLength(0); ++i) { for (int j = 0; j < A.GetLength(1); ++j) { S[i, j] = A[i, j]; } } while (0 < n) { if (1 == n % 2) C = Multiply(C, S); S = Multiply(S,S); n /= 2; } return C; } public static BigInteger Fib(in ulong n) { var C = Power(F, n); return C[0, 1]; } public static void Task(in ulong p) { var ans = Fib(p).ToString(); var sp = p.ToString("N0", nfi); if (ans.Length <= 40) { Console.WriteLine("Fibonacci({0}) = {1}", sp, ans); } else { Console.WriteLine("Fibonacci({0}) = {1} ... {2}", sp, ans[0..19], ans[^20..]); } } public static void Main() { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); for (ulong p = 10; p <= 10_000_000; p *= 10) { Task(p); } stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine("Took " + elapsedTime); } } }
class Head(): def __init__(self, lo, hi=None, shift=0): if hi is None: hi = lo d = hi - lo ds, ls, hs = str(d), str(lo), str(hi) if d and len(ls) > len(ds): assert(len(ls) - len(ds) + 1 > 21) lo = int(str(lo)[:len(ls) - len(ds) + 1]) hi = int(str(hi)[:len(hs) - len(ds) + 1]) + 1 shift += len(ds) - 1 elif len(ls) > 100: lo = int(str(ls)[:100]) hi = lo + 1 shift = len(ls) - 100 self.lo, self.hi, self.shift = lo, hi, shift def __mul__(self, other): lo = self.lo*other.lo hi = self.hi*other.hi shift = self.shift + other.shift return Head(lo, hi, shift) def __add__(self, other): if self.shift < other.shift: return other + self sh = self.shift - other.shift if sh >= len(str(other.hi)): return Head(self.lo, self.hi, self.shift) ls = str(other.lo) hs = str(other.hi) lo = self.lo + int(ls[:len(ls)-sh]) hi = self.hi + int(hs[:len(hs)-sh]) return Head(lo, hi, self.shift) def __repr__(self): return str(self.hi)[:20] class Tail(): def __init__(self, v): self.v = int(f'{v:020d}'[-20:]) def __add__(self, other): return Tail(self.v + other.v) def __mul__(self, other): return Tail(self.v*other.v) def __repr__(self): return f'{self.v:020d}'[-20:] def mul(a, b): return a[0]*b[0] + a[1]*b[1], a[0]*b[1] + a[1]*b[2], a[1]*b[1] + a[2]*b[2] def fibo(n, cls): n -= 1 zero, one = cls(0), cls(1) m = (one, one, zero) e = (one, zero, one) while n: if n&1: e = mul(m, e) m = mul(m, m) n >>= 1 return f'{e[0]}' for i in range(2, 10): n = 10**i print(f'10^{i} :', fibo(n, Head), '...', fibo(n, Tail)) for i in range(3, 8): n = 2**i s = f'2^{n}' print(f'{s:5s}:', fibo(2**n, Head), '...', fibo(2**n, Tail))
Convert the following code from C# to Python, ensuring the logic remains intact.
using System; class Program { static bool isPal(int n) { int rev = 0, lr = -1, rem; while (n > rev) { n = Math.DivRem(n, 10, out rem); if (lr < 0 && rem == 0) return false; lr = rev; rev = 10 * rev + rem; if (n == rev || n == lr) return true; } return false; } static void Main(string[] args) { var sw = System.Diagnostics.Stopwatch.StartNew(); int x = 900009, y = (int)Math.Sqrt(x), y10, max = 999, max9 = max - 9, z, p, bp = x, ld, c; var a = new int[]{ 0,9,0,3,0,0,0,7,0,1 }; string bs = ""; y /= 11; if ((y & 1) == 0) y--; if (y % 5 == 0) y -= 2; y *= 11; while (y <= max) { c = 0; y10 = y * 10; z = max9 + a[ld = y % 10]; p = y * z; while (p >= bp) { if (isPal(p)) { if (p > bp) bp = p; bs = string.Format("{0} x {1} = {2}", y, z - c, bp); } p -= y10; c += 10; } y += ld == 3 ? 44 : 22; } sw.Stop(); Console.Write("{0} {1} μs", bs, sw.Elapsed.TotalMilliseconds * 1000.0); } }
T=[set([(0, 0)])] def double(it): for a, b in it: yield a, b yield b, a def tails(n): if len(T)<=n: l = set() for i in range(10): for j in range(i, 10): I = i*10**(n-1) J = j*10**(n-1) it = tails(n-1) if I!=J: it = double(it) for t1, t2 in it: if ((I+t1)*(J+t2)+1)%10**n == 0: l.add((I+t1, J+t2)) T.append(l) return T[n] def largestPalindrome(n): m, tail = 0, n // 2 head = n - tail up = 10**head for L in range(1, 9*10**(head-1)+1): m = 0 sol = None for i in range(1, L + 1): lo = max(i, int(up - (up - L + 1)**2 / (up - i)) + 1) hi = int(up - (up - L)**2 / (up - i)) for j in range(lo, hi + 1): I = (up-i) * 10**tail J = (up-j) * 10**tail it = tails(tail) if I!=J: it = double(it) for t1, t2 in it: val = (I + t1)*(J + t2) s = str(val) if s == s[::-1] and val>m: sol = (I + t1, J + t2) m = val if m: print("{:2d}\t{:4d}".format(n, m % 1337), sol, sol[0] * sol[1]) return m % 1337 return 0 if __name__ == "__main__": for k in range(1, 14): largestPalindrome(k)
Ensure the translated Python code behaves exactly like the original C# snippet.
static string[] inputs = { "pi=3.14159265358979323846264338327950288419716939937510582097494459231", "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", "\"-in Aus$+1411.8millions\"", "===US$0017440 millions=== (in 2000 dollars)" }; void Main() { inputs.Select(s => Commatize(s, 0, 3, ",")) .ToList() .ForEach(Console.WriteLine); } string Commatize(string text, int startPosition, int interval, string separator) { var matches = Regex.Matches(text.Substring(startPosition), "[0-9]*"); var x = matches.Cast<Match>().Select(match => Commatize(match, interval, separator, text)).ToList(); return string.Join("", x); } string Commatize(Match match, int interval, string separator, string original) { if (match.Length <= interval) return original.Substring(match.Index, match.Index == original.Length ? 0 : Math.Max(match.Length, 1)); return string.Join(separator, match.Value.Split(interval)); } public static class Extension { public static string[] Split(this string source, int interval) { return SplitImpl(source, interval).ToArray(); } static IEnumerable<string>SplitImpl(string source, int interval) { for (int i = 1; i < source.Length; i++) { if (i % interval != 0) continue; yield return source.Substring(i - interval, interval); } } }
import re as RegEx def Commatize( _string, _startPos=0, _periodLen=3, _separator="," ): outString = "" strPos = 0 matches = RegEx.findall( "[0-9]*", _string ) for match in matches[:-1]: if not match: outString += _string[ strPos ] strPos += 1 else: if len(match) > _periodLen: leadIn = match[:_startPos] periods = [ match [ i:i + _periodLen ] for i in range ( _startPos, len ( match ), _periodLen ) ] outString += leadIn + _separator.join( periods ) else: outString += match strPos += len( match ) return outString print ( Commatize( "pi=3.14159265358979323846264338327950288419716939937510582097494459231", 0, 5, " " ) ) print ( Commatize( "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", 0, 3, "." )) print ( Commatize( "\"-in Aus$+1411.8millions\"" )) print ( Commatize( "===US$0017440 millions=== (in 2000 dollars)" )) print ( Commatize( "123.e8000 is pretty big." )) print ( Commatize( "The land area of the earth is 57268900(29% of the surface) square miles." )) print ( Commatize( "Ain't no numbers in this here words, nohow, no way, Jose." )) print ( Commatize( "James was never known as 0000000007" )) print ( Commatize( "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe." )) print ( Commatize( "␢␢␢$-140000±100 millions." )) print ( Commatize( "6/9/1946 was a good year for some." ))
Rewrite this program in Python while keeping its functionality equivalent to the C# version.
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; namespace AruthmeticCoding { using Freq = Dictionary<char, long>; using Triple = Tuple<BigInteger, int, Dictionary<char, long>>; class Program { static Freq CumulativeFreq(Freq freq) { long total = 0; Freq cf = new Freq(); for (int i = 0; i < 256; i++) { char c = (char)i; if (freq.ContainsKey(c)) { long v = freq[c]; cf[c] = total; total += v; } } return cf; } static Triple ArithmeticCoding(string str, long radix) { Freq freq = new Freq(); foreach (char c in str) { if (freq.ContainsKey(c)) { freq[c] += 1; } else { freq[c] = 1; } } Freq cf = CumulativeFreq(freq); BigInteger @base = str.Length; BigInteger lower = 0; BigInteger pf = 1; foreach (char c in str) { BigInteger x = cf[c]; lower = lower * @base + x * pf; pf = pf * freq[c]; } BigInteger upper = lower + pf; int powr = 0; BigInteger bigRadix = radix; while (true) { pf = pf / bigRadix; if (pf == 0) break; powr++; } BigInteger diff = (upper - 1) / (BigInteger.Pow(bigRadix, powr)); return new Triple(diff, powr, freq); } static string ArithmeticDecoding(BigInteger num, long radix, int pwr, Freq freq) { BigInteger powr = radix; BigInteger enc = num * BigInteger.Pow(powr, pwr); long @base = freq.Values.Sum(); Freq cf = CumulativeFreq(freq); Dictionary<long, char> dict = new Dictionary<long, char>(); foreach (char key in cf.Keys) { long value = cf[key]; dict[value] = key; } long lchar = -1; for (long i = 0; i < @base; i++) { if (dict.ContainsKey(i)) { lchar = dict[i]; } else if (lchar != -1) { dict[i] = (char)lchar; } } StringBuilder decoded = new StringBuilder((int)@base); BigInteger bigBase = @base; for (long i = @base - 1; i >= 0; --i) { BigInteger pow = BigInteger.Pow(bigBase, (int)i); BigInteger div = enc / pow; char c = dict[(long)div]; BigInteger fv = freq[c]; BigInteger cv = cf[c]; BigInteger diff = enc - pow * cv; enc = diff / fv; decoded.Append(c); } return decoded.ToString(); } static void Main(string[] args) { long radix = 10; string[] strings = { "DABDDB", "DABDDBBDDBA", "ABRACADABRA", "TOBEORNOTTOBEORTOBEORNOT" }; foreach (string str in strings) { Triple encoded = ArithmeticCoding(str, radix); string dec = ArithmeticDecoding(encoded.Item1, radix, encoded.Item2, encoded.Item3); Console.WriteLine("{0,-25}=> {1,19} * {2}^{3}", str, encoded.Item1, radix, encoded.Item2); if (str != dec) { throw new Exception("\tHowever that is incorrect!"); } } } } }
from collections import Counter def cumulative_freq(freq): cf = {} total = 0 for b in range(256): if b in freq: cf[b] = total total += freq[b] return cf def arithmethic_coding(bytes, radix): freq = Counter(bytes) cf = cumulative_freq(freq) base = len(bytes) lower = 0 pf = 1 for b in bytes: lower = lower*base + cf[b]*pf pf *= freq[b] upper = lower+pf pow = 0 while True: pf //= radix if pf==0: break pow += 1 enc = (upper-1) // radix**pow return enc, pow, freq def arithmethic_decoding(enc, radix, pow, freq): enc *= radix**pow; base = sum(freq.values()) cf = cumulative_freq(freq) dict = {} for k,v in cf.items(): dict[v] = k lchar = None for i in range(base): if i in dict: lchar = dict[i] elif lchar is not None: dict[i] = lchar decoded = bytearray() for i in range(base-1, -1, -1): pow = base**i div = enc//pow c = dict[div] fv = freq[c] cv = cf[c] rem = (enc - pow*cv) // fv enc = rem decoded.append(c) return bytes(decoded) radix = 10 for str in b'DABDDB DABDDBBDDBA ABRACADABRA TOBEORNOTTOBEORTOBEORNOT'.split(): enc, pow, freq = arithmethic_coding(str, radix) dec = arithmethic_decoding(enc, radix, pow, freq) print("%-25s=> %19s * %d^%s" % (str, enc, radix, pow)) if str != dec: raise Exception("\tHowever that is incorrect!")
Rewrite the snippet below in Python so it works the same as the original C# code.
using System; using System.Collections.Generic; class Node { public enum Colors { Black, White, Gray } public Colors color { get; set; } public int N { get; } public Node(int n) { N = n; color = Colors.White; } } class Graph { public HashSet<Node> V { get; } public Dictionary<Node, HashSet<Node>> Adj { get; } public void Kosaraju() { var L = new HashSet<Node>(); Action<Node> Visit = null; Visit = (u) => { if (u.color == Node.Colors.White) { u.color = Node.Colors.Gray; foreach (var v in Adj[u]) Visit(v); L.Add(u); } }; Action<Node, Node> Assign = null; Assign = (u, root) => { if (u.color != Node.Colors.Black) { if (u == root) Console.Write("SCC: "); Console.Write(u.N + " "); u.color = Node.Colors.Black; foreach (var v in Adj[u]) Assign(v, root); if (u == root) Console.WriteLine(); } }; foreach (var u in V) Visit(u); foreach (var u in L) Assign(u, u); } }
def kosaraju(g): class nonlocal: pass size = len(g) vis = [False]*size l = [0]*size nonlocal.x = size t = [[]]*size def visit(u): if not vis[u]: vis[u] = True for v in g[u]: visit(v) t[v] = t[v] + [u] nonlocal.x = nonlocal.x - 1 l[nonlocal.x] = u for u in range(len(g)): visit(u) c = [0]*size def assign(u, root): if vis[u]: vis[u] = False c[u] = root for v in t[u]: assign(v, root) for u in l: assign(u, u) return c g = [[1], [2], [0], [1,2,4], [3,5], [2,6], [5], [4,6,7]] print kosaraju(g)
Change the following C# code into Python without altering its purpose.
using System; using System.Reflection; public class Rosetta { public static void Main() { BindingFlags flags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; foreach (var method in typeof(TestForMethodReflection).GetMethods(flags)) Console.WriteLine(method); } class TestForMethodReflection { public void MyPublicMethod() {} private void MyPrivateMethod() {} public static void MyPublicStaticMethod() {} private static void MyPrivateStaticMethod() {} } }
import inspect class Super(object): def __init__(self, name): self.name = name def __str__(self): return "Super(%s)" % (self.name,) def doSup(self): return 'did super stuff' @classmethod def cls(cls): return 'cls method (in sup)' @classmethod def supCls(cls): return 'Super method' @staticmethod def supStatic(): return 'static method' class Other(object): def otherMethod(self): return 'other method' class Sub(Other, Super): def __init__(self, name, *args): super(Sub, self).__init__(name); self.rest = args; self.methods = {} def __dir__(self): return list(set( \ sum([dir(base) for base in type(self).__bases__], []) \ + type(self).__dict__.keys() \ + self.__dict__.keys() \ + self.methods.keys() \ )) def __getattr__(self, name): if name in self.methods: if callable(self.methods[name]) and self.methods[name].__code__.co_argcount > 0: if self.methods[name].__code__.co_varnames[0] == 'self': return self.methods[name].__get__(self, type(self)) if self.methods[name].__code__.co_varnames[0] == 'cls': return self.methods[name].__get__(type(self), type) return self.methods[name] raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name)) def __str__(self): return "Sub(%s)" % self.name def doSub(): return 'did sub stuff' @classmethod def cls(cls): return 'cls method (in Sub)' @classmethod def subCls(cls): return 'Sub method' @staticmethod def subStatic(): return 'Sub method' sup = Super('sup') sub = Sub('sub', 0, 'I', 'two') sub.methods['incr'] = lambda x: x+1 sub.methods['strs'] = lambda self, x: str(self) * x [method for method in dir(sub) if callable(getattr(sub, method))] [method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == sub] [method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == type(sub)] [method for method in dir(sub) if callable(getattr(sub, method)) and type(getattr(sub, method)) == type(lambda:nil)] inspect.getmembers(sub, predicate=inspect.ismethod) map(lambda t: t[0], inspect.getmembers(sub, predicate=inspect.ismethod))
Generate a Python translation of this C# snippet without changing its computational steps.
var x = 0 var y = 0 There are also multi-line comments Everything inside of ] discard
Translate the given C# code snippet into Python without altering its behavior.
using System; using System.Linq; namespace PentominoTiling { class Program { static readonly char[] symbols = "FILNPTUVWXYZ-".ToCharArray(); static readonly int nRows = 8; static readonly int nCols = 8; static readonly int target = 12; static readonly int blank = 12; static int[][] grid = new int[nRows][]; static bool[] placed = new bool[target]; static void Main(string[] args) { var rand = new Random(); for (int r = 0; r < nRows; r++) grid[r] = Enumerable.Repeat(-1, nCols).ToArray(); for (int i = 0; i < 4; i++) { int randRow, randCol; do { randRow = rand.Next(nRows); randCol = rand.Next(nCols); } while (grid[randRow][randCol] == blank); grid[randRow][randCol] = blank; } if (Solve(0, 0)) { PrintResult(); } else { Console.WriteLine("no solution"); } Console.ReadKey(); } private static void PrintResult() { foreach (int[] r in grid) { foreach (int i in r) Console.Write("{0} ", symbols[i]); Console.WriteLine(); } } private static bool Solve(int pos, int numPlaced) { if (numPlaced == target) return true; int row = pos / nCols; int col = pos % nCols; if (grid[row][col] != -1) return Solve(pos + 1, numPlaced); for (int i = 0; i < shapes.Length; i++) { if (!placed[i]) { foreach (int[] orientation in shapes[i]) { if (!TryPlaceOrientation(orientation, row, col, i)) continue; placed[i] = true; if (Solve(pos + 1, numPlaced + 1)) return true; RemoveOrientation(orientation, row, col); placed[i] = false; } } } return false; } private static void RemoveOrientation(int[] orientation, int row, int col) { grid[row][col] = -1; for (int i = 0; i < orientation.Length; i += 2) grid[row + orientation[i]][col + orientation[i + 1]] = -1; } private static bool TryPlaceOrientation(int[] orientation, int row, int col, int shapeIndex) { for (int i = 0; i < orientation.Length; i += 2) { int x = col + orientation[i + 1]; int y = row + orientation[i]; if (x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1) return false; } grid[row][col] = shapeIndex; for (int i = 0; i < orientation.Length; i += 2) grid[row + orientation[i]][col + orientation[i + 1]] = shapeIndex; return true; } static readonly int[][] F = { new int[] {1, -1, 1, 0, 1, 1, 2, 1}, new int[] {0, 1, 1, -1, 1, 0, 2, 0}, new int[] {1, 0, 1, 1, 1, 2, 2, 1}, new int[] {1, 0, 1, 1, 2, -1, 2, 0}, new int[] {1, -2, 1, -1, 1, 0, 2, -1}, new int[] {0, 1, 1, 1, 1, 2, 2, 1}, new int[] {1, -1, 1, 0, 1, 1, 2, -1}, new int[] {1, -1, 1, 0, 2, 0, 2, 1}}; static readonly int[][] I = { new int[] { 0, 1, 0, 2, 0, 3, 0, 4 }, new int[] { 1, 0, 2, 0, 3, 0, 4, 0 } }; static readonly int[][] L = { new int[] {1, 0, 1, 1, 1, 2, 1, 3}, new int[] {1, 0, 2, 0, 3, -1, 3, 0}, new int[] {0, 1, 0, 2, 0, 3, 1, 3}, new int[] {0, 1, 1, 0, 2, 0, 3, 0}, new int[] {0, 1, 1, 1, 2, 1, 3, 1}, new int[] {0, 1, 0, 2, 0, 3, 1, 0}, new int[] {1, 0, 2, 0, 3, 0, 3, 1}, new int[] {1, -3, 1, -2, 1, -1, 1, 0}}; static readonly int[][] N = { new int[] {0, 1, 1, -2, 1, -1, 1, 0}, new int[] {1, 0, 1, 1, 2, 1, 3, 1}, new int[] {0, 1, 0, 2, 1, -1, 1, 0}, new int[] {1, 0, 2, 0, 2, 1, 3, 1}, new int[] {0, 1, 1, 1, 1, 2, 1, 3}, new int[] {1, 0, 2, -1, 2, 0, 3, -1}, new int[] {0, 1, 0, 2, 1, 2, 1, 3}, new int[] {1, -1, 1, 0, 2, -1, 3, -1}}; static readonly int[][] P = { new int[] {0, 1, 1, 0, 1, 1, 2, 1}, new int[] {0, 1, 0, 2, 1, 0, 1, 1}, new int[] {1, 0, 1, 1, 2, 0, 2, 1}, new int[] {0, 1, 1, -1, 1, 0, 1, 1}, new int[] {0, 1, 1, 0, 1, 1, 1, 2}, new int[] {1, -1, 1, 0, 2, -1, 2, 0}, new int[] {0, 1, 0, 2, 1, 1, 1, 2}, new int[] {0, 1, 1, 0, 1, 1, 2, 0}}; static readonly int[][] T = { new int[] {0, 1, 0, 2, 1, 1, 2, 1}, new int[] {1, -2, 1, -1, 1, 0, 2, 0}, new int[] {1, 0, 2, -1, 2, 0, 2, 1}, new int[] {1, 0, 1, 1, 1, 2, 2, 0}}; static readonly int[][] U = { new int[] {0, 1, 0, 2, 1, 0, 1, 2}, new int[] {0, 1, 1, 1, 2, 0, 2, 1}, new int[] {0, 2, 1, 0, 1, 1, 1, 2}, new int[] {0, 1, 1, 0, 2, 0, 2, 1}}; static readonly int[][] V = { new int[] {1, 0, 2, 0, 2, 1, 2, 2}, new int[] {0, 1, 0, 2, 1, 0, 2, 0}, new int[] {1, 0, 2, -2, 2, -1, 2, 0}, new int[] {0, 1, 0, 2, 1, 2, 2, 2}}; static readonly int[][] W = { new int[] {1, 0, 1, 1, 2, 1, 2, 2}, new int[] {1, -1, 1, 0, 2, -2, 2, -1}, new int[] {0, 1, 1, 1, 1, 2, 2, 2}, new int[] {0, 1, 1, -1, 1, 0, 2, -1}}; static readonly int[][] X = { new int[] { 1, -1, 1, 0, 1, 1, 2, 0 } }; static readonly int[][] Y = { new int[] {1, -2, 1, -1, 1, 0, 1, 1}, new int[] {1, -1, 1, 0, 2, 0, 3, 0}, new int[] {0, 1, 0, 2, 0, 3, 1, 1}, new int[] {1, 0, 2, 0, 2, 1, 3, 0}, new int[] {0, 1, 0, 2, 0, 3, 1, 2}, new int[] {1, 0, 1, 1, 2, 0, 3, 0}, new int[] {1, -1, 1, 0, 1, 1, 1, 2}, new int[] {1, 0, 2, -1, 2, 0, 3, 0}}; static readonly int[][] Z = { new int[] {0, 1, 1, 0, 2, -1, 2, 0}, new int[] {1, 0, 1, 1, 1, 2, 2, 2}, new int[] {0, 1, 1, 1, 2, 1, 2, 2}, new int[] {1, -2, 1, -1, 1, 0, 2, -2}}; static readonly int[][][] shapes = { F, I, L, N, P, T, U, V, W, X, Y, Z }; } }
from itertools import product minos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)), ((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)), ((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)), ((131843, 7, 6), (1798, 6, 7), (775, 6, 7), (1795, 6, 7), (1543, 6, 7), (197377, 7, 6), (197378, 7, 6), (66307, 7, 6)), ((132865, 6, 6), (131846, 6, 6), (198146, 6, 6), (132611, 6, 6), (393986, 6, 6), (263938, 6, 6), (67330, 6, 6), (132868, 6, 6)), ((1039, 5, 7), (33751554, 7, 5), (16843521, 7, 5), (16974081, 7, 5), (33686274, 7, 5), (3842, 5, 7), (3844, 5, 7), (527, 5, 7)), ((1804, 5, 7), (33751297, 7, 5), (33686273, 7, 5), (16974338, 7, 5), (16843522, 7, 5), (782, 5, 7), (3079, 5, 7), (3587, 5, 7)), ((263683, 6, 6), (198148, 6, 6), (66310, 6, 6), (393985, 6, 6)), ((67329, 6, 6), (131591, 6, 6), (459266, 6, 6), (263940, 6, 6)), ((459780, 6, 6), (459009, 6, 6), (263175, 6, 6), (65799, 6, 6)), ((4311810305, 8, 4), (31, 4, 8)), ((132866, 6, 6),)) boxchar_double_width = ' ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋' boxchar_single_width = [c + ' ─━'[i%3] for i, c in enumerate(boxchar_double_width)] patterns = boxchar_single_width tiles = [] for row in reversed(minos): tiles.append([]) for n, x, y in row: for shift in (b*8 + a for a, b in product(range(x), range(y))): tiles[-1].append(n << shift) def img(seq): b = [[0]*10 for _ in range(10)] for i, s in enumerate(seq): for j, k in product(range(8), range(8)): if s & (1<<(j*8 + k)): b[j + 1][k + 1] = i + 1 idices = [[0]*9 for _ in range(9)] for i, j in product(range(9), range(9)): n = (b[i+1][j+1], b[i][j+1], b[i][j], b[i+1][j], b[i+1][j+1]) idices[i][j] = sum((a != b)*(1 + (not a or not b))*3**i for i, (a,b) in enumerate(zip(n, n[1:]))) return '\n'.join(''.join(patterns[i] for i in row) for row in idices) def tile(board=0, seq=tuple(), tiles=tiles): if not tiles: yield img(seq) return for c in tiles[0]: b = board | c tnext = [] for t in tiles[1:]: tnext.append(tuple(n for n in t if not n&b)) if not tnext[-1]: break else: yield from tile(b, seq + (c,), tnext) for x in tile(): print(x)
Port the provided C# code into Python while preserving the original functionality.
using System; class Example { public int foo(int x) { return 42 + x; } } class Program { static void Main(string[] args) { var example = new Example(); var method = "foo"; var result = (int)example.GetType().GetMethod(method).Invoke(example, new object[]{ 5 }); Console.WriteLine("{0}(5) = {1}", method, result); } }
class Example(object): def foo(self, x): return 42 + x name = "foo" getattr(Example(), name)(5)
Convert this C# snippet to Python and keep its semantics consistent.
int j;
example1 = 3 example2 = 3.0 example3 = True example4 = "hello" example1 = "goodbye"
Write a version of this C# function in Python with identical behavior.
using System; using System.Collections.Generic; class Program { static List<int> PrimesUpTo(int limit, bool verbose = false) { var sw = System.Diagnostics.Stopwatch.StartNew(); var members = new SortedSet<int>{ 1 }; int stp = 1, prime = 2, n, nxtpr, rtlim = 1 + (int)Math.Sqrt(limit), nl, ac = 2, rc = 1; List<int> primes = new List<int>(), tl = new List<int>(); while (prime < rtlim) { nl = Math.Min(prime * stp, limit); if (stp < limit) { tl.Clear(); foreach (var w in members) for (n = w + stp; n <= nl; n += stp) tl.Add(n); members.UnionWith(tl); ac += tl.Count; } stp = nl; nxtpr = 5; tl.Clear(); foreach (var w in members) { if (nxtpr == 5 && w > prime) nxtpr = w; if ((n = prime * w) > nl) break; else tl.Add(n); } foreach (var itm in tl) members.Remove(itm); rc += tl.Count; primes.Add(prime); prime = prime == 2 ? 3 : nxtpr; } members.Remove(1); primes.AddRange(members); sw.Stop(); if (verbose) Console.WriteLine("Up to {0}, added:{1}, removed:{2}, primes counted:{3}, time:{4} ms", limit, ac, rc, primes.Count, sw.Elapsed.TotalMilliseconds); return primes; } static void Main(string[] args) { Console.WriteLine("[{0}]", string.Join(", ", PrimesUpTo(150, true))); PrimesUpTo(1000000, true); } }
from numpy import ndarray from math import isqrt def pritchard(limit): members = ndarray(limit + 1, dtype=bool) members.fill(False) members[1] = True steplength, prime, rtlim, nlimit = 1, 2, isqrt(limit), 2 primes = [] while prime <= rtlim: if steplength < limit: for w in range(1, len(members)): if members[w]: n = w + steplength while n <= nlimit: members[n] = True n += steplength steplength = nlimit np = 5 mcpy = members.copy() for w in range(1, len(members)): if mcpy[w]: if np == 5 and w > prime: np = w n = prime * w if n > nlimit: break members[n] = False if np < prime: break primes.append(prime) prime = 3 if prime == 2 else np nlimit = min(steplength * prime, limit) newprimes = [i for i in range(2, len(members)) if members[i]] return sorted(primes + newprimes) print(pritchard(150)) print('Number of primes up to 1,000,000:', len(pritchard(1000000)))
Write the same code in Python as shown below in C#.
using System; namespace ParticleSwarmOptimization { public struct Parameters { public double omega, phip, phig; public Parameters(double omega, double phip, double phig) : this() { this.omega = omega; this.phip = phip; this.phig = phig; } } public struct State { public int iter; public double[] gbpos; public double gbval; public double[] min; public double[] max; public Parameters parameters; public double[][] pos; public double[][] vel; public double[][] bpos; public double[] bval; public int nParticles; public int nDims; public State(int iter, double[] gbpos, double gbval, double[] min, double[] max, Parameters parameters, double[][] pos, double[][] vel, double[][] bpos, double[] bval, int nParticles, int nDims) : this() { this.iter = iter; this.gbpos = gbpos; this.gbval = gbval; this.min = min; this.max = max; this.parameters = parameters; this.pos = pos; this.vel = vel; this.bpos = bpos; this.bval = bval; this.nParticles = nParticles; this.nDims = nDims; } public void Report(string testfunc) { Console.WriteLine("Test Function  : {0}", testfunc); Console.WriteLine("Iterations  : {0}", iter); Console.WriteLine("Global Best Position : {0}", string.Join(", ", gbpos)); Console.WriteLine("Global Best Value  : {0}", gbval); } } class Program { public static State PsoInit(double[] min, double[] max, Parameters parameters, int nParticles) { var nDims = min.Length; double[][] pos = new double[nParticles][]; for (int i = 0; i < nParticles; i++) { pos[i] = new double[min.Length]; min.CopyTo(pos[i], 0); } double[][] vel = new double[nParticles][]; for (int i = 0; i < nParticles; i++) { vel[i] = new double[nDims]; } double[][] bpos = new double[nParticles][]; for (int i = 0; i < nParticles; i++) { bpos[i] = new double[min.Length]; min.CopyTo(bpos[i], 0); } double[] bval = new double[nParticles]; for (int i = 0; i < nParticles; i++) { bval[i] = double.PositiveInfinity; } int iter = 0; double[] gbpos = new double[nDims]; for (int i = 0; i < nDims; i++) { gbpos[i] = double.PositiveInfinity; } double gbval = double.PositiveInfinity; return new State(iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims); } static Random r = new Random(); public static State Pso(Func<double[], double> fn, State y) { var p = y.parameters; double[] v = new double[y.nParticles]; double[][] bpos = new double[y.nParticles][]; for (int i = 0; i < y.nParticles; i++) { bpos[i] = new double[y.min.Length]; y.min.CopyTo(bpos[i], 0); } double[] bval = new double[y.nParticles]; double[] gbpos = new double[y.nDims]; double gbval = double.PositiveInfinity; for (int j = 0; j < y.nParticles; j++) { v[j] = fn.Invoke(y.pos[j]); if (v[j] < y.bval[j]) { y.pos[j].CopyTo(bpos[j], 0); bval[j] = v[j]; } else { y.bpos[j].CopyTo(bpos[j], 0); bval[j] = y.bval[j]; } if (bval[j] < gbval) { gbval = bval[j]; bpos[j].CopyTo(gbpos, 0); } } double rg = r.NextDouble(); double[][] pos = new double[y.nParticles][]; double[][] vel = new double[y.nParticles][]; for (int i = 0; i < y.nParticles; i++) { pos[i] = new double[y.nDims]; vel[i] = new double[y.nDims]; } for (int j = 0; j < y.nParticles; j++) { double rp = r.NextDouble(); bool ok = true; for (int k = 0; k < y.nDims; k++) { vel[j][k] = 0.0; pos[j][k] = 0.0; } for (int k = 0; k < y.nDims; k++) { vel[j][k] = p.omega * y.vel[j][k] + p.phip * rp * (bpos[j][k] - y.pos[j][k]) + p.phig * rg * (gbpos[k] - y.pos[j][k]); pos[j][k] = y.pos[j][k] + vel[j][k]; ok = ok && y.min[k] < pos[j][k] && y.max[k] > pos[j][k]; } if (!ok) { for (int k = 0; k < y.nDims; k++) { pos[j][k] = y.min[k] + (y.max[k] - y.min[k]) * r.NextDouble(); } } } var iter = 1 + y.iter; return new State(iter, gbpos, gbval, y.min, y.max, y.parameters, pos, vel, bpos, bval, y.nParticles, y.nDims); } public static State Iterate(Func<double[], double> fn, int n, State y) { State r = y; if (n == int.MaxValue) { State old = y; while (true) { r = Pso(fn, r); if (r.Equals(old)) break; old = r; } } else { for (int i = 0; i < n; i++) { r = Pso(fn, r); } } return r; } public static double Mccormick(double[] x) { var a = x[0]; var b = x[1]; return Math.Sin(a + b) + (a - b) * (a - b) + 1.0 + 2.5 * b - 1.5 * a; } public static double Michalewicz(double[] x) { int m = 10; int d = x.Length; double sum = 0.0; for (int i = 1; i < d; i++) { var j = x[i - 1]; var k = Math.Sin(i * j * j / Math.PI); sum += Math.Sin(j) * Math.Pow(k, 2.0 * m); } return -sum; } static void Main(string[] args) { var state = PsoInit( new double[] { -1.5, -3.0 }, new double[] { 4.0, 4.0 }, new Parameters(0.0, 0.6, 0.3), 100 ); state = Iterate(Mccormick, 40, state); state.Report("McCormick"); Console.WriteLine("f(-.54719, -1.54719) : {0}", Mccormick(new double[] { -.54719, -1.54719 })); Console.WriteLine(); state = PsoInit( new double[] { -0.0, -0.0 }, new double[] { Math.PI, Math.PI }, new Parameters(0.3, 0.3, 0.3), 1000 ); state = Iterate(Michalewicz, 30, state); state.Report("Michalewicz (2D)"); Console.WriteLine("f(2.20, 1.57)  : {0}", Michalewicz(new double[] { 2.20, 1.57 })); } } }
import math import random INFINITY = 1 << 127 MAX_INT = 1 << 31 class Parameters: def __init__(self, omega, phip, phig): self.omega = omega self.phip = phip self.phig = phig class State: def __init__(self, iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims): self.iter = iter self.gbpos = gbpos self.gbval = gbval self.min = min self.max = max self.parameters = parameters self.pos = pos self.vel = vel self.bpos = bpos self.bval = bval self.nParticles = nParticles self.nDims = nDims def report(self, testfunc): print "Test Function :", testfunc print "Iterations  :", self.iter print "Global Best Position :", self.gbpos print "Global Best Value  : %.16f" % self.gbval def uniform01(): v = random.random() assert 0.0 <= v and v < 1.0 return v def psoInit(min, max, parameters, nParticles): nDims = len(min) pos = [min[:]] * nParticles vel = [[0.0] * nDims] * nParticles bpos = [min[:]] * nParticles bval = [INFINITY] * nParticles iter = 0 gbpos = [INFINITY] * nDims gbval = INFINITY return State(iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDims); def pso(fn, y): p = y.parameters v = [0.0] * (y.nParticles) bpos = [y.min[:]] * (y.nParticles) bval = [0.0] * (y.nParticles) gbpos = [0.0] * (y.nDims) gbval = INFINITY for j in xrange(0, y.nParticles): v[j] = fn(y.pos[j]) if v[j] < y.bval[j]: bpos[j] = y.pos[j][:] bval[j] = v[j] else: bpos[j] = y.bpos[j][:] bval[j] = y.bval[j] if bval[j] < gbval: gbval = bval[j] gbpos = bpos[j][:] rg = uniform01() pos = [[None] * (y.nDims)] * (y.nParticles) vel = [[None] * (y.nDims)] * (y.nParticles) for j in xrange(0, y.nParticles): rp = uniform01() ok = True vel[j] = [0.0] * (len(vel[j])) pos[j] = [0.0] * (len(pos[j])) for k in xrange(0, y.nDims): vel[j][k] = p.omega * y.vel[j][k] \ + p.phip * rp * (bpos[j][k] - y.pos[j][k]) \ + p.phig * rg * (gbpos[k] - y.pos[j][k]) pos[j][k] = y.pos[j][k] + vel[j][k] ok = ok and y.min[k] < pos[j][k] and y.max[k] > pos[j][k] if not ok: for k in xrange(0, y.nDims): pos[j][k] = y.min[k] + (y.max[k] - y.min[k]) * uniform01() iter = 1 + y.iter return State(iter, gbpos, gbval, y.min, y.max, y.parameters, pos, vel, bpos, bval, y.nParticles, y.nDims); def iterate(fn, n, y): r = y old = y if n == MAX_INT: while True: r = pso(fn, r) if r == old: break old = r else: for _ in xrange(0, n): r = pso(fn, r) return r def mccormick(x): (a, b) = x return math.sin(a + b) + (a - b) * (a - b) + 1.0 + 2.5 * b - 1.5 * a def michalewicz(x): m = 10 d = len(x) sum = 0.0 for i in xrange(1, d): j = x[i - 1] k = math.sin(i * j * j / math.pi) sum += math.sin(j) * k ** (2.0 * m) return -sum def main(): state = psoInit([-1.5, -3.0], [4.0, 4.0], Parameters(0.0, 0.6, 0.3), 100) state = iterate(mccormick, 40, state) state.report("McCormick") print "f(-.54719, -1.54719) : %.16f" % (mccormick([-.54719, -1.54719])) print state = psoInit([0.0, 0.0], [math.pi, math.pi], Parameters(0.3, 0.3, 0.3), 1000) state = iterate(michalewicz, 30, state) state.report("Michalewicz (2D)") print "f(2.20, 1.57)  : %.16f" % (michalewicz([2.2, 1.57])) main()
Convert this C# block to Python, preserving its control flow and logic.
using System; using System.Collections.Generic; using System.Linq; public static class TwelveStatements { public static void Main() { Func<Statements, bool>[] checks = { st => st[1], st => st[2] == (7.To(12).Count(i => st[i]) == 3), st => st[3] == (2.To(12, by: 2).Count(i => st[i]) == 2), st => st[4] == st[5].Implies(st[6] && st[7]), st => st[5] == (!st[2] && !st[3] && !st[4]), st => st[6] == (1.To(12, by: 2).Count(i => st[i]) == 4), st => st[7] == (st[2] != st[3]), st => st[8] == st[7].Implies(st[5] && st[6]), st => st[9] == (1.To(6).Count(i => st[i]) == 3), st => st[10] == (st[11] && st[12]), st => st[11] == (7.To(9).Count(i => st[i]) == 1), st => st[12] == (1.To(11).Count(i => st[i]) == 4) }; for (Statements statements = new Statements(0); statements.Value < 4096; statements++) { int count = 0; int falseIndex = 0; for (int i = 0; i < checks.Length; i++) { if (checks[i](statements)) count++; else falseIndex = i; } if (count == 0) Console.WriteLine($"{"All wrong:", -13}{statements}"); else if (count == 11) Console.WriteLine($"{$"Wrong at {falseIndex + 1}:", -13}{statements}"); else if (count == 12) Console.WriteLine($"{"All correct:", -13}{statements}"); } } struct Statements { public Statements(int value) : this() { Value = value; } public int Value { get; } public bool this[int index] => (Value & (1 << index - 1)) != 0; public static Statements operator ++(Statements statements) => new Statements(statements.Value + 1); public override string ToString() { Statements copy = this; return string.Join(" ", from i in 1.To(12) select copy[i] ? "T" : "F"); } } static bool Implies(this bool x, bool y) => !x || y; static IEnumerable<int> To(this int start, int end, int by = 1) { while (start <= end) { yield return start; start += by; } } }
from itertools import product constraintinfo = ( (lambda st: len(st) == 12 ,(1, 'This is a numbered list of twelve statements')), (lambda st: sum(st[-6:]) == 3 ,(2, 'Exactly 3 of the last 6 statements are true')), (lambda st: sum(st[1::2]) == 2 ,(3, 'Exactly 2 of the even-numbered statements are true')), (lambda st: (st[5]&st[6]) if st[4] else 1 ,(4, 'If statement 5 is true, then statements 6 and 7 are both true')), (lambda st: sum(st[1:4]) == 0 ,(5, 'The 3 preceding statements are all false')), (lambda st: sum(st[0::2]) == 4 ,(6, 'Exactly 4 of the odd-numbered statements are true')), (lambda st: sum(st[1:3]) == 1 ,(7, 'Either statement 2 or 3 is true, but not both')), (lambda st: (st[4]&st[5]) if st[6] else 1 ,(8, 'If statement 7 is true, then 5 and 6 are both true')), (lambda st: sum(st[:6]) == 3 ,(9, 'Exactly 3 of the first 6 statements are true')), (lambda st: (st[10]&st[11]) ,(10, 'The next two statements are both true')), (lambda st: sum(st[6:9]) == 1 ,(11, 'Exactly 1 of statements 7, 8 and 9 are true')), (lambda st: sum(st[0:11]) == 4 ,(12, 'Exactly 4 of the preceding statements are true')), ) def printer(st, matches): if False in matches: print('Missed by one statement: %i, %s' % docs[matches.index(False)]) else: print('Full match:') print(' ' + ', '.join('%i:%s' % (i, 'T' if t else 'F') for i, t in enumerate(st, 1))) funcs, docs = zip(*constraintinfo) full, partial = [], [] for st in product( *([(False, True)] * 12) ): truths = [bool(func(st)) for func in funcs] matches = [s == t for s,t in zip(st, truths)] mcount = sum(matches) if mcount == 12: full.append((st, matches)) elif mcount == 11: partial.append((st, matches)) for stm in full + partial: printer(*stm)
Generate a Python translation of this C# snippet without changing its computational steps.
using System; using System.Collections.Generic; using System.Linq; public static class TwelveStatements { public static void Main() { Func<Statements, bool>[] checks = { st => st[1], st => st[2] == (7.To(12).Count(i => st[i]) == 3), st => st[3] == (2.To(12, by: 2).Count(i => st[i]) == 2), st => st[4] == st[5].Implies(st[6] && st[7]), st => st[5] == (!st[2] && !st[3] && !st[4]), st => st[6] == (1.To(12, by: 2).Count(i => st[i]) == 4), st => st[7] == (st[2] != st[3]), st => st[8] == st[7].Implies(st[5] && st[6]), st => st[9] == (1.To(6).Count(i => st[i]) == 3), st => st[10] == (st[11] && st[12]), st => st[11] == (7.To(9).Count(i => st[i]) == 1), st => st[12] == (1.To(11).Count(i => st[i]) == 4) }; for (Statements statements = new Statements(0); statements.Value < 4096; statements++) { int count = 0; int falseIndex = 0; for (int i = 0; i < checks.Length; i++) { if (checks[i](statements)) count++; else falseIndex = i; } if (count == 0) Console.WriteLine($"{"All wrong:", -13}{statements}"); else if (count == 11) Console.WriteLine($"{$"Wrong at {falseIndex + 1}:", -13}{statements}"); else if (count == 12) Console.WriteLine($"{"All correct:", -13}{statements}"); } } struct Statements { public Statements(int value) : this() { Value = value; } public int Value { get; } public bool this[int index] => (Value & (1 << index - 1)) != 0; public static Statements operator ++(Statements statements) => new Statements(statements.Value + 1); public override string ToString() { Statements copy = this; return string.Join(" ", from i in 1.To(12) select copy[i] ? "T" : "F"); } } static bool Implies(this bool x, bool y) => !x || y; static IEnumerable<int> To(this int start, int end, int by = 1) { while (start <= end) { yield return start; start += by; } } }
from itertools import product constraintinfo = ( (lambda st: len(st) == 12 ,(1, 'This is a numbered list of twelve statements')), (lambda st: sum(st[-6:]) == 3 ,(2, 'Exactly 3 of the last 6 statements are true')), (lambda st: sum(st[1::2]) == 2 ,(3, 'Exactly 2 of the even-numbered statements are true')), (lambda st: (st[5]&st[6]) if st[4] else 1 ,(4, 'If statement 5 is true, then statements 6 and 7 are both true')), (lambda st: sum(st[1:4]) == 0 ,(5, 'The 3 preceding statements are all false')), (lambda st: sum(st[0::2]) == 4 ,(6, 'Exactly 4 of the odd-numbered statements are true')), (lambda st: sum(st[1:3]) == 1 ,(7, 'Either statement 2 or 3 is true, but not both')), (lambda st: (st[4]&st[5]) if st[6] else 1 ,(8, 'If statement 7 is true, then 5 and 6 are both true')), (lambda st: sum(st[:6]) == 3 ,(9, 'Exactly 3 of the first 6 statements are true')), (lambda st: (st[10]&st[11]) ,(10, 'The next two statements are both true')), (lambda st: sum(st[6:9]) == 1 ,(11, 'Exactly 1 of statements 7, 8 and 9 are true')), (lambda st: sum(st[0:11]) == 4 ,(12, 'Exactly 4 of the preceding statements are true')), ) def printer(st, matches): if False in matches: print('Missed by one statement: %i, %s' % docs[matches.index(False)]) else: print('Full match:') print(' ' + ', '.join('%i:%s' % (i, 'T' if t else 'F') for i, t in enumerate(st, 1))) funcs, docs = zip(*constraintinfo) full, partial = [], [] for st in product( *([(False, True)] * 12) ): truths = [bool(func(st)) for func in funcs] matches = [s == t for s,t in zip(st, truths)] mcount = sum(matches) if mcount == 12: full.append((st, matches)) elif mcount == 11: partial.append((st, matches)) for stm in full + partial: printer(*stm)
Maintain the same structure and functionality when rewriting this code in Python.
using System; using System.Dynamic; namespace DynamicClassVariable { internal static class Program { #region Static Members private static void Main() { dynamic sampleObj = new ExpandoObject(); sampleObj.bar = 1; Console.WriteLine( "sampleObj.bar = {0}", sampleObj.bar ); Console.WriteLine( "< Press any key >" ); Console.ReadKey(); } #endregion } }
class empty(object): pass e = empty()
Change the following Java code into VB without altering its purpose.
import java.util.Scanner; public class MatrixArithmetic { public static double[][] minor(double[][] a, int x, int y){ int length = a.length-1; double[][] result = new double[length][length]; for(int i=0;i<length;i++) for(int j=0;j<length;j++){ if(i<x && j<y){ result[i][j] = a[i][j]; }else if(i>=x && j<y){ result[i][j] = a[i+1][j]; }else if(i<x && j>=y){ result[i][j] = a[i][j+1]; }else{ result[i][j] = a[i+1][j+1]; } } return result; } public static double det(double[][] a){ if(a.length == 1){ return a[0][0]; }else{ int sign = 1; double sum = 0; for(int i=0;i<a.length;i++){ sum += sign * a[0][i] * det(minor(a,0,i)); sign *= -1; } return sum; } } public static double perm(double[][] a){ if(a.length == 1){ return a[0][0]; }else{ double sum = 0; for(int i=0;i<a.length;i++){ sum += a[0][i] * perm(minor(a,0,i)); } return sum; } } public static void main(String args[]){ Scanner sc = new Scanner(System.in); int size = sc.nextInt(); double[][] a = new double[size][size]; for(int i=0;i<size;i++) for(int j=0;j<size;j++){ a[i][j] = sc.nextDouble(); } sc.close(); System.out.println("Determinant: "+det(a)); System.out.println("Permanent: "+perm(a)); } }
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
Ensure the translated VB code behaves exactly like the original Java snippet.
import static java.lang.Math.*; public class RayCasting { static boolean intersects(int[] A, int[] B, double[] P) { if (A[1] > B[1]) return intersects(B, A, P); if (P[1] == A[1] || P[1] == B[1]) P[1] += 0.0001; if (P[1] > B[1] || P[1] < A[1] || P[0] >= max(A[0], B[0])) return false; if (P[0] < min(A[0], B[0])) return true; double red = (P[1] - A[1]) / (double) (P[0] - A[0]); double blue = (B[1] - A[1]) / (double) (B[0] - A[0]); return red >= blue; } static boolean contains(int[][] shape, double[] pnt) { boolean inside = false; int len = shape.length; for (int i = 0; i < len; i++) { if (intersects(shape[i], shape[(i + 1) % len], pnt)) inside = !inside; } return inside; } public static void main(String[] a) { double[][] testPoints = {{10, 10}, {10, 16}, {-20, 10}, {0, 10}, {20, 10}, {16, 10}, {20, 20}}; for (int[][] shape : shapes) { for (double[] pnt : testPoints) System.out.printf("%7s ", contains(shape, pnt)); System.out.println(); } } final static int[][] square = {{0, 0}, {20, 0}, {20, 20}, {0, 20}}; final static int[][] squareHole = {{0, 0}, {20, 0}, {20, 20}, {0, 20}, {5, 5}, {15, 5}, {15, 15}, {5, 15}}; final static int[][] strange = {{0, 0}, {5, 5}, {0, 20}, {5, 15}, {15, 15}, {20, 20}, {20, 0}}; final static int[][] hexagon = {{6, 0}, {14, 0}, {20, 10}, {14, 20}, {6, 20}, {0, 10}}; final static int[][][] shapes = {square, squareHole, strange, hexagon}; }
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
Write the same code in VB as shown below in Java.
public class CountSubstring { public static int countSubstring(String subStr, String str){ return (str.length() - str.replace(subStr, "").length()) / subStr.length(); } public static void main(String[] args){ System.out.println(countSubstring("th", "the three truths")); System.out.println(countSubstring("abab", "ababababab")); System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab")); } }
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
Generate an equivalent VB version of this Java code.
public class PrimeDigits { private static boolean primeDigitsSum13(int n) { int sum = 0; while (n > 0) { int r = n % 10; if (r != 2 && r != 3 && r != 5 && r != 7) { return false; } n /= 10; sum += r; } return sum == 13; } public static void main(String[] args) { int c = 0; for (int i = 1; i < 1_000_000; i++) { if (primeDigitsSum13(i)) { System.out.printf("%6d ", i); if (c++ == 10) { c = 0; System.out.println(); } } } System.out.println(); } }
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
Generate a VB translation of this Java snippet without changing its computational steps.
public class PrimeDigits { private static boolean primeDigitsSum13(int n) { int sum = 0; while (n > 0) { int r = n % 10; if (r != 2 && r != 3 && r != 5 && r != 7) { return false; } n /= 10; sum += r; } return sum == 13; } public static void main(String[] args) { int c = 0; for (int i = 1; i < 1_000_000; i++) { if (primeDigitsSum13(i)) { System.out.printf("%6d ", i); if (c++ == 10) { c = 0; System.out.println(); } } } System.out.println(); } }
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
Produce a functionally identical VB code for the snippet given in Java.
import java.io.*; import java.nio.channels.*; import java.util.Date; public class TakeNotes { public static void main(String[] args) throws IOException { if (args.length > 0) { PrintStream ps = new PrintStream(new FileOutputStream("notes.txt", true)); ps.println(new Date()); ps.print("\t" + args[0]); for (int i = 1; i < args.length; i++) ps.print(" " + args[i]); ps.println(); ps.close(); } else { FileChannel fc = new FileInputStream("notes.txt").getChannel(); fc.transferTo(0, fc.size(), Channels.newChannel(System.out)); fc.close(); } } }
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
Write a version of this Java function in VB with identical behavior.
public class CommonPath { public static String commonPath(String... paths){ String commonPath = ""; String[][] folders = new String[paths.length][]; for(int i = 0; i < paths.length; i++){ folders[i] = paths[i].split("/"); } for(int j = 0; j < folders[0].length; j++){ String thisFolder = folders[0][j]; boolean allMatched = true; for(int i = 1; i < folders.length && allMatched; i++){ if(folders[i].length < j){ allMatched = false; break; } allMatched &= folders[i][j].equals(thisFolder); } if(allMatched){ commonPath += thisFolder + "/"; }else{ break; } } return commonPath; } public static void main(String[] args){ String[] paths = { "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"}; System.out.println(commonPath(paths)); String[] paths2 = { "/hame/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"}; System.out.println(commonPath(paths2)); } }
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
Produce a functionally identical VB code for the snippet given in Java.
import static java.lang.Math.abs; import java.util.*; import java.util.function.IntSupplier; public class Test { static void distCheck(IntSupplier f, int nRepeats, double delta) { Map<Integer, Integer> counts = new HashMap<>(); for (int i = 0; i < nRepeats; i++) counts.compute(f.getAsInt(), (k, v) -> v == null ? 1 : v + 1); double target = nRepeats / (double) counts.size(); int deltaCount = (int) (delta / 100.0 * target); counts.forEach((k, v) -> { if (abs(target - v) >= deltaCount) System.out.printf("distribution potentially skewed " + "for '%s': '%d'%n", k, v); }); counts.keySet().stream().sorted().forEach(k -> System.out.printf("%d %d%n", k, counts.get(k))); } public static void main(String[] a) { distCheck(() -> (int) (Math.random() * 5) + 1, 1_000_000, 1); } }
Option Explicit sub verifydistribution(calledfunction, samples, delta) Dim i, n, maxdiff Dim d : Set d = CreateObject("Scripting.Dictionary") wscript.echo "Running """ & calledfunction & """ " & samples & " times..." for i = 1 to samples Execute "n = " & calledfunction d(n) = d(n) + 1 next n = d.Count maxdiff = 0 wscript.echo "Expected average count is " & Int(samples/n) & " across " & n & " buckets." for each i in d.Keys dim diff : diff = abs(1 - d(i) / (samples/n)) if diff > maxdiff then maxdiff = diff wscript.echo "Bucket " & i & " had " & d(i) & " occurences" _ & vbTab & " difference from expected=" & FormatPercent(diff, 2) next wscript.echo "Maximum found variation is " & FormatPercent(maxdiff, 2) _ & ", desired limit is " & FormatPercent(delta, 2) & "." if maxdiff > delta then wscript.echo "Skewed!" else wscript.echo "Smooth!" end sub
Preserve the algorithm and functionality while converting the code from Java to VB.
import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class SterlingNumbersSecondKind { public static void main(String[] args) { System.out.println("Stirling numbers of the second kind:"); int max = 12; System.out.printf("n/k"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%10d", n); } System.out.printf("%n"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%-3d", n); for ( int k = 0 ; k <= n ; k++ ) { System.out.printf("%10s", sterling2(n, k)); } System.out.printf("%n"); } System.out.println("The maximum value of S2(100, k) = "); BigInteger previous = BigInteger.ZERO; for ( int k = 1 ; k <= 100 ; k++ ) { BigInteger current = sterling2(100, k); if ( current.compareTo(previous) > 0 ) { previous = current; } else { System.out.printf("%s%n(%d digits, k = %d)%n", previous, previous.toString().length(), k-1); break; } } } private static Map<String,BigInteger> COMPUTED = new HashMap<>(); private static final BigInteger sterling2(int n, int k) { String key = n + "," + k; if ( COMPUTED.containsKey(key) ) { return COMPUTED.get(key); } if ( n == 0 && k == 0 ) { return BigInteger.valueOf(1); } if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) { return BigInteger.ZERO; } if ( n == k ) { return BigInteger.valueOf(1); } if ( k > n ) { return BigInteger.ZERO; } BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1)); COMPUTED.put(key, result); return result; } }
Imports System.Numerics Module Module1 Class Sterling Private Shared ReadOnly COMPUTED As New Dictionary(Of String, BigInteger) Private Shared Function CacheKey(n As Integer, k As Integer) As String Return String.Format("{0}:{1}", n, k) End Function Private Shared Function Impl(n As Integer, k As Integer) As BigInteger If n = 0 AndAlso k = 0 Then Return 1 End If If (n > 0 AndAlso k = 0) OrElse (n = 0 AndAlso k > 0) Then Return 0 End If If n = k Then Return 1 End If If k > n Then Return 0 End If Return k * Sterling2(n - 1, k) + Sterling2(n - 1, k - 1) End Function Public Shared Function Sterling2(n As Integer, k As Integer) As BigInteger Dim key = CacheKey(n, k) If COMPUTED.ContainsKey(key) Then Return COMPUTED(key) End If Dim result = Impl(n, k) COMPUTED.Add(key, result) Return result End Function End Class Sub Main() Console.WriteLine("Stirling numbers of the second kind:") Dim max = 12 Console.Write("n/k") For n = 0 To max Console.Write("{0,10}", n) Next Console.WriteLine() For n = 0 To max Console.Write("{0,3}", n) For k = 0 To n Console.Write("{0,10}", Sterling.Sterling2(n, k)) Next Console.WriteLine() Next Console.WriteLine("The maximum value of S2(100, k) = ") Dim previous = BigInteger.Zero For k = 1 To 100 Dim current = Sterling.Sterling2(100, k) If current > previous Then previous = current Else Console.WriteLine(previous) Console.WriteLine("({0} digits, k = {1})", previous.ToString().Length, k - 1) Exit For End If Next End Sub End Module
Ensure the translated VB code behaves exactly like the original Java snippet.
import java.math.BigInteger; import java.util.HashMap; import java.util.Map; public class SterlingNumbersSecondKind { public static void main(String[] args) { System.out.println("Stirling numbers of the second kind:"); int max = 12; System.out.printf("n/k"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%10d", n); } System.out.printf("%n"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%-3d", n); for ( int k = 0 ; k <= n ; k++ ) { System.out.printf("%10s", sterling2(n, k)); } System.out.printf("%n"); } System.out.println("The maximum value of S2(100, k) = "); BigInteger previous = BigInteger.ZERO; for ( int k = 1 ; k <= 100 ; k++ ) { BigInteger current = sterling2(100, k); if ( current.compareTo(previous) > 0 ) { previous = current; } else { System.out.printf("%s%n(%d digits, k = %d)%n", previous, previous.toString().length(), k-1); break; } } } private static Map<String,BigInteger> COMPUTED = new HashMap<>(); private static final BigInteger sterling2(int n, int k) { String key = n + "," + k; if ( COMPUTED.containsKey(key) ) { return COMPUTED.get(key); } if ( n == 0 && k == 0 ) { return BigInteger.valueOf(1); } if ( (n > 0 && k == 0) || (n == 0 && k > 0) ) { return BigInteger.ZERO; } if ( n == k ) { return BigInteger.valueOf(1); } if ( k > n ) { return BigInteger.ZERO; } BigInteger result = BigInteger.valueOf(k).multiply(sterling2(n-1, k)).add(sterling2(n-1, k-1)); COMPUTED.put(key, result); return result; } }
Imports System.Numerics Module Module1 Class Sterling Private Shared ReadOnly COMPUTED As New Dictionary(Of String, BigInteger) Private Shared Function CacheKey(n As Integer, k As Integer) As String Return String.Format("{0}:{1}", n, k) End Function Private Shared Function Impl(n As Integer, k As Integer) As BigInteger If n = 0 AndAlso k = 0 Then Return 1 End If If (n > 0 AndAlso k = 0) OrElse (n = 0 AndAlso k > 0) Then Return 0 End If If n = k Then Return 1 End If If k > n Then Return 0 End If Return k * Sterling2(n - 1, k) + Sterling2(n - 1, k - 1) End Function Public Shared Function Sterling2(n As Integer, k As Integer) As BigInteger Dim key = CacheKey(n, k) If COMPUTED.ContainsKey(key) Then Return COMPUTED(key) End If Dim result = Impl(n, k) COMPUTED.Add(key, result) Return result End Function End Class Sub Main() Console.WriteLine("Stirling numbers of the second kind:") Dim max = 12 Console.Write("n/k") For n = 0 To max Console.Write("{0,10}", n) Next Console.WriteLine() For n = 0 To max Console.Write("{0,3}", n) For k = 0 To n Console.Write("{0,10}", Sterling.Sterling2(n, k)) Next Console.WriteLine() Next Console.WriteLine("The maximum value of S2(100, k) = ") Dim previous = BigInteger.Zero For k = 1 To 100 Dim current = Sterling.Sterling2(100, k) If current > previous Then previous = current Else Console.WriteLine(previous) Console.WriteLine("({0} digits, k = {1})", previous.ToString().Length, k - 1) Exit For End If Next End Sub End Module
Generate a VB translation of this Java snippet without changing its computational steps.
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class RecamanSequence { public static void main(String[] args) { List<Integer> a = new ArrayList<>(); a.add(0); Set<Integer> used = new HashSet<>(); used.add(0); Set<Integer> used1000 = new HashSet<>(); used1000.add(0); boolean foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a.get(n - 1) - n; if (next < 1 || used.contains(next)) { next += 2 * n; } boolean alreadyUsed = used.contains(next); a.add(next); if (!alreadyUsed) { used.add(next); if (0 <= next && next <= 1000) { used1000.add(next); } } if (n == 14) { System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a); } if (!foundDup && alreadyUsed) { System.out.printf("The first duplicate term is a[%d] = %d\n", n, next); foundDup = true; } if (used1000.size() == 1001) { System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } n++; } } }
nx=15 h=1000 Wscript.StdOut.WriteLine "Recaman Wscript.StdOut.WriteLine recaman("seq",nx) Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0) Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h) Wscript.StdOut.Write vbCrlf&".../...": zz=Wscript.StdIn.ReadLine() function recaman(op,nn) Dim b,d,h Set b = CreateObject("Scripting.Dictionary") Set d = CreateObject("Scripting.Dictionary") list="0" : firstdup=0 if op="firstdup" then nn=1000 : firstdup=1 end if if op="numterm" then h=nn : nn=10000000 : numterm=1 end if ax=0 b.Add 0,1 s=0 for n=1 to nn-1 an=ax-n if an<=0 then an=ax+n elseif b.Exists(an) then an=ax+n end if ax=an if not b.Exists(an) then b.Add an,1 if op="seq" then list=list&" "&an end if if firstdup then if d.Exists(an) then recaman="a("&n&")="&an exit function else d.Add an,1 end if end if if numterm then if an<=h then if not d.Exists(an) then s=s+1 d.Add an,1 end if if s>=h then recaman=n exit function end if end if end if next recaman=list end function
Rewrite the snippet below in VB so it works the same as the original Java code.
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class RecamanSequence { public static void main(String[] args) { List<Integer> a = new ArrayList<>(); a.add(0); Set<Integer> used = new HashSet<>(); used.add(0); Set<Integer> used1000 = new HashSet<>(); used1000.add(0); boolean foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a.get(n - 1) - n; if (next < 1 || used.contains(next)) { next += 2 * n; } boolean alreadyUsed = used.contains(next); a.add(next); if (!alreadyUsed) { used.add(next); if (0 <= next && next <= 1000) { used1000.add(next); } } if (n == 14) { System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a); } if (!foundDup && alreadyUsed) { System.out.printf("The first duplicate term is a[%d] = %d\n", n, next); foundDup = true; } if (used1000.size() == 1001) { System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n); } n++; } } }
nx=15 h=1000 Wscript.StdOut.WriteLine "Recaman Wscript.StdOut.WriteLine recaman("seq",nx) Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0) Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h) Wscript.StdOut.Write vbCrlf&".../...": zz=Wscript.StdIn.ReadLine() function recaman(op,nn) Dim b,d,h Set b = CreateObject("Scripting.Dictionary") Set d = CreateObject("Scripting.Dictionary") list="0" : firstdup=0 if op="firstdup" then nn=1000 : firstdup=1 end if if op="numterm" then h=nn : nn=10000000 : numterm=1 end if ax=0 b.Add 0,1 s=0 for n=1 to nn-1 an=ax-n if an<=0 then an=ax+n elseif b.Exists(an) then an=ax+n end if ax=an if not b.Exists(an) then b.Add an,1 if op="seq" then list=list&" "&an end if if firstdup then if d.Exists(an) then recaman="a("&n&")="&an exit function else d.Add an,1 end if end if if numterm then if an<=h then if not d.Exists(an) then s=s+1 d.Add an,1 end if if s>=h then recaman=n exit function end if end if end if next recaman=list end function
Port the provided Java code into VB while preserving the original functionality.
public class Count{ public static void main(String[] args){ for(long i = 1; ;i++) System.out.println(i); } }
For i As Integer = 0 To Integer.MaxValue Console.WriteLine(i) Next
Translate this program into VB but keep the logic exactly as in Java.
public class Count{ public static void main(String[] args){ for(long i = 1; ;i++) System.out.println(i); } }
For i As Integer = 0 To Integer.MaxValue Console.WriteLine(i) Next
Produce a language-to-language conversion: from Java to VB, same semantics.
import java.net.InetAddress; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.UnknownHostException; class DnsQuery { public static void main(String[] args) { try { InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net"); for(int i=0; i < ipAddr.length ; i++) { if (ipAddr[i] instanceof Inet4Address) { System.out.println("IPv4 : " + ipAddr[i].getHostAddress()); } else if (ipAddr[i] instanceof Inet6Address) { System.out.println("IPv6 : " + ipAddr[i].getHostAddress()); } } } catch (UnknownHostException uhe) { System.err.println("unknown host"); } } }
Function dns_query(url,ver) Set r = New RegExp r.Pattern = "Pinging.+?\[(.+?)\].+" Set objshell = CreateObject("WScript.Shell") Set objexec = objshell.Exec("%comspec% /c " & "ping -" & ver & " " & url) WScript.StdOut.WriteLine "URL: " & url Do Until objexec.StdOut.AtEndOfStream line = objexec.StdOut.ReadLine If r.Test(line) Then WScript.StdOut.WriteLine "IP Version " &_ ver & ": " & r.Replace(line,"$1") End If Loop End Function Call dns_query(WScript.Arguments(0),WScript.Arguments(1))
Can you help me rewrite this code in VB instead of Java, keeping it the same logically?
import java.io.*; public class PeanoCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("peano_curve.svg"))) { PeanoCurve s = new PeanoCurve(writer); final int length = 8; s.currentAngle = 90; s.currentX = length; s.currentY = length; s.lineLength = length; s.begin(656); s.execute(rewrite(4)); s.end(); } catch (final Exception ex) { ex.printStackTrace(); } } private PeanoCurve(final Writer writer) { this.writer = writer; } private void begin(final int size) throws IOException { write("<svg xmlns='http: write("<rect width='100%%' height='100%%' fill='white'/>\n"); write("<path stroke-width='1' stroke='black' fill='none' d='"); } private void end() throws IOException { write("'/>\n</svg>\n"); } private void execute(final String s) throws IOException { write("M%g,%g\n", currentX, currentY); for (int i = 0, n = s.length(); i < n; ++i) { switch (s.charAt(i)) { case 'F': line(lineLength); break; case '+': turn(ANGLE); break; case '-': turn(-ANGLE); break; } } } private void line(final double length) throws IOException { final double theta = (Math.PI * currentAngle) / 180.0; currentX += length * Math.cos(theta); currentY += length * Math.sin(theta); write("L%g,%g\n", currentX, currentY); } private void turn(final int angle) { currentAngle = (currentAngle + angle) % 360; } private void write(final String format, final Object... args) throws IOException { writer.write(String.format(format, args)); } private static String rewrite(final int order) { String s = "L"; for (int i = 0; i < order; ++i) { final StringBuilder sb = new StringBuilder(); for (int j = 0, n = s.length(); j < n; ++j) { final char ch = s.charAt(j); if (ch == 'L') sb.append("LFRFL-F-RFLFR+F+LFRFL"); else if (ch == 'R') sb.append("RFLFR+F+LFRFL-F-RFLFR"); else sb.append(ch); } s = sb.toString(); } return s; } private final Writer writer; private double lineLength; private double currentX; private double currentY; private int currentAngle; private static final int ANGLE = 90; }
Const WIDTH = 243 Dim n As Long Dim points() As Single Dim flag As Boolean Private Sub lineto(x As Integer, y As Integer) If flag Then points(n, 1) = x points(n, 2) = y End If n = n + 1 End Sub Private Sub Peano(ByVal x As Integer, ByVal y As Integer, ByVal lg As Integer, _ ByVal i1 As Integer, ByVal i2 As Integer) If (lg = 1) Then Call lineto(x * 3, y * 3) Exit Sub End If lg = lg / 3 Call Peano(x + (2 * i1 * lg), y + (2 * i1 * lg), lg, i1, i2) Call Peano(x + ((i1 - i2 + 1) * lg), y + ((i1 + i2) * lg), lg, i1, 1 - i2) Call Peano(x + lg, y + lg, lg, i1, 1 - i2) Call Peano(x + ((i1 + i2) * lg), y + ((i1 - i2 + 1) * lg), lg, 1 - i1, 1 - i2) Call Peano(x + (2 * i2 * lg), y + (2 * (1 - i2) * lg), lg, i1, i2) Call Peano(x + ((1 + i2 - i1) * lg), y + ((2 - i1 - i2) * lg), lg, i1, i2) Call Peano(x + (2 * (1 - i1) * lg), y + (2 * (1 - i1) * lg), lg, i1, i2) Call Peano(x + ((2 - i1 - i2) * lg), y + ((1 + i2 - i1) * lg), lg, 1 - i1, i2) Call Peano(x + (2 * (1 - i2) * lg), y + (2 * i2 * lg), lg, 1 - i1, i2) End Sub Sub main() n = 1: flag = False Call Peano(0, 0, WIDTH, 0, 0) ReDim points(1 To n - 1, 1 To 2) n = 1: flag = True Call Peano(0, 0, WIDTH, 0, 0) ActiveSheet.Shapes.AddPolyline points End Sub
Keep all operations the same but rewrite the snippet in VB.
import java.util.Random; public class SevenSidedDice { private static final Random rnd = new Random(); public static void main(String[] args) { SevenSidedDice now=new SevenSidedDice(); System.out.println("Random number from 1 to 7: "+now.seven()); } int seven() { int v=21; while(v>20) v=five()+five()*5-6; return 1+v%7; } int five() { return 1+rnd.nextInt(5); } }
Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean Dim Total As Long, Ei As Long, i As Integer Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double Debug.Print "[1] ""Data set:"" "; For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies) Total = Total + ObservationFrequencies(i) Debug.Print ObservationFrequencies(i); " "; Next i DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies) Ei = Total / (DegreesOfFreedom + 1) For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies) ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei Next i p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True) Debug.Print Debug.Print "Chi-squared test for given frequencies" Debug.Print "X-squared ="; Format(ChiSquared, "0.0000"); ", "; Debug.Print "df ="; DegreesOfFreedom; ", "; Debug.Print "p-value = "; Format(p_value, "0.0000") Test4DiscreteUniformDistribution = p_value > Significance End Function Private Function Dice5() As Integer Dice5 = Int(5 * Rnd + 1) End Function Private Function Dice7() As Integer Dim i As Integer Do i = 5 * (Dice5 - 1) + Dice5 Loop While i > 21 Dice7 = i Mod 7 + 1 End Function Sub TestDice7() Dim i As Long, roll As Integer Dim Bins(1 To 7) As Variant For i = 1 To 1000000 roll = Dice7 Bins(roll) = Bins(roll) + 1 Next i Debug.Print "[1] ""Uniform? "; Test4DiscreteUniformDistribution(Bins, 0.05); """" End Sub
Change the programming language of this snippet from Java to VB without modifying what it does.
import java.util.ArrayList; import java.util.List; public class MagnanimousNumbers { public static void main(String[] args) { runTask("Find and display the first 45 magnanimous numbers.", 1, 45); runTask("241st through 250th magnanimous numbers.", 241, 250); runTask("391st through 400th magnanimous numbers.", 391, 400); } private static void runTask(String message, int startN, int endN) { int count = 0; List<Integer> nums = new ArrayList<>(); for ( int n = 0 ; count < endN ; n++ ) { if ( isMagnanimous(n) ) { nums.add(n); count++; } } System.out.printf("%s%n", message); System.out.printf("%s%n%n", nums.subList(startN-1, endN)); } private static boolean isMagnanimous(long n) { if ( n >= 0 && n <= 9 ) { return true; } long q = 11; for ( long div = 10 ; q >= 10 ; div *= 10 ) { q = n / div; long r = n % div; if ( ! isPrime(q+r) ) { return false; } } return true; } private static final int MAX = 100_000; private static final boolean[] primes = new boolean[MAX]; private static boolean SIEVE_COMPLETE = false; private static final boolean isPrimeTrivial(long test) { if ( ! SIEVE_COMPLETE ) { sieve(); SIEVE_COMPLETE = true; } return primes[(int) test]; } private static final void sieve() { for ( int i = 2 ; i < MAX ; i++ ) { primes[i] = true; } for ( int i = 2 ; i < MAX ; i++ ) { if ( primes[i] ) { for ( int j = 2*i ; j < MAX ; j += i ) { primes[j] = false; } } } } public static final boolean isPrime(long testValue) { if ( testValue == 2 ) return true; if ( testValue % 2 == 0 ) return false; if ( testValue <= MAX ) return isPrimeTrivial(testValue); long d = testValue-1; int s = 0; while ( d % 2 == 0 ) { s += 1; d /= 2; } if ( testValue < 1373565L ) { if ( ! aSrp(2, s, d, testValue) ) { return false; } if ( ! aSrp(3, s, d, testValue) ) { return false; } return true; } if ( testValue < 4759123141L ) { if ( ! aSrp(2, s, d, testValue) ) { return false; } if ( ! aSrp(7, s, d, testValue) ) { return false; } if ( ! aSrp(61, s, d, testValue) ) { return false; } return true; } if ( testValue < 10000000000000000L ) { if ( ! aSrp(3, s, d, testValue) ) { return false; } if ( ! aSrp(24251, s, d, testValue) ) { return false; } return true; } if ( ! aSrp(37, s, d, testValue) ) { return false; } if ( ! aSrp(47, s, d, testValue) ) { return false; } if ( ! aSrp(61, s, d, testValue) ) { return false; } if ( ! aSrp(73, s, d, testValue) ) { return false; } if ( ! aSrp(83, s, d, testValue) ) { return false; } return true; } private static final boolean aSrp(int a, int s, long d, long n) { long modPow = modPow(a, d, n); if ( modPow == 1 ) { return true; } int twoExpR = 1; for ( int r = 0 ; r < s ; r++ ) { if ( modPow(modPow, twoExpR, n) == n-1 ) { return true; } twoExpR *= 2; } return false; } private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE); public static final long modPow(long base, long exponent, long modulus) { long result = 1; while ( exponent > 0 ) { if ( exponent % 2 == 1 ) { if ( result > SQRT || base > SQRT ) { result = multiply(result, base, modulus); } else { result = (result * base) % modulus; } } exponent >>= 1; if ( base > SQRT ) { base = multiply(base, base, modulus); } else { base = (base * base) % modulus; } } return result; } public static final long multiply(long a, long b, long modulus) { long x = 0; long y = a % modulus; long t; while ( b > 0 ) { if ( b % 2 == 1 ) { t = x + y; x = (t > modulus ? t-modulus : t); } t = y << 1; y = (t > modulus ? t-modulus : t); b >>= 1; } return x % modulus; } }
Imports System, System.Console Module Module1 Dim np As Boolean() Sub ms(ByVal lmt As Long) np = New Boolean(CInt(lmt)) {} : np(0) = True : np(1) = True Dim n As Integer = 2, j As Integer = 1 : While n < lmt If Not np(n) Then Dim k As Long = CLng(n) * n While k < lmt : np(CInt(k)) = True : k += n : End While End If : n += j : j = 2 : End While End Sub Function is_Mag(ByVal n As Integer) As Boolean Dim res, rm As Integer, p As Integer = 10 While n >= p res = Math.DivRem(n, p, rm) If np(res + rm) Then Return False p = p * 10 : End While : Return True End Function Sub Main(ByVal args As String()) ms(100_009) : Dim mn As String = " magnanimous numbers:" WriteLine("First 45{0}", mn) : Dim l As Integer = 0, c As Integer = 0 While c < 400 : If is_Mag(l) Then c += 1 : If c <= 45 OrElse (c > 240 AndAlso c <= 250) OrElse c > 390 Then Write(If(c <= 45, "{0,4} ", "{0,8:n0} "), l) If c < 45 AndAlso c Mod 15 = 0 Then WriteLine() If c = 240 Then WriteLine(vbLf & vbLf & "241st through 250th{0}", mn) If c = 390 Then WriteLine(vbLf & vbLf & "391st through 400th{0}", mn) End If : l += 1 : End While End Sub End Module
Generate an equivalent VB version of this Java code.
import java.util.*; public class PrimeGenerator { private int limit_; private int index_ = 0; private int increment_; private int count_ = 0; private List<Integer> primes_ = new ArrayList<>(); private BitSet sieve_ = new BitSet(); private int sieveLimit_ = 0; public PrimeGenerator(int initialLimit, int increment) { limit_ = nextOddNumber(initialLimit); increment_ = increment; primes_.add(2); findPrimes(3); } public int nextPrime() { if (index_ == primes_.size()) { if (Integer.MAX_VALUE - increment_ < limit_) return 0; int start = limit_ + 2; limit_ = nextOddNumber(limit_ + increment_); primes_.clear(); findPrimes(start); } ++count_; return primes_.get(index_++); } public int count() { return count_; } private void findPrimes(int start) { index_ = 0; int newLimit = sqrt(limit_); for (int p = 3; p * p <= newLimit; p += 2) { if (sieve_.get(p/2 - 1)) continue; int q = p * Math.max(p, nextOddNumber((sieveLimit_ + p - 1)/p)); for (; q <= newLimit; q += 2*p) sieve_.set(q/2 - 1, true); } sieveLimit_ = newLimit; int count = (limit_ - start)/2 + 1; BitSet composite = new BitSet(count); for (int p = 3; p <= newLimit; p += 2) { if (sieve_.get(p/2 - 1)) continue; int q = p * Math.max(p, nextOddNumber((start + p - 1)/p)) - start; q /= 2; for (; q >= 0 && q < count; q += p) composite.set(q, true); } for (int p = 0; p < count; ++p) { if (!composite.get(p)) primes_.add(p * 2 + start); } } private static int sqrt(int n) { return nextOddNumber((int)Math.sqrt(n)); } private static int nextOddNumber(int n) { return 1 + 2 * (n/2); } public static void main(String[] args) { PrimeGenerator pgen = new PrimeGenerator(20, 200000); System.out.println("First 20 primes:"); for (int i = 0; i < 20; ++i) { if (i > 0) System.out.print(", "); System.out.print(pgen.nextPrime()); } System.out.println(); System.out.println("Primes between 100 and 150:"); for (int i = 0; ; ) { int prime = pgen.nextPrime(); if (prime > 150) break; if (prime >= 100) { if (i++ != 0) System.out.print(", "); System.out.print(prime); } } System.out.println(); int count = 0; for (;;) { int prime = pgen.nextPrime(); if (prime > 8000) break; if (prime >= 7700) ++count; } System.out.println("Number of primes between 7700 and 8000: " + count); int n = 10000; for (;;) { int prime = pgen.nextPrime(); if (prime == 0) { System.out.println("Can't generate any more primes."); break; } if (pgen.count() == n) { System.out.println(n + "th prime: " + prime); n *= 10; } } } }
Option Explicit Sub Main() Dim Primes() As Long, n As Long, temp$ Dim t As Single t = Timer n = 133218295 Primes = ListPrimes(n) Debug.Print "For N = " & Format(n, "#,##0") & ", execution time : " & _ Format(Timer - t, "0.000 s") & ", " & _ Format(UBound(Primes) + 1, "#,##0") & " primes numbers." For n = 0 To 19 temp = temp & ", " & Primes(n) Next Debug.Print "First twenty primes : "; Mid(temp, 3) n = 0: temp = vbNullString Do While Primes(n) < 100 n = n + 1 Loop Do While Primes(n) < 150 temp = temp & ", " & Primes(n) n = n + 1 Loop Debug.Print "Primes between 100 and 150 : " & Mid(temp, 3) Dim ccount As Long n = 0 Do While Primes(n) < 7700 n = n + 1 Loop Do While Primes(n) < 8000 ccount = ccount + 1 n = n + 1 Loop Debug.Print "Number of primes between 7,700 and 8,000 : " & ccount n = 1 Do While n <= 100000 n = n * 10 Debug.Print "The " & n & "th prime: "; Format(Primes(n - 1), "#,##0") Loop Debug.Print "VBA has a limit in array Debug.Print "With my computer, the limit for an array of Long is : 133 218 295" Debug.Print "The last prime I could find is the : " & _ Format(UBound(Primes), "#,##0") & "th, Value : " & _ Format(Primes(UBound(Primes)), "#,##0") End Sub Function ListPrimes(MAX As Long) As Long() Dim t() As Boolean, L() As Long, c As Long, s As Long, i As Long, j As Long ReDim t(2 To MAX) ReDim L(MAX \ 2) s = Sqr(MAX) For i = 3 To s Step 2 If t(i) = False Then For j = i * i To MAX Step i t(j) = True Next End If Next i L(0) = 2 For i = 3 To MAX Step 2 If t(i) = False Then c = c + 1 L(c) = i End If Next i ReDim Preserve L(c) ListPrimes = L End Function
Translate the given Java code snippet into VB without altering its behavior.
import java.util.Scanner; public class twoDimArray { public static void main(String[] args) { Scanner in = new Scanner(System.in); int nbr1 = in.nextInt(); int nbr2 = in.nextInt(); double[][] array = new double[nbr1][nbr2]; array[0][0] = 42.0; System.out.println("The number at place [0 0] is " + array[0][0]); } }
Module Program Sub Main() Console.WriteLine("Enter two space-delimited integers:") Dim input = Console.ReadLine().Split() Dim rows = Integer.Parse(input(0)) Dim cols = Integer.Parse(input(1)) Dim arr(rows - 1, cols - 1) As Integer arr(0, 0) = 2 Console.WriteLine(arr(0, 0)) End Sub End Module
Write the same algorithm in VB as shown in this Java implementation.
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1; if (b == 1) return 1; while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(n, a)); } }
Private Function chinese_remainder(n As Variant, a As Variant) As Variant Dim p As Long, prod As Long, tot As Long prod = 1: tot = 0 For i = 1 To UBound(n) prod = prod * n(i) Next i Dim m As Variant For i = 1 To UBound(n) p = prod / n(i) m = mul_inv(p, n(i)) If WorksheetFunction.IsText(m) Then chinese_remainder = "fail" Exit Function End If tot = tot + a(i) * m * p Next i chinese_remainder = tot Mod prod End Function Public Sub re() Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}]) Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}]) Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}]) Debug.Print chinese_remainder([{100,23}], [{19,0}]) End Sub
Can you help me rewrite this code in VB instead of Java, keeping it the same logically?
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1; if (b == 1) return 1; while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(n, a)); } }
Private Function chinese_remainder(n As Variant, a As Variant) As Variant Dim p As Long, prod As Long, tot As Long prod = 1: tot = 0 For i = 1 To UBound(n) prod = prod * n(i) Next i Dim m As Variant For i = 1 To UBound(n) p = prod / n(i) m = mul_inv(p, n(i)) If WorksheetFunction.IsText(m) Then chinese_remainder = "fail" Exit Function End If tot = tot + a(i) * m * p Next i chinese_remainder = tot Mod prod End Function Public Sub re() Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}]) Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}]) Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}]) Debug.Print chinese_remainder([{100,23}], [{19,0}]) End Sub
Can you help me rewrite this code in VB instead of Java, keeping it the same logically?
import java.math.BigInteger ; public class Pi { final BigInteger TWO = BigInteger.valueOf(2) ; final BigInteger THREE = BigInteger.valueOf(3) ; final BigInteger FOUR = BigInteger.valueOf(4) ; final BigInteger SEVEN = BigInteger.valueOf(7) ; BigInteger q = BigInteger.ONE ; BigInteger r = BigInteger.ZERO ; BigInteger t = BigInteger.ONE ; BigInteger k = BigInteger.ONE ; BigInteger n = BigInteger.valueOf(3) ; BigInteger l = BigInteger.valueOf(3) ; public void calcPiDigits(){ BigInteger nn, nr ; boolean first = true ; while(true){ if(FOUR.multiply(q).add(r).subtract(t).compareTo(n.multiply(t)) == -1){ System.out.print(n) ; if(first){System.out.print(".") ; first = false ;} nr = BigInteger.TEN.multiply(r.subtract(n.multiply(t))) ; n = BigInteger.TEN.multiply(THREE.multiply(q).add(r)).divide(t).subtract(BigInteger.TEN.multiply(n)) ; q = q.multiply(BigInteger.TEN) ; r = nr ; System.out.flush() ; }else{ nr = TWO.multiply(q).add(r).multiply(l) ; nn = q.multiply((SEVEN.multiply(k))).add(TWO).add(r.multiply(l)).divide(t.multiply(l)) ; q = q.multiply(k) ; t = t.multiply(l) ; l = l.add(TWO) ; k = k.add(BigInteger.ONE) ; n = nn ; r = nr ; } } } public static void main(String[] args) { Pi p = new Pi() ; p.calcPiDigits() ; } }
Option Explicit Sub Main() Const VECSIZE As Long = 3350 Const BUFSIZE As Long = 201 Dim buffer(1 To BUFSIZE) As Long Dim vect(1 To VECSIZE) As Long Dim more As Long, karray As Long, num As Long, k As Long, l As Long, n As Long For n = 1 To VECSIZE vect(n) = 2 Next n For n = 1 To BUFSIZE karray = 0 For l = VECSIZE To 1 Step -1 num = 100000 * vect(l) + karray * l karray = num \ (2 * l - 1) vect(l) = num - karray * (2 * l - 1) Next l k = karray \ 100000 buffer(n) = more + k more = karray - k * 100000 Next n Debug.Print CStr(buffer(1)); Debug.Print "." l = 0 For n = 2 To BUFSIZE Debug.Print Format$(buffer(n), "00000"); l = l + 1 If l = 10 Then l = 0 Debug.Print End If Next n End Sub
Port the provided Java code into VB while preserving the original functionality.
import java.util.HashMap; import java.util.Map; public class HofQ { private static Map<Integer, Integer> q = new HashMap<Integer, Integer>(){{ put(1, 1); put(2, 1); }}; private static int[] nUses = new int[100001]; public static int Q(int n){ nUses[n]++; if(q.containsKey(n)){ return q.get(n); } int ans = Q(n - Q(n - 1)) + Q(n - Q(n - 2)); q.put(n, ans); return ans; } public static void main(String[] args){ for(int i = 1; i <= 10; i++){ System.out.println("Q(" + i + ") = " + Q(i)); } int last = 6; int count = 0; for(int i = 11; i <= 100000; i++){ int curr = Q(i); if(curr < last) count++; last = curr; if(i == 1000) System.out.println("Q(1000) = " + curr); } System.out.println("Q(i) is less than Q(i-1) for i <= 100000 " + count + " times"); int maxUses = 0, maxN = 0; for(int i = 1; i<nUses.length;i++){ if(nUses[i] > maxUses){ maxUses = nUses[i]; maxN = i; } } System.out.println("Q(" + maxN + ") was called the most with " + maxUses + " calls"); } }
Public Q(100000) As Long Public Sub HofstadterQ() Dim n As Long, smaller As Long Q(1) = 1 Q(2) = 1 For n = 3 To 100000 Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2)) If Q(n) < Q(n - 1) Then smaller = smaller + 1 Next n Debug.Print "First ten terms:" For i = 1 To 10 Debug.Print Q(i); Next i Debug.print Debug.Print "The 1000th term is:"; Q(1000) Debug.Print "Number of times smaller:"; smaller End Sub
Translate this program into VB but keep the logic exactly as in Java.
import java.util.HashMap; import java.util.Map; public class HofQ { private static Map<Integer, Integer> q = new HashMap<Integer, Integer>(){{ put(1, 1); put(2, 1); }}; private static int[] nUses = new int[100001]; public static int Q(int n){ nUses[n]++; if(q.containsKey(n)){ return q.get(n); } int ans = Q(n - Q(n - 1)) + Q(n - Q(n - 2)); q.put(n, ans); return ans; } public static void main(String[] args){ for(int i = 1; i <= 10; i++){ System.out.println("Q(" + i + ") = " + Q(i)); } int last = 6; int count = 0; for(int i = 11; i <= 100000; i++){ int curr = Q(i); if(curr < last) count++; last = curr; if(i == 1000) System.out.println("Q(1000) = " + curr); } System.out.println("Q(i) is less than Q(i-1) for i <= 100000 " + count + " times"); int maxUses = 0, maxN = 0; for(int i = 1; i<nUses.length;i++){ if(nUses[i] > maxUses){ maxUses = nUses[i]; maxN = i; } } System.out.println("Q(" + maxN + ") was called the most with " + maxUses + " calls"); } }
Public Q(100000) As Long Public Sub HofstadterQ() Dim n As Long, smaller As Long Q(1) = 1 Q(2) = 1 For n = 3 To 100000 Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2)) If Q(n) < Q(n - 1) Then smaller = smaller + 1 Next n Debug.Print "First ten terms:" For i = 1 To 10 Debug.Print Q(i); Next i Debug.print Debug.Print "The 1000th term is:"; Q(1000) Debug.Print "Number of times smaller:"; smaller End Sub
Can you help me rewrite this code in VB instead of Java, keeping it the same logically?
import java.util.function.Function; public interface YCombinator { interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { } public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) { RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x)); return r.apply(r); } public static void main(String... arguments) { Function<Integer,Integer> fib = Y(f -> n -> (n <= 2) ? 1 : (f.apply(n - 1) + f.apply(n - 2)) ); Function<Integer,Integer> fac = Y(f -> n -> (n <= 1) ? 1 : (n * f.apply(n - 1)) ); System.out.println("fib(10) = " + fib.apply(10)); System.out.println("fac(10) = " + fac.apply(10)); } }
Private Function call_fn(f As String, n As Long) As Long call_fn = Application.Run(f, f, n) End Function Private Function Y(f As String) As String Y = f End Function Private Function fac(self As String, n As Long) As Long If n > 1 Then fac = n * call_fn(self, n - 1) Else fac = 1 End If End Function Private Function fib(self As String, n As Long) As Long If n > 1 Then fib = call_fn(self, n - 1) + call_fn(self, n - 2) Else fib = n End If End Function Private Sub test(name As String) Dim f As String: f = Y(name) Dim i As Long Debug.Print name For i = 1 To 10 Debug.Print call_fn(f, i); Next i Debug.Print End Sub Public Sub main() test "fac" test "fib" End Sub
Write the same algorithm in VB as shown in this Java implementation.
import java.util.function.Function; public interface YCombinator { interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { } public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) { RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x)); return r.apply(r); } public static void main(String... arguments) { Function<Integer,Integer> fib = Y(f -> n -> (n <= 2) ? 1 : (f.apply(n - 1) + f.apply(n - 2)) ); Function<Integer,Integer> fac = Y(f -> n -> (n <= 1) ? 1 : (n * f.apply(n - 1)) ); System.out.println("fib(10) = " + fib.apply(10)); System.out.println("fac(10) = " + fac.apply(10)); } }
Private Function call_fn(f As String, n As Long) As Long call_fn = Application.Run(f, f, n) End Function Private Function Y(f As String) As String Y = f End Function Private Function fac(self As String, n As Long) As Long If n > 1 Then fac = n * call_fn(self, n - 1) Else fac = 1 End If End Function Private Function fib(self As String, n As Long) As Long If n > 1 Then fib = call_fn(self, n - 1) + call_fn(self, n - 2) Else fib = n End If End Function Private Sub test(name As String) Dim f As String: f = Y(name) Dim i As Long Debug.Print name For i = 1 To 10 Debug.Print call_fn(f, i); Next i Debug.Print End Sub Public Sub main() test "fac" test "fib" End Sub
Generate a VB translation of this Java snippet without changing its computational steps.
import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; public class RReturnMultipleVals { public static final String K_lipsum = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."; public static final Long K_1024 = 1024L; public static final String L = "L"; public static final String R = "R"; public static void main(String[] args) throws NumberFormatException{ Long nv_; String sv_; switch (args.length) { case 0: nv_ = K_1024; sv_ = K_lipsum; break; case 1: nv_ = Long.parseLong(args[0]); sv_ = K_lipsum; break; case 2: nv_ = Long.parseLong(args[0]); sv_ = args[1]; break; default: nv_ = Long.parseLong(args[0]); sv_ = args[1]; for (int ix = 2; ix < args.length; ++ix) { sv_ = sv_ + " " + args[ix]; } break; } RReturnMultipleVals lcl = new RReturnMultipleVals(); Pair<Long, String> rvp = lcl.getPairFromPair(nv_, sv_); System.out.println("Results extracted from a composite object:"); System.out.printf("%s, %s%n%n", rvp.getLeftVal(), rvp.getRightVal()); List<Object> rvl = lcl.getPairFromList(nv_, sv_); System.out.println("Results extracted from a Java Colections \"List\" object:"); System.out.printf("%s, %s%n%n", rvl.get(0), rvl.get(1)); Map<String, Object> rvm = lcl.getPairFromMap(nv_, sv_); System.out.println("Results extracted from a Java Colections \"Map\" object:"); System.out.printf("%s, %s%n%n", rvm.get(L), rvm.get(R)); } public <T, U> Pair<T, U> getPairFromPair(T vl_, U vr_) { return new Pair<T, U>(vl_, vr_); } public List<Object> getPairFromList(Object nv_, Object sv_) { List<Object> rset = new ArrayList<Object>(); rset.add(nv_); rset.add(sv_); return rset; } public Map<String, Object> getPairFromMap(Object nv_, Object sv_) { Map<String, Object> rset = new HashMap<String, Object>(); rset.put(L, nv_); rset.put(R, sv_); return rset; } private static class Pair<L, R> { private L leftVal; private R rightVal; public Pair(L nv_, R sv_) { setLeftVal(nv_); setRightVal(sv_); } public void setLeftVal(L nv_) { leftVal = nv_; } public L getLeftVal() { return leftVal; } public void setRightVal(R sv_) { rightVal = sv_; } public R getRightVal() { return rightVal; } } }
Type Contact Name As String firstname As String Age As Byte End Type Function SetContact(N As String, Fn As String, A As Byte) As Contact SetContact.Name = N SetContact.firstname = Fn SetContact.Age = A End Function Sub Test_SetContact() Dim Cont As Contact Cont = SetContact("SMITH", "John", 23) Debug.Print Cont.Name & " " & Cont.firstname & ", " & Cont.Age & " years old." End Sub
Change the following Java code into VB without altering its purpose.
import java.util.HashMap; import java.util.Map; public class VanEckSequence { public static void main(String[] args) { System.out.println("First 10 terms of Van Eck's sequence:"); vanEck(1, 10); System.out.println(""); System.out.println("Terms 991 to 1000 of Van Eck's sequence:"); vanEck(991, 1000); } private static void vanEck(int firstIndex, int lastIndex) { Map<Integer,Integer> vanEckMap = new HashMap<>(); int last = 0; if ( firstIndex == 1 ) { System.out.printf("VanEck[%d] = %d%n", 1, 0); } for ( int n = 2 ; n <= lastIndex ; n++ ) { int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0; vanEckMap.put(last, n); last = vanEck; if ( n >= firstIndex ) { System.out.printf("VanEck[%d] = %d%n", n, vanEck); } } } }
Imports System.Linq Module Module1 Dim h() As Integer Sub sho(i As Integer) Console.WriteLine(String.Join(" ", h.Skip(i).Take(10))) End Sub Sub Main() Dim a, b, c, d, f, g As Integer : g = 1000 h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g f = h(b) : For d = a To 0 Step -1 If f = h(d) Then h(c) = b - d: Exit For Next : a = b : b = c : Next : sho(0) : sho(990) End Sub End Module
Write the same algorithm in VB as shown in this Java implementation.
import java.util.HashMap; import java.util.Map; public class VanEckSequence { public static void main(String[] args) { System.out.println("First 10 terms of Van Eck's sequence:"); vanEck(1, 10); System.out.println(""); System.out.println("Terms 991 to 1000 of Van Eck's sequence:"); vanEck(991, 1000); } private static void vanEck(int firstIndex, int lastIndex) { Map<Integer,Integer> vanEckMap = new HashMap<>(); int last = 0; if ( firstIndex == 1 ) { System.out.printf("VanEck[%d] = %d%n", 1, 0); } for ( int n = 2 ; n <= lastIndex ; n++ ) { int vanEck = vanEckMap.containsKey(last) ? n - vanEckMap.get(last) : 0; vanEckMap.put(last, n); last = vanEck; if ( n >= firstIndex ) { System.out.printf("VanEck[%d] = %d%n", n, vanEck); } } } }
Imports System.Linq Module Module1 Dim h() As Integer Sub sho(i As Integer) Console.WriteLine(String.Join(" ", h.Skip(i).Take(10))) End Sub Sub Main() Dim a, b, c, d, f, g As Integer : g = 1000 h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g f = h(b) : For d = a To 0 Step -1 If f = h(d) Then h(c) = b - d: Exit For Next : a = b : b = c : Next : sho(0) : sho(990) End Sub End Module
Translate the given Java code snippet into VB without altering its behavior.
import java.util.*; public class Game24 { static Random r = new Random(); public static void main(String[] args) { int[] digits = randomDigits(); Scanner in = new Scanner(System.in); System.out.print("Make 24 using these digits: "); System.out.println(Arrays.toString(digits)); System.out.print("> "); Stack<Float> s = new Stack<>(); long total = 0; for (char c : in.nextLine().toCharArray()) { if ('0' <= c && c <= '9') { int d = c - '0'; total += (1 << (d * 5)); s.push((float) d); } else if ("+/-*".indexOf(c) != -1) { s.push(applyOperator(s.pop(), s.pop(), c)); } } if (tallyDigits(digits) != total) System.out.print("Not the same digits. "); else if (Math.abs(24 - s.peek()) < 0.001F) System.out.println("Correct!"); else System.out.print("Not correct."); } static float applyOperator(float a, float b, char c) { switch (c) { case '+': return a + b; case '-': return b - a; case '*': return a * b; case '/': return b / a; default: return Float.NaN; } } static long tallyDigits(int[] a) { long total = 0; for (int i = 0; i < 4; i++) total += (1 << (a[i] * 5)); return total; } static int[] randomDigits() { int[] result = new int[4]; for (int i = 0; i < 4; i++) result[i] = r.nextInt(9) + 1; return result; } }
Sub Rosetta_24game() Dim Digit(4) As Integer, i As Integer, iDigitCount As Integer Dim stUserExpression As String Dim stFailMessage As String, stFailDigits As String Dim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean Dim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant GenerateNewDigits: For i = 1 To 4 Digit(i) = [randbetween(1,9)] Next i GetUserExpression: bValidExpression = True stFailMessage = "" stFailDigits = "" stUserExpression = InputBox("Enter a mathematical expression which results in 24, using the following digits: " & _ Digit(1) & ", " & Digit(2) & ", " & Digit(3) & " and " & Digit(4), "Rosetta Code | 24 Game") bValidDigits = True stFailDigits = "" For i = 1 To 4 If InStr(stUserExpression, Digit(i)) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & Digit(i) End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = "Your expression excluded the following required digits: " & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" For i = 1 To Len(stUserExpression) If InStr("0123456789+-*/()", Mid(stUserExpression, i, 1)) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1) End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid characters:" & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" iDigitCount = 0 For i = 1 To Len(stUserExpression) If Not InStr("0123456789", Mid(stUserExpression, i, 1)) = 0 Then iDigitCount = iDigitCount + 1 If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then bValidDigits = False stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1) End If End If Next i If iDigitCount > 4 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained more than 4 digits" & vbCr & vbCr End If If iDigitCount < 4 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained less than 4 digits" & vbCr & vbCr End If If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid digits:" & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" For i = 11 To 99 If Not InStr(stUserExpression, i) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & i End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid numbers:" & stFailDigits & vbCr & vbCr End If On Error GoTo EvalFail vResult = Evaluate(stUserExpression) If Not vResult = 24 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression did not result in 24. It returned: " & vResult End If If bValidExpression = False Then vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & "Would you like to try again?", vbCritical + vbRetryCancel, "Rosetta Code | 24 Game | FAILED") If vTryAgain = vbRetry Then vSameDigits = MsgBox("Do you want to use the same numbers?", vbQuestion + vbYesNo, "Rosetta Code | 24 Game | RETRY") If vSameDigits = vbYes Then GoTo GetUserExpression Else GoTo GenerateNewDigits End If End If Else vTryAgain = MsgBox("You entered: " & stUserExpression & vbCr & vbCr & "which resulted in: " & vResult, _ vbInformation + vbRetryCancel, "Rosetta Code | 24 Game | SUCCESS") If vTryAgain = vbRetry Then GoTo GenerateNewDigits End If End If Exit Sub EvalFail: bValidExpression = False vResult = Err.Description Resume End Sub
Convert the following code from Java to VB, ensuring the logic remains intact.
import java.util.*; public class Game24 { static Random r = new Random(); public static void main(String[] args) { int[] digits = randomDigits(); Scanner in = new Scanner(System.in); System.out.print("Make 24 using these digits: "); System.out.println(Arrays.toString(digits)); System.out.print("> "); Stack<Float> s = new Stack<>(); long total = 0; for (char c : in.nextLine().toCharArray()) { if ('0' <= c && c <= '9') { int d = c - '0'; total += (1 << (d * 5)); s.push((float) d); } else if ("+/-*".indexOf(c) != -1) { s.push(applyOperator(s.pop(), s.pop(), c)); } } if (tallyDigits(digits) != total) System.out.print("Not the same digits. "); else if (Math.abs(24 - s.peek()) < 0.001F) System.out.println("Correct!"); else System.out.print("Not correct."); } static float applyOperator(float a, float b, char c) { switch (c) { case '+': return a + b; case '-': return b - a; case '*': return a * b; case '/': return b / a; default: return Float.NaN; } } static long tallyDigits(int[] a) { long total = 0; for (int i = 0; i < 4; i++) total += (1 << (a[i] * 5)); return total; } static int[] randomDigits() { int[] result = new int[4]; for (int i = 0; i < 4; i++) result[i] = r.nextInt(9) + 1; return result; } }
Sub Rosetta_24game() Dim Digit(4) As Integer, i As Integer, iDigitCount As Integer Dim stUserExpression As String Dim stFailMessage As String, stFailDigits As String Dim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean Dim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant GenerateNewDigits: For i = 1 To 4 Digit(i) = [randbetween(1,9)] Next i GetUserExpression: bValidExpression = True stFailMessage = "" stFailDigits = "" stUserExpression = InputBox("Enter a mathematical expression which results in 24, using the following digits: " & _ Digit(1) & ", " & Digit(2) & ", " & Digit(3) & " and " & Digit(4), "Rosetta Code | 24 Game") bValidDigits = True stFailDigits = "" For i = 1 To 4 If InStr(stUserExpression, Digit(i)) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & Digit(i) End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = "Your expression excluded the following required digits: " & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" For i = 1 To Len(stUserExpression) If InStr("0123456789+-*/()", Mid(stUserExpression, i, 1)) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1) End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid characters:" & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" iDigitCount = 0 For i = 1 To Len(stUserExpression) If Not InStr("0123456789", Mid(stUserExpression, i, 1)) = 0 Then iDigitCount = iDigitCount + 1 If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then bValidDigits = False stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1) End If End If Next i If iDigitCount > 4 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained more than 4 digits" & vbCr & vbCr End If If iDigitCount < 4 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained less than 4 digits" & vbCr & vbCr End If If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid digits:" & stFailDigits & vbCr & vbCr End If bValidDigits = True stFailDigits = "" For i = 11 To 99 If Not InStr(stUserExpression, i) = 0 Then bValidDigits = False stFailDigits = stFailDigits & " " & i End If Next i If bValidDigits = False Then bValidExpression = False stFailMessage = stFailMessage & "Your expression contained invalid numbers:" & stFailDigits & vbCr & vbCr End If On Error GoTo EvalFail vResult = Evaluate(stUserExpression) If Not vResult = 24 Then bValidExpression = False stFailMessage = stFailMessage & "Your expression did not result in 24. It returned: " & vResult End If If bValidExpression = False Then vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & "Would you like to try again?", vbCritical + vbRetryCancel, "Rosetta Code | 24 Game | FAILED") If vTryAgain = vbRetry Then vSameDigits = MsgBox("Do you want to use the same numbers?", vbQuestion + vbYesNo, "Rosetta Code | 24 Game | RETRY") If vSameDigits = vbYes Then GoTo GetUserExpression Else GoTo GenerateNewDigits End If End If Else vTryAgain = MsgBox("You entered: " & stUserExpression & vbCr & vbCr & "which resulted in: " & vResult, _ vbInformation + vbRetryCancel, "Rosetta Code | 24 Game | SUCCESS") If vTryAgain = vbRetry Then GoTo GenerateNewDigits End If End If Exit Sub EvalFail: bValidExpression = False vResult = Err.Description Resume End Sub
Produce a language-to-language conversion: from Java to VB, same semantics.
for(int i = 1;i <= 10; i++){ System.out.print(i); if(i % 5 == 0){ System.out.println(); continue; } System.out.print(", "); }
For i = 1 To 10 Console.Write(i) If i Mod 5 = 0 Then Console.WriteLine() Else Console.Write(", ") End If Next
Convert this Java block to VB, preserving its control flow and logic.
import static java.util.Arrays.stream; import java.util.Locale; import static java.util.stream.IntStream.range; public class Test { static double dotProduct(double[] a, double[] b) { return range(0, a.length).mapToDouble(i -> a[i] * b[i]).sum(); } static double[][] matrixMul(double[][] A, double[][] B) { double[][] result = new double[A.length][B[0].length]; double[] aux = new double[B.length]; for (int j = 0; j < B[0].length; j++) { for (int k = 0; k < B.length; k++) aux[k] = B[k][j]; for (int i = 0; i < A.length; i++) result[i][j] = dotProduct(A[i], aux); } return result; } static double[][] pivotize(double[][] m) { int n = m.length; double[][] id = range(0, n).mapToObj(j -> range(0, n) .mapToDouble(i -> i == j ? 1 : 0).toArray()) .toArray(double[][]::new); for (int i = 0; i < n; i++) { double maxm = m[i][i]; int row = i; for (int j = i; j < n; j++) if (m[j][i] > maxm) { maxm = m[j][i]; row = j; } if (i != row) { double[] tmp = id[i]; id[i] = id[row]; id[row] = tmp; } } return id; } static double[][][] lu(double[][] A) { int n = A.length; double[][] L = new double[n][n]; double[][] U = new double[n][n]; double[][] P = pivotize(A); double[][] A2 = matrixMul(P, A); for (int j = 0; j < n; j++) { L[j][j] = 1; for (int i = 0; i < j + 1; i++) { double s1 = 0; for (int k = 0; k < i; k++) s1 += U[k][j] * L[i][k]; U[i][j] = A2[i][j] - s1; } for (int i = j; i < n; i++) { double s2 = 0; for (int k = 0; k < j; k++) s2 += U[k][j] * L[i][k]; L[i][j] = (A2[i][j] - s2) / U[j][j]; } } return new double[][][]{L, U, P}; } static void print(double[][] m) { stream(m).forEach(a -> { stream(a).forEach(n -> System.out.printf(Locale.US, "%5.1f ", n)); System.out.println(); }); System.out.println(); } public static void main(String[] args) { double[][] a = {{1.0, 3, 5}, {2.0, 4, 7}, {1.0, 1, 0}}; double[][] b = {{11.0, 9, 24, 2}, {1.0, 5, 2, 6}, {3.0, 17, 18, 1}, {2.0, 5, 7, 1}}; for (double[][] m : lu(a)) print(m); System.out.println(); for (double[][] m : lu(b)) print(m); } }
Option Base 1 Private Function pivotize(m As Variant) As Variant Dim n As Integer: n = UBound(m) Dim im() As Double ReDim im(n, n) For i = 1 To n For j = 1 To n im(i, j) = 0 Next j im(i, i) = 1 Next i For i = 1 To n mx = Abs(m(i, i)) row_ = i For j = i To n If Abs(m(j, i)) > mx Then mx = Abs(m(j, i)) row_ = j End If Next j If i <> Row Then For j = 1 To n tmp = im(i, j) im(i, j) = im(row_, j) im(row_, j) = tmp Next j End If Next i pivotize = im End Function Private Function lu(a As Variant) As Variant Dim n As Integer: n = UBound(a) Dim l() As Double ReDim l(n, n) For i = 1 To n For j = 1 To n l(i, j) = 0 Next j Next i u = l p = pivotize(a) a2 = WorksheetFunction.MMult(p, a) For j = 1 To n l(j, j) = 1# For i = 1 To j sum1 = 0# For k = 1 To i sum1 = sum1 + u(k, j) * l(i, k) Next k u(i, j) = a2(i, j) - sum1 Next i For i = j + 1 To n sum2 = 0# For k = 1 To j sum2 = sum2 + u(k, j) * l(i, k) Next k l(i, j) = (a2(i, j) - sum2) / u(j, j) Next i Next j Dim res(4) As Variant res(1) = a res(2) = l res(3) = u res(4) = p lu = res End Function Public Sub main() a = [{1, 3, 5; 2, 4, 7; 1, 1, 0}] Debug.Print "== a,l,u,p: ==" result = lu(a) For i = 1 To 4 For j = 1 To UBound(result(1)) For k = 1 To UBound(result(1), 2) Debug.Print result(i)(j, k), Next k Debug.Print Next j Debug.Print Next i a = [{11, 9,24, 2; 1, 5, 2, 6; 3,17,18, 1; 2, 5, 7, 1}] Debug.Print "== a,l,u,p: ==" result = lu(a) For i = 1 To 4 For j = 1 To UBound(result(1)) For k = 1 To UBound(result(1), 2) Debug.Print Format(result(i)(j, k), "0.#####"), Next k Debug.Print Next j Debug.Print Next i End Sub
Keep all operations the same but rewrite the snippet in VB.
public class FizzBuzz { public static void main(String[] args) { Sound[] sounds = {new Sound(3, "Fizz"), new Sound(5, "Buzz"), new Sound(7, "Baxx")}; for (int i = 1; i <= 20; i++) { StringBuilder sb = new StringBuilder(); for (Sound sound : sounds) { sb.append(sound.generate(i)); } System.out.println(sb.length() == 0 ? i : sb.toString()); } } private static class Sound { private final int trigger; private final String onomatopoeia; public Sound(int trigger, String onomatopoeia) { this.trigger = trigger; this.onomatopoeia = onomatopoeia; } public String generate(int i) { return i % trigger == 0 ? onomatopoeia : ""; } } }
Option Explicit Private Type Choice Number As Integer Name As String End Type Private MaxNumber As Integer Sub Main() Dim U(1 To 3) As Choice, i As Integer, j As Integer, t$ MaxNumber = Application.InputBox("Enter the max number : ", "Integer please", Type:=1) For i = 1 To 3 U(i) = UserChoice Next For i = 1 To MaxNumber t = vbNullString For j = 1 To 3 If i Mod U(j).Number = 0 Then t = t & U(j).Name Next Debug.Print IIf(t = vbNullString, i, t) Next i End Sub Private Function UserChoice() As Choice Dim ok As Boolean Do While Not ok UserChoice.Number = Application.InputBox("Enter the factors to be calculated : ", "Integer please", Type:=1) UserChoice.Name = InputBox("Enter the corresponding word : ") If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True Loop End Function