Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Convert this C# block to Python, preserving its control flow and logic.
using System; using System.Collections.Generic; using System.Linq; class Program { public static void Main() { var sequence = new[] { "A", "B", "C", "D" }; foreach (var subset in Subsets(sequence.Length).Where(s => !IsContinuous(s))) { Console.WriteLine(string.Join(" ", subset.Select(i => sequence[i]))); } } static IEnumerable<List<int>> Subsets(int length) { int[] values = Enumerable.Range(0, length).ToArray(); var stack = new Stack<int>(length); for (int i = 0; stack.Count > 0 || i < length; ) { if (i < length) { stack.Push(i++); yield return (from index in stack.Reverse() select values[index]).ToList(); } else { i = stack.Pop() + 1; if (stack.Count > 0) i = stack.Pop() + 1; } } } static bool IsContinuous(List<int> list) => list[list.Count - 1] - list[0] + 1 == list.Count; }
def ncsub(seq, s=0): if seq: x = seq[:1] xs = seq[1:] p2 = s % 2 p1 = not p2 return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + p2) else: return [[]] if s >= 3 else []
Translate the given C# code snippet into Python without altering its behavior.
using System; using System.Collections.Generic; using System.Linq; class Program { public static void Main() { var sequence = new[] { "A", "B", "C", "D" }; foreach (var subset in Subsets(sequence.Length).Where(s => !IsContinuous(s))) { Console.WriteLine(string.Join(" ", subset.Select(i => sequence[i]))); } } static IEnumerable<List<int>> Subsets(int length) { int[] values = Enumerable.Range(0, length).ToArray(); var stack = new Stack<int>(length); for (int i = 0; stack.Count > 0 || i < length; ) { if (i < length) { stack.Push(i++); yield return (from index in stack.Reverse() select values[index]).ToList(); } else { i = stack.Pop() + 1; if (stack.Count > 0) i = stack.Pop() + 1; } } } static bool IsContinuous(List<int> list) => list[list.Count - 1] - list[0] + 1 == list.Count; }
def ncsub(seq, s=0): if seq: x = seq[:1] xs = seq[1:] p2 = s % 2 p1 = not p2 return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + p2) else: return [[]] if s >= 3 else []
Convert this C# block to Python, preserving its control flow and logic.
using System; class Program { static uint[] res = new uint[10]; static uint ri = 1, p = 10, count = 0; static void TabulateTwinPrimes(uint bound) { if (bound < 5) return; count++; uint cl = (bound - 1) >> 1, i = 1, j, limit = (uint)(Math.Sqrt(bound) - 1) >> 1; var comp = new bool[cl]; bool lp; for (j = 3; j < cl; j += 3) comp[j] = true; while (i < limit) { if (lp = !comp[i]) { uint pr = (i << 1) + 3; for (j = (pr * pr - 2) >> 1; j < cl; j += pr) comp[j] = true; } if (!comp[++i]) { uint pr = (i << 1) + 3; if (lp) { if (pr > p) { res[ri++] = count; p *= 10; } count++; i++; } for (j = (pr * pr - 2) >> 1; j < cl; j += pr) comp[j] = true; } } cl--; while (i < cl) { lp = !comp[i++]; if (!comp[i] && lp) { if ((i++ << 1) + 3 > p) { res[ri++] = count; p *= 10; } count++; } } res[ri] = count; } static void Main(string[] args) { var sw = System.Diagnostics.Stopwatch.StartNew(); string fmt = "{0,9:n0} twin primes below {1,-13:n0}"; TabulateTwinPrimes(1_000_000_000); sw.Stop(); p = 1; for (var j = 1; j <= ri; j++) Console.WriteLine(fmt, res[j], p *= 10); Console.Write("{0} sec", sw.Elapsed.TotalSeconds); } }
primes = [2, 3, 5, 7, 11, 13, 17, 19] def count_twin_primes(limit: int) -> int: global primes if limit > primes[-1]: ram_limit = primes[-1] + 90000000 - len(primes) reasonable_limit = min(limit, primes[-1] ** 2, ram_limit) - 1 while reasonable_limit < limit: ram_limit = primes[-1] + 90000000 - len(primes) if ram_limit > primes[-1]: reasonable_limit = min(limit, primes[-1] ** 2, ram_limit) else: reasonable_limit = min(limit, primes[-1] ** 2) sieve = list({x for prime in primes for x in range(primes[-1] + prime - (primes[-1] % prime), reasonable_limit, prime)}) primes += [x - 1 for i, x in enumerate(sieve) if i and x - 1 != sieve[i - 1] and x - 1 < limit] count = len([(x, y) for (x, y) in zip(primes, primes[1:]) if x + 2 == y]) return count def test(limit: int): count = count_twin_primes(limit) print(f"Number of twin prime pairs less than {limit} is {count}\n") test(10) test(100) test(1000) test(10000) test(100000) test(1000000) test(10000000) test(100000000)
Keep all operations the same but rewrite the snippet in Python.
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; class Program { static IEnumerable<Complex> RootsOfUnity(int degree) { return Enumerable .Range(0, degree) .Select(element => Complex.FromPolarCoordinates(1, 2 * Math.PI * element / degree)); } static void Main() { var degree = 3; foreach (var root in RootsOfUnity(degree)) { Console.WriteLine(root); } } }
import cmath class Complex(complex): def __repr__(self): rp = '%7.5f' % self.real if not self.pureImag() else '' ip = '%7.5fj' % self.imag if not self.pureReal() else '' conj = '' if ( self.pureImag() or self.pureReal() or self.imag < 0.0 ) else '+' return '0.0' if ( self.pureImag() and self.pureReal() ) else rp + conj + ip def pureImag(self): return abs(self.real) < 0.000005 def pureReal(self): return abs(self.imag) < 0.000005 def croots(n): if n <= 0: return None return (Complex(cmath.rect(1, 2 * k * cmath.pi / n)) for k in range(n)) for nr in range(2, 11): print(nr, list(croots(nr)))
Produce a language-to-language conversion: from C# to Python, same semantics.
using System; using static System.Console; using BI = System.Numerics.BigInteger; class Program { static decimal mx = 1E28M, hm = 1E14M, a; struct bi { public decimal hi, lo; } static bi set4sq(decimal a) { bi r; r.hi = Math.Floor(a / hm); r.lo = a % hm; return r; } static string toStr(bi a, bool comma = false) { string r = a.hi == 0 ? string.Format("{0:0}", a.lo) : string.Format("{0:0}{1:" + new string('0', 28) + "}", a.hi, a.lo); if (!comma) return r; string rc = ""; for (int i = r.Length - 3; i > 0; i -= 3) rc = "," + r.Substring(i, 3) + rc; return r.Substring(0, ((r.Length + 2) % 3) + 1) + rc; } static decimal Pow_dec(decimal bas, uint exp) { if (exp == 0) return 1M; decimal tmp = Pow_dec(bas, exp >> 1); tmp *= tmp; if ((exp & 1) == 0) return tmp; return tmp * bas; } static void Main(string[] args) { for (uint p = 64; p < 95; p += 30) { bi x = set4sq(a = Pow_dec(2M, p)), y; WriteLine("The square of (2^{0}): {1,38:n0}", p, a); BI BS = BI.Pow((BI)a, 2); y.lo = x.lo * x.lo; y.hi = x.hi * x.hi; a = x.hi * x.lo * 2M; y.hi += Math.Floor(a / hm); y.lo += (a % hm) * hm; while (y.lo > mx) { y.lo -= mx; y.hi++; } WriteLine(" is {0,75} (which {1} match the BigInteger computation)\n", toStr(y, true), BS.ToString() == toStr(y) ? "does" : "fails to"); } } }
print 2**64*2**64
Can you help me rewrite this code in Python instead of C#, keeping it the same logically?
using System; using System.Numerics; static class Program { static void Fun(ref BigInteger a, ref BigInteger b, int c) { BigInteger t = a; a = b; b = b * c + t; } static void SolvePell(int n, ref BigInteger a, ref BigInteger b) { int x = (int)Math.Sqrt(n), y = x, z = 1, r = x << 1; BigInteger e1 = 1, e2 = 0, f1 = 0, f2 = 1; while (true) { y = r * z - y; z = (n - y * y) / z; r = (x + y) / z; Fun(ref e1, ref e2, r); Fun(ref f1, ref f2, r); a = f2; b = e2; Fun(ref b, ref a, x); if (a * a - n * b * b == 1) return; } } static void Main() { BigInteger x, y; foreach (int n in new[] { 61, 109, 181, 277 }) { SolvePell(n, ref x, ref y); Console.WriteLine("x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}", n, x, y); } } }
import math def solvePell(n): x = int(math.sqrt(n)) y, z, r = x, 1, x << 1 e1, e2 = 1, 0 f1, f2 = 0, 1 while True: y = r * z - y z = (n - y * y) // z r = (x + y) // z e1, e2 = e2, e1 + e2 * r f1, f2 = f2, f1 + f2 * r a, b = f2 * x + e2, f2 if a * a - n * b * b == 1: return a, b for n in [61, 109, 181, 277]: x, y = solvePell(n) print("x^2 - %3d * y^2 = 1 for x = %27d and y = %25d" % (n, x, y))
Produce a functionally identical Python code for the snippet given in C#.
using System; namespace BullsnCows { class Program { static void Main(string[] args) { int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; KnuthShuffle<int>(ref nums); int[] chosenNum = new int[4]; Array.Copy(nums, chosenNum, 4); Console.WriteLine("Your Guess ?"); while (!game(Console.ReadLine(), chosenNum)) { Console.WriteLine("Your next Guess ?"); } Console.ReadKey(); } public static void KnuthShuffle<T>(ref T[] array) { System.Random random = new System.Random(); for (int i = 0; i < array.Length; i++) { int j = random.Next(array.Length); T temp = array[i]; array[i] = array[j]; array[j] = temp; } } public static bool game(string guess, int[] num) { char[] guessed = guess.ToCharArray(); int bullsCount = 0, cowsCount = 0; if (guessed.Length != 4) { Console.WriteLine("Not a valid guess."); return false; } for (int i = 0; i < 4; i++) { int curguess = (int) char.GetNumericValue(guessed[i]); if (curguess < 1 || curguess > 9) { Console.WriteLine("Digit must be ge greater 0 and lower 10."); return false; } if (curguess == num[i]) { bullsCount++; } else { for (int j = 0; j < 4; j++) { if (curguess == num[j]) cowsCount++; } } } if (bullsCount == 4) { Console.WriteLine("Congratulations! You have won!"); return true; } else { Console.WriteLine("Your Score is {0} bulls and {1} cows", bullsCount, cowsCount); return false; } } } }
import random digits = '123456789' size = 4 chosen = ''.join(random.sample(digits,size)) print % (size, size) guesses = 0 while True: guesses += 1 while True: guess = raw_input('\nNext guess [%i]: ' % guesses).strip() if len(guess) == size and \ all(char in digits for char in guess) \ and len(set(guess)) == size: break print "Problem, try again. You need to enter %i unique digits from 1 to 9" % size if guess == chosen: print '\nCongratulations you guessed correctly in',guesses,'attempts' break bulls = cows = 0 for i in range(size): if guess[i] == chosen[i]: bulls += 1 elif guess[i] in chosen: cows += 1 print ' %i Bulls\n %i Cows' % (bulls, cows)
Preserve the algorithm and functionality while converting the code from C# to Python.
using System; using System.Collections.Generic; namespace RosettaCode.BubbleSort { public static class BubbleSortMethods { public static void BubbleSort<T>(this List<T> list) where T : IComparable { bool madeChanges; int itemCount = list.Count; do { madeChanges = false; itemCount--; for (int i = 0; i < itemCount; i++) { if (list[i].CompareTo(list[i + 1]) > 0) { T temp = list[i + 1]; list[i + 1] = list[i]; list[i] = temp; madeChanges = true; } } } while (madeChanges); } } class Program { static void Main() { List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 }; testList.BubbleSort(); foreach (var t in testList) Console.Write(t + " "); } } }
def bubble_sort(seq): changed = True while changed: changed = False for i in range(len(seq) - 1): if seq[i] > seq[i+1]: seq[i], seq[i+1] = seq[i+1], seq[i] changed = True return seq if __name__ == "__main__": from random import shuffle testset = [_ for _ in range(100)] testcase = testset.copy() shuffle(testcase) assert testcase != testset bubble_sort(testcase) assert testcase == testset
Write the same code in Python as shown below in C#.
using System; using System.IO; namespace FileIO { class Program { static void Main() { String s = scope .(); File.ReadAllText("input.txt", s); File.WriteAllText("output.txt", s); } } }
import shutil shutil.copyfile('input.txt', 'output.txt')
Write the same algorithm in Python as shown in this C# implementation.
using System; class Program { static void Main(string[] args) { int a = Convert.ToInt32(args[0]); int b = Convert.ToInt32(args[1]); Console.WriteLine("{0} + {1} = {2}", a, b, a + b); Console.WriteLine("{0} - {1} = {2}", a, b, a - b); Console.WriteLine("{0} * {1} = {2}", a, b, a * b); Console.WriteLine("{0} / {1} = {2}", a, b, a / b); Console.WriteLine("{0} % {1} = {2}", a, b, a % b); Console.WriteLine("{0} to the power of {1} = {2}", a, b, Math.Pow(a, b)); } }
x = int(raw_input("Number 1: ")) y = int(raw_input("Number 2: ")) print "Sum: %d" % (x + y) print "Difference: %d" % (x - y) print "Product: %d" % (x * y) print "Quotient: %d" % (x / y) print "Remainder: %d" % (x % y) print "Quotient: %d with Remainder: %d" % divmod(x, y) print "Power: %d" % x**y raw_input( )
Transform the following C# implementation into Python, maintaining the same output and logic.
using System; using System.Text; namespace prog { class MainClass { public static void Main (string[] args) { double[,] m = { {1,2,3},{4,5,6},{7,8,9} }; double[,] t = Transpose( m ); for( int i=0; i<t.GetLength(0); i++ ) { for( int j=0; j<t.GetLength(1); j++ ) Console.Write( t[i,j] + " " ); Console.WriteLine(""); } } public static double[,] Transpose( double[,] m ) { double[,] t = new double[m.GetLength(1),m.GetLength(0)]; for( int i=0; i<m.GetLength(0); i++ ) for( int j=0; j<m.GetLength(1); j++ ) t[j,i] = m[i,j]; return t; } } }
m=((1, 1, 1, 1), (2, 4, 8, 16), (3, 9, 27, 81), (4, 16, 64, 256), (5, 25,125, 625)) print(zip(*m))
Write the same algorithm in Python as shown in this C# implementation.
using System; delegate T Func<T>(); class ManOrBoy { static void Main() { Console.WriteLine(A(10, C(1), C(-1), C(-1), C(1), C(0))); } static Func<int> C(int i) { return delegate { return i; }; } static int A(int k, Func<int> x1, Func<int> x2, Func<int> x3, Func<int> x4, Func<int> x5) { Func<int> b = null; b = delegate { k--; return A(k, b, x1, x2, x3, x4); }; return k <= 0 ? x4() + x5() : b(); } }
import sys sys.setrecursionlimit(1025) def a(in_k, x1, x2, x3, x4, x5): k = [in_k] def b(): k[0] -= 1 return a(k[0], b, x1, x2, x3, x4) return x4() + x5() if k[0] <= 0 else b() x = lambda i: lambda: i print(a(10, x(1), x(-1), x(-1), x(1), x(0)))
Preserve the algorithm and functionality while converting the code from C# to Python.
using System; class Program { static bool a(bool value) { Console.WriteLine("a"); return value; } static bool b(bool value) { Console.WriteLine("b"); return value; } static void Main() { foreach (var i in new[] { false, true }) { foreach (var j in new[] { false, true }) { Console.WriteLine("{0} and {1} = {2}", i, j, a(i) && b(j)); Console.WriteLine(); Console.WriteLine("{0} or {1} = {2}", i, j, a(i) || b(j)); Console.WriteLine(); } } } }
>>> def a(answer): print(" return answer >>> def b(answer): print(" return answer >>> for i in (False, True): for j in (False, True): print ("\nCalculating: x = a(i) and b(j)") x = a(i) and b(j) print ("Calculating: y = a(i) or b(j)") y = a(i) or b(j) Calculating: x = a(i) and b(j) Calculating: y = a(i) or b(j) Calculating: x = a(i) and b(j) Calculating: y = a(i) or b(j) Calculating: x = a(i) and b(j) Calculating: y = a(i) or b(j) Calculating: x = a(i) and b(j) Calculating: y = a(i) or b(j)
Convert this C# block to Python, preserving its control flow and logic.
using System; class RecursionLimit { static void Main(string[] args) { Recur(0); } private static void Recur(int i) { Console.WriteLine(i); Recur(i + 1); } }
import sys print(sys.getrecursionlimit())
Port the following code from C# to Python with equivalent syntax and logic.
using System; class RecursionLimit { static void Main(string[] args) { Recur(0); } private static void Recur(int i) { Console.WriteLine(i); Recur(i + 1); } }
import sys print(sys.getrecursionlimit())
Transform the following C# implementation into Python, maintaining the same output and logic.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Runtime.InteropServices; using System.Windows.Forms; class Program { static Size size = new Size(320, 240); static Rectangle rectsize = new Rectangle(new Point(0, 0), size); static int numpixels = size.Width * size.Height; static int numbytes = numpixels * 3; static PictureBox pb; static BackgroundWorker worker; static double time = 0; static double frames = 0; static Random rand = new Random(); static byte tmp; static byte white = 255; static byte black = 0; static int halfmax = int.MaxValue / 2; static IEnumerable<byte> YieldVodoo() { for (int i = 0; i < numpixels; i++) { tmp = rand.Next() < halfmax ? black : white; yield return tmp; yield return tmp; yield return tmp; } } static Image Randimg() { var bitmap = new Bitmap(size.Width, size.Height); var data = bitmap.LockBits(rectsize, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb); Marshal.Copy( YieldVodoo().ToArray<byte>(), 0, data.Scan0, numbytes); bitmap.UnlockBits(data); return bitmap; } [STAThread] static void Main() { var form = new Form(); form.AutoSize = true; form.Size = new Size(0, 0); form.Text = "Test"; form.FormClosed += delegate { Application.Exit(); }; worker = new BackgroundWorker(); worker.DoWork += delegate { System.Threading.Thread.Sleep(500); while (true) { var a = DateTime.Now; pb.Image = Randimg(); var b = DateTime.Now; time += (b - a).TotalSeconds; frames += 1; if (frames == 30) { Console.WriteLine("{0} frames in {1:0.000} seconds. ({2:0} FPS)", frames, time, frames / time); time = 0; frames = 0; } } }; worker.RunWorkerAsync(); FlowLayoutPanel flp = new FlowLayoutPanel(); form.Controls.Add(flp); pb = new PictureBox(); pb.Size = size; flp.AutoSize = true; flp.Controls.Add(pb); form.Show(); Application.Run(); } }
black = color(0) white = color(255) def setup(): size(320, 240) def draw(): loadPixels() for i in range(len(pixels)): if random(1) < 0.5: pixels[i] = black else: pixels[i] = white updatePixels() fill(0, 128) rect(0, 0, 60, 20) fill(255) text(frameRate, 5, 15)
Generate an equivalent Python version of this C# code.
static void Main(string[] args) { Console.WriteLine("Perfect numbers from 1 to 33550337:"); for (int x = 0; x < 33550337; x++) { if (IsPerfect(x)) Console.WriteLine(x + " is perfect."); } Console.ReadLine(); } static bool IsPerfect(int num) { int sum = 0; for (int i = 1; i < num; i++) { if (num % i == 0) sum += i; } return sum == num ; }
def perf1(n): sum = 0 for i in range(1, n): if n % i == 0: sum += i return sum == n
Rewrite this program in Python while keeping its functionality equivalent to the C# version.
using System; using System.Diagnostics; using System.Linq; using System.Numerics; static class Program { static void Main() { BigInteger n = BigInteger.Pow(5, (int)BigInteger.Pow(4, (int)BigInteger.Pow(3, 2))); string result = n.ToString(); Debug.Assert(result.Length == 183231); Debug.Assert(result.StartsWith("62060698786608744707")); Debug.Assert(result.EndsWith("92256259918212890625")); Console.WriteLine("n = 5^4^3^2"); Console.WriteLine("n = {0}...{1}", result.Substring(0, 20), result.Substring(result.Length - 20, 20) ); Console.WriteLine("n digits = {0}", result.Length); } }
>>> y = str( 5**4**3**2 ) >>> print ("5**4**3**2 = %s...%s and has %i digits" % (y[:20], y[-20:], len(y))) 5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits
Keep all operations the same but rewrite the snippet in Python.
using System; using System.Collections.Generic; using System.IO; using System.Linq; class InvertedIndex { static Dictionary<TItem, IEnumerable<TKey>> Invert<TKey, TItem>(Dictionary<TKey, IEnumerable<TItem>> dictionary) { return dictionary .SelectMany(keyValuePair => keyValuePair.Value.Select(item => new KeyValuePair<TItem, TKey>(item, keyValuePair.Key))) .GroupBy(keyValuePair => keyValuePair.Key) .ToDictionary(group => group.Key, group => group.Select(keyValuePair => keyValuePair.Value)); } static void Main() { Console.Write("files: "); var files = Console.ReadLine(); Console.Write("find: "); var find = Console.ReadLine(); var dictionary = files.Split().ToDictionary(file => file, file => File.ReadAllText(file).Split().AsEnumerable()); Console.WriteLine("{0} found in: {1}", find, string.Join(" ", Invert(dictionary)[find])); } }
from pprint import pprint as pp from glob import glob try: reduce except: from functools import reduce try: raw_input except: raw_input = input def parsetexts(fileglob='InvertedIndex/T*.txt'): texts, words = {}, set() for txtfile in glob(fileglob): with open(txtfile, 'r') as f: txt = f.read().split() words |= set(txt) texts[txtfile.split('\\')[-1]] = txt return texts, words def termsearch(terms): return reduce(set.intersection, (invindex[term] for term in terms), set(texts.keys())) texts, words = parsetexts() print('\nTexts') pp(texts) print('\nWords') pp(sorted(words)) invindex = {word:set(txt for txt, wrds in texts.items() if word in wrds) for word in words} print('\nInverted Index') pp({k:sorted(v) for k,v in invindex.items()}) terms = ["what", "is", "it"] print('\nTerm Search for: ' + repr(terms)) pp(sorted(termsearch(terms)))
Port the following code from C# to Python with equivalent syntax and logic.
Using System; class Program { static int gcd(int m, int n) { return n == 0 ? Math.Abs(m) : gcd(n, n % m); } static int lcm(int m, int n) { return Math.Abs(m * n) / gcd(m, n); } static void Main() { Console.WriteLine("lcm(12,18)=" + lcm(12,18)); } }
>>> import fractions >>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0 >>> lcm(12, 18) 36 >>> lcm(-6, 14) 42 >>> assert lcm(0, 2) == lcm(2, 0) == 0 >>>
Port the provided C# code into Python while preserving the original functionality.
Using System; class Program { static int gcd(int m, int n) { return n == 0 ? Math.Abs(m) : gcd(n, n % m); } static int lcm(int m, int n) { return Math.Abs(m * n) / gcd(m, n); } static void Main() { Console.WriteLine("lcm(12,18)=" + lcm(12,18)); } }
>>> import fractions >>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0 >>> lcm(12, 18) 36 >>> lcm(-6, 14) 42 >>> assert lcm(0, 2) == lcm(2, 0) == 0 >>>
Convert this C# block to Python, preserving its control flow and logic.
class Program { static void Main(string[] args) { Random random = new Random(); while (true) { int a = random.Next(20); Console.WriteLine(a); if (a == 10) break; int b = random.Next(20) Console.WriteLine(b); } Console.ReadLine(); } }
from random import randrange while True: a = randrange(20) print(a) if a == 10: break b = randrange(20) print(b)
Generate a Python translation of this C# snippet without changing its computational steps.
class Program { static void Main(string[] args) { int[][] wta = { new int[] {1, 5, 3, 7, 2}, new int[] { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 }, new int[] { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 }, new int[] { 5, 5, 5, 5 }, new int[] { 5, 6, 7, 8 }, new int[] { 8, 7, 7, 6 }, new int[] { 6, 7, 10, 7, 6 }}; string blk, lf = "\n", tb = "██", wr = "≈≈", mt = " "; for (int i = 0; i < wta.Length; i++) { int bpf; blk = ""; do { string floor = ""; bpf = 0; for (int j = 0; j < wta[i].Length; j++) { if (wta[i][j] > 0) { floor += tb; wta[i][j] -= 1; bpf += 1; } else floor += (j > 0 && j < wta[i].Length - 1 ? wr : mt); } if (bpf > 0) blk = floor + lf + blk; } while (bpf > 0); while (blk.Contains(mt + wr)) blk = blk.Replace(mt + wr, mt + mt); while (blk.Contains(wr + mt)) blk = blk.Replace(wr + mt, mt + mt); if (args.Length > 0) System.Console.Write("\n{0}", blk); System.Console.WriteLine("Block {0} retains {1,2} water units.", i + 1, (blk.Length - blk.Replace(wr, "").Length) / 2); } } }
def water_collected(tower): N = len(tower) highest_left = [0] + [max(tower[:n]) for n in range(1,N)] highest_right = [max(tower[n:N]) for n in range(1,N)] + [0] water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0) for n in range(N)] print("highest_left: ", highest_left) print("highest_right: ", highest_right) print("water_level: ", water_level) print("tower_level: ", tower) print("total_water: ", sum(water_level)) print("") return sum(water_level) towers = [[1, 5, 3, 7, 2], [5, 3, 7, 2, 6, 4, 5, 9, 1, 2], [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1], [5, 5, 5, 5], [5, 6, 7, 8], [8, 7, 7, 6], [6, 7, 10, 7, 6]] [water_collected(tower) for tower in towers]
Ensure the translated Python code behaves exactly like the original C# snippet.
using System; class Program { static bool ispr(uint n) { if ((n & 1) == 0 || n < 2) return n == 2; for (uint j = 3; j * j <= n; j += 2) if (n % j == 0) return false; return true; } static void Main(string[] args) { uint c = 0; int nc; var ps = new uint[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var nxt = new uint[128]; while (true) { nc = 0; foreach (var a in ps) { if (ispr(a)) Console.Write("{0,8}{1}", a, ++c % 5 == 0 ? "\n" : " "); for (uint b = a * 10, l = a % 10 + b++; b < l; b++) nxt[nc++] = b; } if (nc > 1) { Array.Resize (ref ps, nc); Array.Copy(nxt, ps, nc); } else break; } Console.WriteLine("\n{0} descending primes found", c); } }
from sympy import isprime def descending(xs=range(10)): for x in xs: yield x yield from descending(x*10 + d for d in range(x%10)) for i, p in enumerate(sorted(filter(isprime, descending()))): print(f'{p:9d}', end=' ' if (1 + i)%8 else '\n') print()
Maintain the same structure and functionality when rewriting this code in Python.
using System; class Program { static bool ispr(uint n) { if ((n & 1) == 0 || n < 2) return n == 2; for (uint j = 3; j * j <= n; j += 2) if (n % j == 0) return false; return true; } static void Main(string[] args) { uint c = 0; int nc; var ps = new uint[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var nxt = new uint[128]; while (true) { nc = 0; foreach (var a in ps) { if (ispr(a)) Console.Write("{0,8}{1}", a, ++c % 5 == 0 ? "\n" : " "); for (uint b = a * 10, l = a % 10 + b++; b < l; b++) nxt[nc++] = b; } if (nc > 1) { Array.Resize (ref ps, nc); Array.Copy(nxt, ps, nc); } else break; } Console.WriteLine("\n{0} descending primes found", c); } }
from sympy import isprime def descending(xs=range(10)): for x in xs: yield x yield from descending(x*10 + d for d in range(x%10)) for i, p in enumerate(sorted(filter(isprime, descending()))): print(f'{p:9d}', end=' ' if (1 + i)%8 else '\n') print()
Write the same algorithm in Python as shown in this C# implementation.
using System; using System.Linq; using System.Collections.Generic; public class Program { public static void Main() { const int maxSum = 100; var pairs = ( from X in 2.To(maxSum / 2 - 1) from Y in (X + 1).To(maxSum - 2).TakeWhile(y => X + y <= maxSum) select new { X, Y, S = X + Y, P = X * Y } ).ToHashSet(); Console.WriteLine(pairs.Count); var uniqueP = pairs.GroupBy(pair => pair.P).Where(g => g.Count() == 1).Select(g => g.Key).ToHashSet(); pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Any(pair => uniqueP.Contains(pair.P))).SelectMany(g => g)); Console.WriteLine(pairs.Count); pairs.ExceptWith(pairs.GroupBy(pair => pair.P).Where(g => g.Count() > 1).SelectMany(g => g)); Console.WriteLine(pairs.Count); pairs.ExceptWith(pairs.GroupBy(pair => pair.S).Where(g => g.Count() > 1).SelectMany(g => g)); Console.WriteLine(pairs.Count); foreach (var pair in pairs) Console.WriteLine(pair); } } public static class Extensions { public static IEnumerable<int> To(this int start, int end) { for (int i = start; i <= end; i++) yield return i; } public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) => new HashSet<T>(source); }
from collections import Counter def decompose_sum(s): return [(a,s-a) for a in range(2,int(s/2+1))] all_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100) product_counts = Counter(c*d for c,d in all_pairs) unique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1) s_pairs = [(a,b) for a,b in all_pairs if all((x,y) not in unique_products for (x,y) in decompose_sum(a+b))] product_counts = Counter(c*d for c,d in s_pairs) p_pairs = [(a,b) for a,b in s_pairs if product_counts[a*b]==1] sum_counts = Counter(c+d for c,d in p_pairs) final_pairs = [(a,b) for a,b in p_pairs if sum_counts[a+b]==1] print(final_pairs)
Write the same algorithm in Python as shown in this C# implementation.
using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { string infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; Console.WriteLine(infix.ToPostfix()); } } public static class ShuntingYard { private static readonly Dictionary<string, (string symbol, int precedence, bool rightAssociative)> operators = new (string symbol, int precedence, bool rightAssociative) [] { ("^", 4, true), ("*", 3, false), ("/", 3, false), ("+", 2, false), ("-", 2, false) }.ToDictionary(op => op.symbol); public static string ToPostfix(this string infix) { string[] tokens = infix.Split(' '); var stack = new Stack<string>(); var output = new List<string>(); foreach (string token in tokens) { if (int.TryParse(token, out _)) { output.Add(token); Print(token); } else if (operators.TryGetValue(token, out var op1)) { while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) { int c = op1.precedence.CompareTo(op2.precedence); if (c < 0 || !op1.rightAssociative && c <= 0) { output.Add(stack.Pop()); } else { break; } } stack.Push(token); Print(token); } else if (token == "(") { stack.Push(token); Print(token); } else if (token == ")") { string top = ""; while (stack.Count > 0 && (top = stack.Pop()) != "(") { output.Add(top); } if (top != "(") throw new ArgumentException("No matching left parenthesis."); Print(token); } } while (stack.Count > 0) { var top = stack.Pop(); if (!operators.ContainsKey(top)) throw new ArgumentException("No matching right parenthesis."); output.Add(top); } Print("pop"); return string.Join(" ", output); void Print(string action) => Console.WriteLine($"{action + ":",-4} {$"stack[ {string.Join(" ", stack.Reverse())} ]",-18} {$"out[ {string.Join(" ", output)} ]"}"); void Print(string action) => Console.WriteLine("{0,-4} {1,-18} {2}", action + ":", $"stack[ {string.Join(" ", stack.Reverse())} ]", $"out[ {string.Join(" ", output)} ]"); } }
from collections import namedtuple from pprint import pprint as pp OpInfo = namedtuple('OpInfo', 'prec assoc') L, R = 'Left Right'.split() ops = { '^': OpInfo(prec=4, assoc=R), '*': OpInfo(prec=3, assoc=L), '/': OpInfo(prec=3, assoc=L), '+': OpInfo(prec=2, assoc=L), '-': OpInfo(prec=2, assoc=L), '(': OpInfo(prec=9, assoc=L), ')': OpInfo(prec=0, assoc=L), } NUM, LPAREN, RPAREN = 'NUMBER ( )'.split() def get_input(inp = None): 'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)' if inp is None: inp = input('expression: ') tokens = inp.strip().split() tokenvals = [] for token in tokens: if token in ops: tokenvals.append((token, ops[token])) else: tokenvals.append((NUM, token)) return tokenvals def shunting(tokenvals): outq, stack = [], [] table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')] for token, val in tokenvals: note = action = '' if token is NUM: action = 'Add number to output' outq.append(val) table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) elif token in ops: t1, (p1, a1) = token, val v = t1 note = 'Pop ops from stack to output' while stack: t2, (p2, a2) = stack[-1] if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2): if t1 != RPAREN: if t2 != LPAREN: stack.pop() action = '(Pop op)' outq.append(t2) else: break else: if t2 != LPAREN: stack.pop() action = '(Pop op)' outq.append(t2) else: stack.pop() action = '(Pop & discard "(")' table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) break table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) v = note = '' else: note = '' break note = '' note = '' if t1 != RPAREN: stack.append((token, val)) action = 'Push op token to stack' else: action = 'Discard ")"' table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) note = 'Drain stack to output' while stack: v = '' t2, (p2, a2) = stack[-1] action = '(Pop op)' stack.pop() outq.append(t2) table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) v = note = '' return table if __name__ == '__main__': infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3' print( 'For infix expression: %r\n' % infix ) rp = shunting(get_input(infix)) maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)] row = rp[0] print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row))) for row in rp[1:]: print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row))) print('\n The final output RPN is: %r' % rp[-1][2])
Transform the following C# implementation into Python, maintaining the same output and logic.
using System; namespace RosettaCode { class Program { static void Main(string[] args) { string text = Math.Abs(int.Parse(Console.ReadLine())).ToString(); Console.WriteLine(text.Length < 2 || text.Length % 2 == 0 ? "Error" : text.Substring((text.Length - 3) / 2, 3)); } } }
>>> def middle_three_digits(i): s = str(abs(i)) length = len(s) assert length >= 3 and length % 2 == 1, "Need odd and >= 3 digits" mid = length // 2 return s[mid-1:mid+2] >>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345] >>> failing = [1, 2, -1, -10, 2002, -2002, 0] >>> for x in passing + failing: try: answer = middle_three_digits(x) except AssertionError as error: answer = error print("middle_three_digits(%s) returned: %r" % (x, answer)) middle_three_digits(123) returned: '123' middle_three_digits(12345) returned: '234' middle_three_digits(1234567) returned: '345' middle_three_digits(987654321) returned: '654' middle_three_digits(10001) returned: '000' middle_three_digits(-10001) returned: '000' middle_three_digits(-123) returned: '123' middle_three_digits(-100) returned: '100' middle_three_digits(100) returned: '100' middle_three_digits(-12345) returned: '234' middle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',) >>>
Write the same code in Python as shown below in C#.
using System; using System.Collections.Generic; using System.Linq; static class Program { static List<int> l = new List<int>() { 1, 1 }; static int gcd(int a, int b) { return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; } static void Main(string[] args) { int max = 1000; int take = 15; int i = 1; int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 }; do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; } while (l.Count < max || l[l.Count - 2] != selection.Last()); Console.Write("The first {0} items In the Stern-Brocot sequence: ", take); Console.WriteLine("{0}\n", string.Join(", ", l.Take(take))); Console.WriteLine("The locations of where the selected numbers (1-to-10, & 100) first appear:"); foreach (int ii in selection) { int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine("{0,3}: {1:n0}", ii, j); } Console.WriteLine(); bool good = true; for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } } Console.WriteLine("The greatest common divisor of all the two consecutive items of the" + " series up to the {0}th item is {1}always one.", max, good ? "" : "not "); } }
def stern_brocot(predicate=lambda series: len(series) < 20): sb, i = [1, 1], 0 while predicate(sb): sb += [sum(sb[i:i + 2]), sb[i + 1]] i += 1 return sb if __name__ == '__main__': from fractions import gcd n_first = 15 print('The first %i values:\n ' % n_first, stern_brocot(lambda series: len(series) < n_first)[:n_first]) print() n_max = 10 for n_occur in list(range(1, n_max + 1)) + [100]: print('1-based index of the first occurrence of %3i in the series:' % n_occur, stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1) print() n_gcd = 1000 s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd] assert all(gcd(prev, this) == 1 for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'
Convert this C# snippet to Python and keep its semantics consistent.
using System; using System.Collections.Generic; using System.Linq; static class Program { static List<int> l = new List<int>() { 1, 1 }; static int gcd(int a, int b) { return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; } static void Main(string[] args) { int max = 1000; int take = 15; int i = 1; int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 }; do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; } while (l.Count < max || l[l.Count - 2] != selection.Last()); Console.Write("The first {0} items In the Stern-Brocot sequence: ", take); Console.WriteLine("{0}\n", string.Join(", ", l.Take(take))); Console.WriteLine("The locations of where the selected numbers (1-to-10, & 100) first appear:"); foreach (int ii in selection) { int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine("{0,3}: {1:n0}", ii, j); } Console.WriteLine(); bool good = true; for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } } Console.WriteLine("The greatest common divisor of all the two consecutive items of the" + " series up to the {0}th item is {1}always one.", max, good ? "" : "not "); } }
def stern_brocot(predicate=lambda series: len(series) < 20): sb, i = [1, 1], 0 while predicate(sb): sb += [sum(sb[i:i + 2]), sb[i + 1]] i += 1 return sb if __name__ == '__main__': from fractions import gcd n_first = 15 print('The first %i values:\n ' % n_first, stern_brocot(lambda series: len(series) < n_first)[:n_first]) print() n_max = 10 for n_occur in list(range(1, n_max + 1)) + [100]: print('1-based index of the first occurrence of %3i in the series:' % n_occur, stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1) print() n_gcd = 1000 s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd] assert all(gcd(prev, this) == 1 for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'
Write the same code in Python as shown below in C#.
public static class XMLSystem { static XMLSystem() { } public static XmlDocument GetXML(string name) { return null; } }
class Doc(object): def method(self, num): pass
Translate this program into Python but keep the logic exactly as in C#.
using System; namespace ApolloniusProblemCalc { class Program { static float rs = 0; static float xs = 0; static float ys = 0; public static void Main(string[] args) { float gx1; float gy1; float gr1; float gx2; float gy2; float gr2; float gx3; float gy3; float gr3; gx1 = 0; gy1 = 0; gr1 = 1; gx2 = 4; gy2 = 0; gr2 = 1; gx3 = 2; gy3 = 4; gr3 = 2; for (int i = 1; i <= 8; i++) { SolveTheApollonius(i, gx1, gy1, gr1, gx2, gy2, gr2, gx3, gy3, gr3); if (i == 1) { Console.WriteLine("X of point of the " + i + "st solution: " + xs.ToString()); Console.WriteLine("Y of point of the " + i + "st solution: " + ys.ToString()); Console.WriteLine(i + "st Solution circle's radius: " + rs.ToString()); } else if (i == 2) { Console.WriteLine("X of point of the " + i + "ed solution: " + xs.ToString()); Console.WriteLine("Y of point of the " + i + "ed solution: " + ys.ToString()); Console.WriteLine(i + "ed Solution circle's radius: " + rs.ToString()); } else if(i == 3) { Console.WriteLine("X of point of the " + i + "rd solution: " + xs.ToString()); Console.WriteLine("Y of point of the " + i + "rd solution: " + ys.ToString()); Console.WriteLine(i + "rd Solution circle's radius: " + rs.ToString()); } else { Console.WriteLine("X of point of the " + i + "th solution: " + xs.ToString()); Console.WriteLine("Y of point of the " + i + "th solution: " + ys.ToString()); Console.WriteLine(i + "th Solution circle's radius: " + rs.ToString()); } Console.WriteLine(); } Console.ReadKey(true); } private static void SolveTheApollonius(int calcCounter, float x1, float y1, float r1, float x2, float y2, float r2, float x3, float y3, float r3) { float s1 = 1; float s2 = 1; float s3 = 1; if (calcCounter == 2) { s1 = -1; s2 = -1; s3 = -1; } else if (calcCounter == 3) { s1 = 1; s2 = -1; s3 = -1; } else if (calcCounter == 4) { s1 = -1; s2 = 1; s3 = -1; } else if (calcCounter == 5) { s1 = -1; s2 = -1; s3 = 1; } else if (calcCounter == 6) { s1 = 1; s2 = 1; s3 = -1; } else if (calcCounter == 7) { s1 = -1; s2 = 1; s3 = 1; } else if (calcCounter == 8) { s1 = 1; s2 = -1; s3 = 1; } float v11 = 2 * x2 - 2 * x1; float v12 = 2 * y2 - 2 * y1; float v13 = x1 * x1 - x2 * x2 + y1 * y1 - y2 * y2 - r1 * r1 + r2 * r2; float v14 = 2 * s2 * r2 - 2 * s1 * r1; float v21 = 2 * x3 - 2 * x2; float v22 = 2 * y3 - 2 * y2; float v23 = x2 * x2 - x3 * x3 + y2 * y2 - y3 * y3 - r2 * r2 + r3 * r3; float v24 = 2 * s3 * r3 - 2 * s2 * r2; float w12 = v12 / v11; float w13 = v13 / v11; float w14 = v14 / v11; float w22 = v22 / v21 - w12; float w23 = v23 / v21 - w13; float w24 = v24 / v21 - w14; float P = -w23 / w22; float Q = w24 / w22; float M = -w12 * P - w13; float N = w14 - w12 * Q; float a = N * N + Q * Q - 1; float b = 2 * M * N - 2 * N * x1 + 2 * P * Q - 2 * Q * y1 + 2 * s1 * r1; float c = x1 * x1 + M * M - 2 * M * x1 + P * P + y1 * y1 - 2 * P * y1 - r1 * r1; float D = b * b - 4 * a * c; rs = (-b - float.Parse(Math.Sqrt(D).ToString())) / (2 * float.Parse(a.ToString())); xs = M + N * rs; ys = P + Q * rs; } } }
from collections import namedtuple import math Circle = namedtuple('Circle', 'x, y, r') def solveApollonius(c1, c2, c3, s1, s2, s3): x1, y1, r1 = c1 x2, y2, r2 = c2 x3, y3, r3 = c3 v11 = 2*x2 - 2*x1 v12 = 2*y2 - 2*y1 v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2 v14 = 2*s2*r2 - 2*s1*r1 v21 = 2*x3 - 2*x2 v22 = 2*y3 - 2*y2 v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3 v24 = 2*s3*r3 - 2*s2*r2 w12 = v12/v11 w13 = v13/v11 w14 = v14/v11 w22 = v22/v21-w12 w23 = v23/v21-w13 w24 = v24/v21-w14 P = -w23/w22 Q = w24/w22 M = -w12*P-w13 N = w14 - w12*Q a = N*N + Q*Q - 1 b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1 c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1 D = b*b-4*a*c rs = (-b-math.sqrt(D))/(2*a) xs = M+N*rs ys = P+Q*rs return Circle(xs, ys, rs) if __name__ == '__main__': c1, c2, c3 = Circle(0, 0, 1), Circle(4, 0, 1), Circle(2, 4, 2) print(solveApollonius(c1, c2, c3, 1, 1, 1)) print(solveApollonius(c1, c2, c3, -1, -1, -1))
Change the programming language of this snippet from C# to Python without modifying what it does.
using System; using System.Collections.Generic; using System.Net.Sockets; using System.Text; using System.Threading; namespace ChatServer { class State { private TcpClient client; private StringBuilder sb = new StringBuilder(); public string Name { get; } public State(string name, TcpClient client) { Name = name; this.client = client; } public void Add(byte b) { sb.Append((char)b); } public void Send(string text) { var bytes = Encoding.ASCII.GetBytes(string.Format("{0}\r\n", text)); client.GetStream().Write(bytes, 0, bytes.Length); } } class Program { static TcpListener listen; static Thread serverthread; static Dictionary<int, State> connections = new Dictionary<int, State>(); static void Main(string[] args) { listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 4004); serverthread = new Thread(new ThreadStart(DoListen)); serverthread.Start(); } private static void DoListen() { listen.Start(); Console.WriteLine("Server: Started server"); while (true) { Console.WriteLine("Server: Waiting..."); TcpClient client = listen.AcceptTcpClient(); Console.WriteLine("Server: Waited"); Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient)); clientThread.Start(client); } } private static void DoClient(object client) { TcpClient tClient = (TcpClient)client; Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId); byte[] bytes = Encoding.ASCII.GetBytes("Enter name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); string name = string.Empty; bool done = false; do { if (!tClient.Connected) { Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } name = Receive(tClient); done = true; if (done) { foreach (var cl in connections) { var state = cl.Value; if (state.Name == name) { bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); done = false; } } } } while (!done); connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient)); Console.WriteLine("\tTotal connections: {0}", connections.Count); Broadcast(string.Format("+++ {0} arrived +++", name)); do { string text = Receive(tClient); if (text == "/quit") { Broadcast(string.Format("Connection from {0} closed.", name)); connections.Remove(Thread.CurrentThread.ManagedThreadId); Console.WriteLine("\tTotal connections: {0}", connections.Count); break; } if (!tClient.Connected) { break; } Broadcast(string.Format("{0}> {1}", name, text)); } while (true); Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } private static string Receive(TcpClient client) { StringBuilder sb = new StringBuilder(); do { if (client.Available > 0) { while (client.Available > 0) { char ch = (char)client.GetStream().ReadByte(); if (ch == '\r') { continue; } if (ch == '\n') { return sb.ToString(); } sb.Append(ch); } } Thread.Sleep(100); } while (true); } private static void Broadcast(string text) { Console.WriteLine(text); foreach (var oClient in connections) { if (oClient.Key != Thread.CurrentThread.ManagedThreadId) { State state = oClient.Value; state.Send(text); } } } } }
import socket import thread import time HOST = "" PORT = 4004 def accept(conn): def threaded(): while True: conn.send("Please enter your name: ") try: name = conn.recv(1024).strip() except socket.error: continue if name in users: conn.send("Name entered is already in use.\n") elif name: conn.setblocking(False) users[name] = conn broadcast(name, "+++ %s arrived +++" % name) break thread.start_new_thread(threaded, ()) def broadcast(name, message): print message for to_name, conn in users.items(): if to_name != name: try: conn.send(message + "\n") except socket.error: pass server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.setblocking(False) server.bind((HOST, PORT)) server.listen(1) print "Listening on %s" % ("%s:%s" % server.getsockname()) users = {} while True: try: while True: try: conn, addr = server.accept() except socket.error: break accept(conn) for name, conn in users.items(): try: message = conn.recv(1024) except socket.error: continue if not message: del users[name] broadcast(name, "--- %s leaves ---" % name) else: broadcast(name, "%s> %s" % (name, message.strip())) time.sleep(.1) except (SystemExit, KeyboardInterrupt): break
Convert the following code from C# to Python, ensuring the logic remains intact.
using System; using System.Collections.Generic; using System.IO; using System.Text; class Program { public class FastaEntry { public string Name { get; set; } public StringBuilder Sequence { get; set; } } static IEnumerable<FastaEntry> ParseFasta(StreamReader fastaFile) { FastaEntry f = null; string line; while ((line = fastaFile.ReadLine()) != null) { if (line.StartsWith(";")) continue; if (line.StartsWith(">")) { if (f != null) yield return f; f = new FastaEntry { Name = line.Substring(1), Sequence = new StringBuilder() }; } else if (f != null) f.Sequence.Append(line); } yield return f; } static void Main(string[] args) { try { using (var fastaFile = new StreamReader("fasta.txt")) { foreach (FastaEntry f in ParseFasta(fastaFile)) Console.WriteLine("{0}: {1}", f.Name, f.Sequence); } } catch (FileNotFoundException e) { Console.WriteLine(e); } Console.ReadLine(); } }
import io FASTA= infile = io.StringIO(FASTA) def fasta_parse(infile): key = '' for line in infile: if line.startswith('>'): if key: yield key, val key, val = line[1:].rstrip().split()[0], '' elif key: val += line.rstrip() if key: yield key, val print('\n'.join('%s: %s' % keyval for keyval in fasta_parse(infile)))
Port the provided C# code into Python while preserving the original functionality.
using System; using System.Collections.Generic; using System.Linq; public class FindPalindromicNumbers { static void Main(string[] args) { var query = PalindromicTernaries() .Where(IsPalindromicBinary) .Take(6); foreach (var x in query) { Console.WriteLine("Decimal: " + x); Console.WriteLine("Ternary: " + ToTernary(x)); Console.WriteLine("Binary: " + Convert.ToString(x, 2)); Console.WriteLine(); } } public static IEnumerable<long> PalindromicTernaries() { yield return 0; yield return 1; yield return 13; yield return 23; var f = new List<long> {0}; long fMiddle = 9; while (true) { for (long edge = 1; edge < 3; edge++) { int i; do { long result = fMiddle; long fLeft = fMiddle * 3; long fRight = fMiddle / 3; for (int j = f.Count - 1; j >= 0; j--) { result += (fLeft + fRight) * f[j]; fLeft *= 3; fRight /= 3; } result += (fLeft + fRight) * edge; yield return result; for (i = f.Count - 1; i >= 0; i--) { if (f[i] == 2) { f[i] = 0; } else { f[i]++; break; } } } while (i >= 0); } f.Add(0); fMiddle *= 3; } } public static bool IsPalindromicBinary(long number) { long n = number; long reverse = 0; while (n != 0) { reverse <<= 1; if ((n & 1) == 1) reverse++; n >>= 1; } return reverse == number; } public static string ToTernary(long n) { if (n == 0) return "0"; string result = ""; while (n > 0) { { result = (n % 3) + result; n /= 3; } return result; } }
from itertools import islice digits = "0123456789abcdefghijklmnopqrstuvwxyz" def baseN(num,b): if num == 0: return "0" result = "" while num != 0: num, d = divmod(num, b) result += digits[d] return result[::-1] def pal2(num): if num == 0 or num == 1: return True based = bin(num)[2:] return based == based[::-1] def pal_23(): yield 0 yield 1 n = 1 while True: n += 1 b = baseN(n, 3) revb = b[::-1] for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb), '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)): t = int(trial, 3) if pal2(t): yield t for pal23 in islice(pal_23(), 6): print(pal23, baseN(pal23, 3), baseN(pal23, 2))
Port the provided C# code into Python while preserving the original functionality.
using System; using System.Collections.Generic; using System.Linq; public class FindPalindromicNumbers { static void Main(string[] args) { var query = PalindromicTernaries() .Where(IsPalindromicBinary) .Take(6); foreach (var x in query) { Console.WriteLine("Decimal: " + x); Console.WriteLine("Ternary: " + ToTernary(x)); Console.WriteLine("Binary: " + Convert.ToString(x, 2)); Console.WriteLine(); } } public static IEnumerable<long> PalindromicTernaries() { yield return 0; yield return 1; yield return 13; yield return 23; var f = new List<long> {0}; long fMiddle = 9; while (true) { for (long edge = 1; edge < 3; edge++) { int i; do { long result = fMiddle; long fLeft = fMiddle * 3; long fRight = fMiddle / 3; for (int j = f.Count - 1; j >= 0; j--) { result += (fLeft + fRight) * f[j]; fLeft *= 3; fRight /= 3; } result += (fLeft + fRight) * edge; yield return result; for (i = f.Count - 1; i >= 0; i--) { if (f[i] == 2) { f[i] = 0; } else { f[i]++; break; } } } while (i >= 0); } f.Add(0); fMiddle *= 3; } } public static bool IsPalindromicBinary(long number) { long n = number; long reverse = 0; while (n != 0) { reverse <<= 1; if ((n & 1) == 1) reverse++; n >>= 1; } return reverse == number; } public static string ToTernary(long n) { if (n == 0) return "0"; string result = ""; while (n > 0) { { result = (n % 3) + result; n /= 3; } return result; } }
from itertools import islice digits = "0123456789abcdefghijklmnopqrstuvwxyz" def baseN(num,b): if num == 0: return "0" result = "" while num != 0: num, d = divmod(num, b) result += digits[d] return result[::-1] def pal2(num): if num == 0 or num == 1: return True based = bin(num)[2:] return based == based[::-1] def pal_23(): yield 0 yield 1 n = 1 while True: n += 1 b = baseN(n, 3) revb = b[::-1] for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb), '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)): t = int(trial, 3) if pal2(t): yield t for pal23 in islice(pal_23(), 6): print(pal23, baseN(pal23, 3), baseN(pal23, 2))
Produce a language-to-language conversion: from C# to Python, same semantics.
static void Main(string[] args) { int bufferHeight = Console.BufferHeight; int bufferWidth = Console.BufferWidth; int windowHeight = Console.WindowHeight; int windowWidth = Console.WindowWidth; Console.Write("Buffer Height: "); Console.WriteLine(bufferHeight); Console.Write("Buffer Width: "); Console.WriteLine(bufferWidth); Console.Write("Window Height: "); Console.WriteLine(windowHeight); Console.Write("Window Width: "); Console.WriteLine(windowWidth); Console.ReadLine(); }
import os def get_windows_terminal(): from ctypes import windll, create_string_buffer h = windll.kernel32.GetStdHandle(-12) csbi = create_string_buffer(22) res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi) if not res: return 80, 25 import struct (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy)\ = struct.unpack("hhhhHhhhhhh", csbi.raw) width = right - left + 1 height = bottom - top + 1 return width, height def get_linux_terminal(): width = os.popen('tput cols', 'r').readline() height = os.popen('tput lines', 'r').readline() return int(width), int(height) print get_linux_terminal() if os.name == 'posix' else get_windows_terminal()
Maintain the same structure and functionality when rewriting this code in Python.
using System; using System.Numerics; namespace CipollaAlgorithm { class Program { static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151; private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) { BigInteger n = BigInteger.Parse(ns); BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG; BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p); if (ls(n) != 1) { return new Tuple<BigInteger, BigInteger, bool>(0, 0, false); } BigInteger a = 0; BigInteger omega2; while (true) { omega2 = (a * a + p - n) % p; if (ls(omega2) == p - 1) { break; } a += 1; } BigInteger finalOmega = omega2; Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) { return new Tuple<BigInteger, BigInteger>( (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p ); } Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0); Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1); BigInteger nn = ((p + 1) >> 1) % p; while (nn > 0) { if ((nn & 1) == 1) { r = mul(r, s); } s = mul(s, s); nn >>= 1; } if (r.Item2 != 0) { return new Tuple<BigInteger, BigInteger, bool>(0, 0, false); } if (r.Item1 * r.Item1 % p != n) { return new Tuple<BigInteger, BigInteger, bool>(0, 0, false); } return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true); } static void Main(string[] args) { Console.WriteLine(C("10", "13")); Console.WriteLine(C("56", "101")); Console.WriteLine(C("8218", "10007")); Console.WriteLine(C("8219", "10007")); Console.WriteLine(C("331575", "1000003")); Console.WriteLine(C("665165880", "1000000007")); Console.WriteLine(C("881398088036", "1000000000039")); Console.WriteLine(C("34035243914635549601583369544560650254325084643201", "")); } } }
def convertToBase(n, b): if(n < 2): return [n]; temp = n; ans = []; while(temp != 0): ans = [temp % b]+ ans; temp /= b; return ans; def cipolla(n,p): n %= p if(n == 0 or n == 1): return (n,-n%p) phi = p - 1 if(pow(n, phi/2, p) != 1): return () if(p%4 == 3): ans = pow(n,(p+1)/4,p) return (ans,-ans%p) aa = 0 for i in xrange(1,p): temp = pow((i*i-n)%p,phi/2,p) if(temp == phi): aa = i break; exponent = convertToBase((p+1)/2,2) def cipollaMult((a,b),(c,d),w,p): return ((a*c+b*d*w)%p,(a*d+b*c)%p) x1 = (aa,1) x2 = cipollaMult(x1,x1,aa*aa-n,p) for i in xrange(1,len(exponent)): if(exponent[i] == 0): x2 = cipollaMult(x2,x1,aa*aa-n,p) x1 = cipollaMult(x1,x1,aa*aa-n,p) else: x1 = cipollaMult(x1,x2,aa*aa-n,p) x2 = cipollaMult(x2,x2,aa*aa-n,p) return (x1[0],-x1[0]%p) print "Roots of 2 mod 7: " +str(cipolla(2,7)) print "Roots of 8218 mod 10007: " +str(cipolla(8218,10007)) print "Roots of 56 mod 101: " +str(cipolla(56,101)) print "Roots of 1 mod 11: " +str(cipolla(1,11)) print "Roots of 8219 mod 10007: " +str(cipolla(8219,10007))
Change the following C# code into Python without altering its purpose.
using System; using System.Numerics; namespace CipollaAlgorithm { class Program { static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151; private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) { BigInteger n = BigInteger.Parse(ns); BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG; BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p); if (ls(n) != 1) { return new Tuple<BigInteger, BigInteger, bool>(0, 0, false); } BigInteger a = 0; BigInteger omega2; while (true) { omega2 = (a * a + p - n) % p; if (ls(omega2) == p - 1) { break; } a += 1; } BigInteger finalOmega = omega2; Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) { return new Tuple<BigInteger, BigInteger>( (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p ); } Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0); Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1); BigInteger nn = ((p + 1) >> 1) % p; while (nn > 0) { if ((nn & 1) == 1) { r = mul(r, s); } s = mul(s, s); nn >>= 1; } if (r.Item2 != 0) { return new Tuple<BigInteger, BigInteger, bool>(0, 0, false); } if (r.Item1 * r.Item1 % p != n) { return new Tuple<BigInteger, BigInteger, bool>(0, 0, false); } return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true); } static void Main(string[] args) { Console.WriteLine(C("10", "13")); Console.WriteLine(C("56", "101")); Console.WriteLine(C("8218", "10007")); Console.WriteLine(C("8219", "10007")); Console.WriteLine(C("331575", "1000003")); Console.WriteLine(C("665165880", "1000000007")); Console.WriteLine(C("881398088036", "1000000000039")); Console.WriteLine(C("34035243914635549601583369544560650254325084643201", "")); } } }
def convertToBase(n, b): if(n < 2): return [n]; temp = n; ans = []; while(temp != 0): ans = [temp % b]+ ans; temp /= b; return ans; def cipolla(n,p): n %= p if(n == 0 or n == 1): return (n,-n%p) phi = p - 1 if(pow(n, phi/2, p) != 1): return () if(p%4 == 3): ans = pow(n,(p+1)/4,p) return (ans,-ans%p) aa = 0 for i in xrange(1,p): temp = pow((i*i-n)%p,phi/2,p) if(temp == phi): aa = i break; exponent = convertToBase((p+1)/2,2) def cipollaMult((a,b),(c,d),w,p): return ((a*c+b*d*w)%p,(a*d+b*c)%p) x1 = (aa,1) x2 = cipollaMult(x1,x1,aa*aa-n,p) for i in xrange(1,len(exponent)): if(exponent[i] == 0): x2 = cipollaMult(x2,x1,aa*aa-n,p) x1 = cipollaMult(x1,x1,aa*aa-n,p) else: x1 = cipollaMult(x1,x2,aa*aa-n,p) x2 = cipollaMult(x2,x2,aa*aa-n,p) return (x1[0],-x1[0]%p) print "Roots of 2 mod 7: " +str(cipolla(2,7)) print "Roots of 8218 mod 10007: " +str(cipolla(8218,10007)) print "Roots of 56 mod 101: " +str(cipolla(56,101)) print "Roots of 1 mod 11: " +str(cipolla(1,11)) print "Roots of 8219 mod 10007: " +str(cipolla(8219,10007))
Write the same code in Python as shown below in C#.
using System; using System.Numerics; namespace CipollaAlgorithm { class Program { static readonly BigInteger BIG = BigInteger.Pow(10, 50) + 151; private static Tuple<BigInteger, BigInteger, bool> C(string ns, string ps) { BigInteger n = BigInteger.Parse(ns); BigInteger p = ps.Length > 0 ? BigInteger.Parse(ps) : BIG; BigInteger ls(BigInteger a0) => BigInteger.ModPow(a0, (p - 1) / 2, p); if (ls(n) != 1) { return new Tuple<BigInteger, BigInteger, bool>(0, 0, false); } BigInteger a = 0; BigInteger omega2; while (true) { omega2 = (a * a + p - n) % p; if (ls(omega2) == p - 1) { break; } a += 1; } BigInteger finalOmega = omega2; Tuple<BigInteger, BigInteger> mul(Tuple<BigInteger, BigInteger> aa, Tuple<BigInteger, BigInteger> bb) { return new Tuple<BigInteger, BigInteger>( (aa.Item1 * bb.Item1 + aa.Item2 * bb.Item2 * finalOmega) % p, (aa.Item1 * bb.Item2 + bb.Item1 * aa.Item2) % p ); } Tuple<BigInteger, BigInteger> r = new Tuple<BigInteger, BigInteger>(1, 0); Tuple<BigInteger, BigInteger> s = new Tuple<BigInteger, BigInteger>(a, 1); BigInteger nn = ((p + 1) >> 1) % p; while (nn > 0) { if ((nn & 1) == 1) { r = mul(r, s); } s = mul(s, s); nn >>= 1; } if (r.Item2 != 0) { return new Tuple<BigInteger, BigInteger, bool>(0, 0, false); } if (r.Item1 * r.Item1 % p != n) { return new Tuple<BigInteger, BigInteger, bool>(0, 0, false); } return new Tuple<BigInteger, BigInteger, bool>(r.Item1, p - r.Item1, true); } static void Main(string[] args) { Console.WriteLine(C("10", "13")); Console.WriteLine(C("56", "101")); Console.WriteLine(C("8218", "10007")); Console.WriteLine(C("8219", "10007")); Console.WriteLine(C("331575", "1000003")); Console.WriteLine(C("665165880", "1000000007")); Console.WriteLine(C("881398088036", "1000000000039")); Console.WriteLine(C("34035243914635549601583369544560650254325084643201", "")); } } }
def convertToBase(n, b): if(n < 2): return [n]; temp = n; ans = []; while(temp != 0): ans = [temp % b]+ ans; temp /= b; return ans; def cipolla(n,p): n %= p if(n == 0 or n == 1): return (n,-n%p) phi = p - 1 if(pow(n, phi/2, p) != 1): return () if(p%4 == 3): ans = pow(n,(p+1)/4,p) return (ans,-ans%p) aa = 0 for i in xrange(1,p): temp = pow((i*i-n)%p,phi/2,p) if(temp == phi): aa = i break; exponent = convertToBase((p+1)/2,2) def cipollaMult((a,b),(c,d),w,p): return ((a*c+b*d*w)%p,(a*d+b*c)%p) x1 = (aa,1) x2 = cipollaMult(x1,x1,aa*aa-n,p) for i in xrange(1,len(exponent)): if(exponent[i] == 0): x2 = cipollaMult(x2,x1,aa*aa-n,p) x1 = cipollaMult(x1,x1,aa*aa-n,p) else: x1 = cipollaMult(x1,x2,aa*aa-n,p) x2 = cipollaMult(x2,x2,aa*aa-n,p) return (x1[0],-x1[0]%p) print "Roots of 2 mod 7: " +str(cipolla(2,7)) print "Roots of 8218 mod 10007: " +str(cipolla(8218,10007)) print "Roots of 56 mod 101: " +str(cipolla(56,101)) print "Roots of 1 mod 11: " +str(cipolla(1,11)) print "Roots of 8219 mod 10007: " +str(cipolla(8219,10007))
Rewrite this program in Python while keeping its functionality equivalent to the C# version.
string path = @"C:\Windows\System32"; string multiline = @"Line 1. Line 2. Line 3.";
'c' == "c" 'text' == "text" ' " ' " ' " '\x20' == ' ' u'unicode string' u'\u05d0'
Keep all operations the same but rewrite the snippet in Python.
using System; using System.Drawing; using System.Windows.Forms; static class Program { static void Main() { Rectangle bounds = Screen.PrimaryScreen.Bounds; Console.WriteLine($"Primary screen bounds: {bounds.Width}x{bounds.Height}"); Rectangle workingArea = Screen.PrimaryScreen.WorkingArea; Console.WriteLine($"Primary screen working area: {workingArea.Width}x{workingArea.Height}"); } }
import tkinter as tk root = tk.Tk() root.state('zoomed') root.update_idletasks() tk.Label(root, text=(str(root.winfo_width())+ " x " +str(root.winfo_height())), font=("Helvetica", 25)).pack() root.mainloop()
Translate the given C# code snippet into Python without altering its behavior.
enum fruits { apple, banana, cherry } enum fruits { apple = 0, banana = 1, cherry = 2 } enum fruits : int { apple = 0, banana = 1, cherry = 2 } [FlagsAttribute] enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }
>>> from enum import Enum >>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE') >>> Contact.__members__ mappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)])) >>> >>> >>> class Contact2(Enum): FIRST_NAME = 1 LAST_NAME = 2 PHONE = 3 >>> Contact2.__members__ mappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)])) >>>
Translate this program into Python but keep the logic exactly as in C#.
using System; using System.Collections.Generic; namespace A_star { class A_star { public class Coordinates : IEquatable<Coordinates> { public int row; public int col; public Coordinates() { this.row = -1; this.col = -1; } public Coordinates(int row, int col) { this.row = row; this.col = col; } public Boolean Equals(Coordinates c) { if (this.row == c.row && this.col == c.col) return true; else return false; } } public class Cell { public int cost; public int g; public int f; public Coordinates parent; } public class Astar { public Cell[,] cells = new Cell[8, 8]; public List<Coordinates> path = new List<Coordinates>(); public List<Coordinates> opened = new List<Coordinates>(); public List<Coordinates> closed = new List<Coordinates>(); public Coordinates startCell = new Coordinates(0, 0); public Coordinates finishCell = new Coordinates(7, 7); public Astar() { for (int i = 0; i < 8; i++) for (int j = 0; j < 8; j++) { cells[i, j] = new Cell(); cells[i, j].parent = new Coordinates(); if (IsAWall(i, j)) cells[i, j].cost = 100; else cells[i, j].cost = 1; } opened.Add(startCell); Boolean pathFound = false; do { List<Coordinates> neighbors = new List<Coordinates>(); Coordinates currentCell = ShorterExpectedPath(); neighbors = neighborsCells(currentCell); foreach (Coordinates newCell in neighbors) { if (newCell.row == finishCell.row && newCell.col == finishCell.col) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; pathFound = true; break; } else if (!opened.Contains(newCell) && !closed.Contains(newCell)) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].f = cells[newCell.row, newCell.col].g + Heuristic(newCell); cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; SetCell(newCell, opened); } else if (cells[newCell.row, newCell.col].g > cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].f = cells[newCell.row, newCell.col].g + Heuristic(newCell); cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; SetCell(newCell, opened); ResetCell(newCell, closed); } } SetCell(currentCell, closed); ResetCell(currentCell, opened); } while (opened.Count > 0 && pathFound == false); if (pathFound) { path.Add(finishCell); Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col); while (cells[currentCell.row, currentCell.col].parent.row >= 0) { path.Add(cells[currentCell.row, currentCell.col].parent); int tmp_row = cells[currentCell.row, currentCell.col].parent.row; currentCell.col = cells[currentCell.row, currentCell.col].parent.col; currentCell.row = tmp_row; } for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { char gr = '.'; if (path.Contains(new Coordinates(i, j))) { gr = 'X'; } else if (cells[i, j].cost > 1) { gr = '\u2588'; } System.Console.Write(gr); } System.Console.WriteLine(); } System.Console.Write("\nPath: "); for (int i = path.Count - 1; i >= 0; i--) { System.Console.Write("({0},{1})", path[i].row, path[i].col); } System.Console.WriteLine("\nPath cost: {0}", path.Count - 1); String wt = System.Console.ReadLine(); } } public Coordinates ShorterExpectedPath() { int sep = 0; if (opened.Count > 1) { for (int i = 1; i < opened.Count; i++) { if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row, opened[sep].col].f) { sep = i; } } } return opened[sep]; } public List<Coordinates> neighborsCells(Coordinates c) { List<Coordinates> lc = new List<Coordinates>(); for (int i = -1; i <= 1; i++) for (int j = -1; j <= 1; j++) if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 && (i != 0 || j != 0)) { lc.Add(new Coordinates(c.row + i, c.col + j)); } return lc; } public bool IsAWall(int row, int col) { int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 }, { 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } }; bool found = false; for (int i = 0; i < walls.GetLength(0); i++) if (walls[i,0] == row && walls[i,1] == col) found = true; return found; } public int Heuristic(Coordinates cell) { int dRow = Math.Abs(finishCell.row - cell.row); int dCol = Math.Abs(finishCell.col - cell.col); return Math.Max(dRow, dCol); } public void SetCell(Coordinates cell, List<Coordinates> coordinatesList) { if (coordinatesList.Contains(cell) == false) { coordinatesList.Add(cell); } } public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList) { if (coordinatesList.Contains(cell)) { coordinatesList.Remove(cell); } } } static void Main(string[] args) { Astar astar = new Astar(); } } }
from __future__ import print_function import matplotlib.pyplot as plt class AStarGraph(object): def __init__(self): self.barriers = [] self.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)]) def heuristic(self, start, goal): D = 1 D2 = 1 dx = abs(start[0] - goal[0]) dy = abs(start[1] - goal[1]) return D * (dx + dy) + (D2 - 2 * D) * min(dx, dy) def get_vertex_neighbours(self, pos): n = [] for dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]: x2 = pos[0] + dx y2 = pos[1] + dy if x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7: continue n.append((x2, y2)) return n def move_cost(self, a, b): for barrier in self.barriers: if b in barrier: return 100 return 1 def AStarSearch(start, end, graph): G = {} F = {} G[start] = 0 F[start] = graph.heuristic(start, end) closedVertices = set() openVertices = set([start]) cameFrom = {} while len(openVertices) > 0: current = None currentFscore = None for pos in openVertices: if current is None or F[pos] < currentFscore: currentFscore = F[pos] current = pos if current == end: path = [current] while current in cameFrom: current = cameFrom[current] path.append(current) path.reverse() return path, F[end] openVertices.remove(current) closedVertices.add(current) for neighbour in graph.get_vertex_neighbours(current): if neighbour in closedVertices: continue candidateG = G[current] + graph.move_cost(current, neighbour) if neighbour not in openVertices: openVertices.add(neighbour) elif candidateG >= G[neighbour]: continue cameFrom[neighbour] = current G[neighbour] = candidateG H = graph.heuristic(neighbour, end) F[neighbour] = G[neighbour] + H raise RuntimeError("A* failed to find a solution") if __name__=="__main__": graph = AStarGraph() result, cost = AStarSearch((0,0), (7,7), graph) print ("route", result) print ("cost", cost) plt.plot([v[0] for v in result], [v[1] for v in result]) for barrier in graph.barriers: plt.plot([v[0] for v in barrier], [v[1] for v in barrier]) plt.xlim(-1,8) plt.ylim(-1,8) plt.show()
Port the following code from C# to Python with equivalent syntax and logic.
using System; using System.Collections.Generic; namespace A_star { class A_star { public class Coordinates : IEquatable<Coordinates> { public int row; public int col; public Coordinates() { this.row = -1; this.col = -1; } public Coordinates(int row, int col) { this.row = row; this.col = col; } public Boolean Equals(Coordinates c) { if (this.row == c.row && this.col == c.col) return true; else return false; } } public class Cell { public int cost; public int g; public int f; public Coordinates parent; } public class Astar { public Cell[,] cells = new Cell[8, 8]; public List<Coordinates> path = new List<Coordinates>(); public List<Coordinates> opened = new List<Coordinates>(); public List<Coordinates> closed = new List<Coordinates>(); public Coordinates startCell = new Coordinates(0, 0); public Coordinates finishCell = new Coordinates(7, 7); public Astar() { for (int i = 0; i < 8; i++) for (int j = 0; j < 8; j++) { cells[i, j] = new Cell(); cells[i, j].parent = new Coordinates(); if (IsAWall(i, j)) cells[i, j].cost = 100; else cells[i, j].cost = 1; } opened.Add(startCell); Boolean pathFound = false; do { List<Coordinates> neighbors = new List<Coordinates>(); Coordinates currentCell = ShorterExpectedPath(); neighbors = neighborsCells(currentCell); foreach (Coordinates newCell in neighbors) { if (newCell.row == finishCell.row && newCell.col == finishCell.col) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; pathFound = true; break; } else if (!opened.Contains(newCell) && !closed.Contains(newCell)) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].f = cells[newCell.row, newCell.col].g + Heuristic(newCell); cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; SetCell(newCell, opened); } else if (cells[newCell.row, newCell.col].g > cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].f = cells[newCell.row, newCell.col].g + Heuristic(newCell); cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; SetCell(newCell, opened); ResetCell(newCell, closed); } } SetCell(currentCell, closed); ResetCell(currentCell, opened); } while (opened.Count > 0 && pathFound == false); if (pathFound) { path.Add(finishCell); Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col); while (cells[currentCell.row, currentCell.col].parent.row >= 0) { path.Add(cells[currentCell.row, currentCell.col].parent); int tmp_row = cells[currentCell.row, currentCell.col].parent.row; currentCell.col = cells[currentCell.row, currentCell.col].parent.col; currentCell.row = tmp_row; } for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { char gr = '.'; if (path.Contains(new Coordinates(i, j))) { gr = 'X'; } else if (cells[i, j].cost > 1) { gr = '\u2588'; } System.Console.Write(gr); } System.Console.WriteLine(); } System.Console.Write("\nPath: "); for (int i = path.Count - 1; i >= 0; i--) { System.Console.Write("({0},{1})", path[i].row, path[i].col); } System.Console.WriteLine("\nPath cost: {0}", path.Count - 1); String wt = System.Console.ReadLine(); } } public Coordinates ShorterExpectedPath() { int sep = 0; if (opened.Count > 1) { for (int i = 1; i < opened.Count; i++) { if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row, opened[sep].col].f) { sep = i; } } } return opened[sep]; } public List<Coordinates> neighborsCells(Coordinates c) { List<Coordinates> lc = new List<Coordinates>(); for (int i = -1; i <= 1; i++) for (int j = -1; j <= 1; j++) if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 && (i != 0 || j != 0)) { lc.Add(new Coordinates(c.row + i, c.col + j)); } return lc; } public bool IsAWall(int row, int col) { int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 }, { 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } }; bool found = false; for (int i = 0; i < walls.GetLength(0); i++) if (walls[i,0] == row && walls[i,1] == col) found = true; return found; } public int Heuristic(Coordinates cell) { int dRow = Math.Abs(finishCell.row - cell.row); int dCol = Math.Abs(finishCell.col - cell.col); return Math.Max(dRow, dCol); } public void SetCell(Coordinates cell, List<Coordinates> coordinatesList) { if (coordinatesList.Contains(cell) == false) { coordinatesList.Add(cell); } } public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList) { if (coordinatesList.Contains(cell)) { coordinatesList.Remove(cell); } } } static void Main(string[] args) { Astar astar = new Astar(); } } }
from __future__ import print_function import matplotlib.pyplot as plt class AStarGraph(object): def __init__(self): self.barriers = [] self.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)]) def heuristic(self, start, goal): D = 1 D2 = 1 dx = abs(start[0] - goal[0]) dy = abs(start[1] - goal[1]) return D * (dx + dy) + (D2 - 2 * D) * min(dx, dy) def get_vertex_neighbours(self, pos): n = [] for dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]: x2 = pos[0] + dx y2 = pos[1] + dy if x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7: continue n.append((x2, y2)) return n def move_cost(self, a, b): for barrier in self.barriers: if b in barrier: return 100 return 1 def AStarSearch(start, end, graph): G = {} F = {} G[start] = 0 F[start] = graph.heuristic(start, end) closedVertices = set() openVertices = set([start]) cameFrom = {} while len(openVertices) > 0: current = None currentFscore = None for pos in openVertices: if current is None or F[pos] < currentFscore: currentFscore = F[pos] current = pos if current == end: path = [current] while current in cameFrom: current = cameFrom[current] path.append(current) path.reverse() return path, F[end] openVertices.remove(current) closedVertices.add(current) for neighbour in graph.get_vertex_neighbours(current): if neighbour in closedVertices: continue candidateG = G[current] + graph.move_cost(current, neighbour) if neighbour not in openVertices: openVertices.add(neighbour) elif candidateG >= G[neighbour]: continue cameFrom[neighbour] = current G[neighbour] = candidateG H = graph.heuristic(neighbour, end) F[neighbour] = G[neighbour] + H raise RuntimeError("A* failed to find a solution") if __name__=="__main__": graph = AStarGraph() result, cost = AStarSearch((0,0), (7,7), graph) print ("route", result) print ("cost", cost) plt.plot([v[0] for v in result], [v[1] for v in result]) for barrier in graph.barriers: plt.plot([v[0] for v in barrier], [v[1] for v in barrier]) plt.xlim(-1,8) plt.ylim(-1,8) plt.show()
Generate a Python translation of this C# snippet without changing its computational steps.
using System; using System.Collections.Generic; namespace A_star { class A_star { public class Coordinates : IEquatable<Coordinates> { public int row; public int col; public Coordinates() { this.row = -1; this.col = -1; } public Coordinates(int row, int col) { this.row = row; this.col = col; } public Boolean Equals(Coordinates c) { if (this.row == c.row && this.col == c.col) return true; else return false; } } public class Cell { public int cost; public int g; public int f; public Coordinates parent; } public class Astar { public Cell[,] cells = new Cell[8, 8]; public List<Coordinates> path = new List<Coordinates>(); public List<Coordinates> opened = new List<Coordinates>(); public List<Coordinates> closed = new List<Coordinates>(); public Coordinates startCell = new Coordinates(0, 0); public Coordinates finishCell = new Coordinates(7, 7); public Astar() { for (int i = 0; i < 8; i++) for (int j = 0; j < 8; j++) { cells[i, j] = new Cell(); cells[i, j].parent = new Coordinates(); if (IsAWall(i, j)) cells[i, j].cost = 100; else cells[i, j].cost = 1; } opened.Add(startCell); Boolean pathFound = false; do { List<Coordinates> neighbors = new List<Coordinates>(); Coordinates currentCell = ShorterExpectedPath(); neighbors = neighborsCells(currentCell); foreach (Coordinates newCell in neighbors) { if (newCell.row == finishCell.row && newCell.col == finishCell.col) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; pathFound = true; break; } else if (!opened.Contains(newCell) && !closed.Contains(newCell)) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].f = cells[newCell.row, newCell.col].g + Heuristic(newCell); cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; SetCell(newCell, opened); } else if (cells[newCell.row, newCell.col].g > cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost) { cells[newCell.row, newCell.col].g = cells[currentCell.row, currentCell.col].g + cells[newCell.row, newCell.col].cost; cells[newCell.row, newCell.col].f = cells[newCell.row, newCell.col].g + Heuristic(newCell); cells[newCell.row, newCell.col].parent.row = currentCell.row; cells[newCell.row, newCell.col].parent.col = currentCell.col; SetCell(newCell, opened); ResetCell(newCell, closed); } } SetCell(currentCell, closed); ResetCell(currentCell, opened); } while (opened.Count > 0 && pathFound == false); if (pathFound) { path.Add(finishCell); Coordinates currentCell = new Coordinates(finishCell.row, finishCell.col); while (cells[currentCell.row, currentCell.col].parent.row >= 0) { path.Add(cells[currentCell.row, currentCell.col].parent); int tmp_row = cells[currentCell.row, currentCell.col].parent.row; currentCell.col = cells[currentCell.row, currentCell.col].parent.col; currentCell.row = tmp_row; } for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { char gr = '.'; if (path.Contains(new Coordinates(i, j))) { gr = 'X'; } else if (cells[i, j].cost > 1) { gr = '\u2588'; } System.Console.Write(gr); } System.Console.WriteLine(); } System.Console.Write("\nPath: "); for (int i = path.Count - 1; i >= 0; i--) { System.Console.Write("({0},{1})", path[i].row, path[i].col); } System.Console.WriteLine("\nPath cost: {0}", path.Count - 1); String wt = System.Console.ReadLine(); } } public Coordinates ShorterExpectedPath() { int sep = 0; if (opened.Count > 1) { for (int i = 1; i < opened.Count; i++) { if (cells[opened[i].row, opened[i].col].f < cells[opened[sep].row, opened[sep].col].f) { sep = i; } } } return opened[sep]; } public List<Coordinates> neighborsCells(Coordinates c) { List<Coordinates> lc = new List<Coordinates>(); for (int i = -1; i <= 1; i++) for (int j = -1; j <= 1; j++) if (c.row+i >= 0 && c.row+i < 8 && c.col+j >= 0 && c.col+j < 8 && (i != 0 || j != 0)) { lc.Add(new Coordinates(c.row + i, c.col + j)); } return lc; } public bool IsAWall(int row, int col) { int[,] walls = new int[,] { { 2, 4 }, { 2, 5 }, { 2, 6 }, { 3, 6 }, { 4, 6 }, { 5, 6 }, { 5, 5 }, { 5, 4 }, { 5, 3 }, { 5, 2 }, { 4, 2 }, { 3, 2 } }; bool found = false; for (int i = 0; i < walls.GetLength(0); i++) if (walls[i,0] == row && walls[i,1] == col) found = true; return found; } public int Heuristic(Coordinates cell) { int dRow = Math.Abs(finishCell.row - cell.row); int dCol = Math.Abs(finishCell.col - cell.col); return Math.Max(dRow, dCol); } public void SetCell(Coordinates cell, List<Coordinates> coordinatesList) { if (coordinatesList.Contains(cell) == false) { coordinatesList.Add(cell); } } public void ResetCell(Coordinates cell, List<Coordinates> coordinatesList) { if (coordinatesList.Contains(cell)) { coordinatesList.Remove(cell); } } } static void Main(string[] args) { Astar astar = new Astar(); } } }
from __future__ import print_function import matplotlib.pyplot as plt class AStarGraph(object): def __init__(self): self.barriers = [] self.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)]) def heuristic(self, start, goal): D = 1 D2 = 1 dx = abs(start[0] - goal[0]) dy = abs(start[1] - goal[1]) return D * (dx + dy) + (D2 - 2 * D) * min(dx, dy) def get_vertex_neighbours(self, pos): n = [] for dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]: x2 = pos[0] + dx y2 = pos[1] + dy if x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7: continue n.append((x2, y2)) return n def move_cost(self, a, b): for barrier in self.barriers: if b in barrier: return 100 return 1 def AStarSearch(start, end, graph): G = {} F = {} G[start] = 0 F[start] = graph.heuristic(start, end) closedVertices = set() openVertices = set([start]) cameFrom = {} while len(openVertices) > 0: current = None currentFscore = None for pos in openVertices: if current is None or F[pos] < currentFscore: currentFscore = F[pos] current = pos if current == end: path = [current] while current in cameFrom: current = cameFrom[current] path.append(current) path.reverse() return path, F[end] openVertices.remove(current) closedVertices.add(current) for neighbour in graph.get_vertex_neighbours(current): if neighbour in closedVertices: continue candidateG = G[current] + graph.move_cost(current, neighbour) if neighbour not in openVertices: openVertices.add(neighbour) elif candidateG >= G[neighbour]: continue cameFrom[neighbour] = current G[neighbour] = candidateG H = graph.heuristic(neighbour, end) F[neighbour] = G[neighbour] + H raise RuntimeError("A* failed to find a solution") if __name__=="__main__": graph = AStarGraph() result, cost = AStarSearch((0,0), (7,7), graph) print ("route", result) print ("cost", cost) plt.plot([v[0] for v in result], [v[1] for v in result]) for barrier in graph.barriers: plt.plot([v[0] for v in barrier], [v[1] for v in barrier]) plt.xlim(-1,8) plt.ylim(-1,8) plt.show()
Change the following C# code into Python without altering its purpose.
using System; using System.Collections.Generic; using System.Linq; class RangeExtraction { static void Main() { const string testString = "0, 1, 2, 4, 6, 7, 8, 11, 12, 14,15, 16, 17, 18, 19, 20, 21, 22, 23, 24,25, 27, 28, 29, 30, 31, 32, 33, 35, 36,37, 38, 39"; var result = String.Join(",", RangesToStrings(GetRanges(testString))); Console.Out.WriteLine(result); } public static IEnumerable<IEnumerable<int>> GetRanges(string testString) { var numbers = testString.Split(new[] { ',' }).Select(x => Convert.ToInt32(x)); var current = new List<int>(); foreach (var n in numbers) { if (current.Count == 0) { current.Add(n); } else { if (current.Max() + 1 == n) { current.Add(n); } else { yield return current; current = new List<int> { n }; } } } yield return current; } public static IEnumerable<string> RangesToStrings(IEnumerable<IEnumerable<int>> ranges) { foreach (var range in ranges) { if (range.Count() == 1) { yield return range.Single().ToString(); } else if (range.Count() == 2) { yield return range.Min() + "," + range.Max(); } else { yield return range.Min() + "-" + range.Max(); } } } }
def range_extract(lst): 'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints' lenlst = len(lst) i = 0 while i< lenlst: low = lst[i] while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1 hi = lst[i] if hi - low >= 2: yield (low, hi) elif hi - low == 1: yield (low,) yield (hi,) else: yield (low,) i += 1 def printr(ranges): print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r) for r in ranges ) ) if __name__ == '__main__': for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20], [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]: printr(range_extract(lst))
Port the provided C# code into Python while preserving the original functionality.
using System; namespace RosetaCode { class MainClass { public static void Main (string[] args) { int[,] list = new int[18,19]; string input = @"55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93"; var charArray = input.Split ('\n'); for (int i=0; i < charArray.Length; i++) { var numArr = charArray[i].Trim().Split(' '); for (int j = 0; j<numArr.Length; j++) { int number = Convert.ToInt32 (numArr[j]); list [i, j] = number; } } for (int i = 16; i >= 0; i--) { for (int j = 0; j < 18; j++) { list[i,j] = Math.Max(list[i, j] + list[i+1, j], list[i,j] + list[i+1, j+1]); } } Console.WriteLine (string.Format("Maximum total: {0}", list [0, 0])); } } }
fun maxpathsum(t): let a = val t for i in a.length-1..-1..1, c in linearindices a[r]: a[r, c] += max(a[r+1, c], a[r=1, c+1]) return a[1, 1] let test = [ [55], [94, 48], [95, 30, 96], [77, 71, 26, 67], [97, 13, 76, 38, 45], [07, 36, 79, 16, 37, 68], [48, 07, 09, 18, 70, 26, 06], [18, 72, 79, 46, 59, 79, 29, 90], [20, 76, 87, 11, 32, 07, 07, 49, 18], [27, 83, 58, 35, 71, 11, 25, 57, 29, 85], [14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55], [02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23], [92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42], [56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72], [44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36], [85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52], [06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15], [27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93] ] @print maxpathsum test
Generate an equivalent Python version of this C# code.
static void Main(string[] args) { Console.Write("\n\n\n\n Cursor is here --> "); System.Threading.Thread.Sleep(3000); Console.CursorLeft = Console.CursorLeft - 1; System.Threading.Thread.Sleep(3000); Console.CursorLeft = Console.CursorLeft + 1; System.Threading.Thread.Sleep(3000); Console.CursorTop = Console.CursorTop - 1; System.Threading.Thread.Sleep(3000); Console.CursorTop = Console.CursorTop + 1; System.Threading.Thread.Sleep(3000); Console.CursorLeft = 0; System.Threading.Thread.Sleep(3000); Console.CursorLeft = Console.BufferWidth - 1; System.Threading.Thread.Sleep(3000); Console.SetCursorPosition(0,0); System.Threading.Thread.Sleep(3000); Console.SetCursorPosition(Console.BufferWidth-1, Console.WindowHeight-1); System.Threading.Thread.Sleep(3000); }
import curses scr = curses.initscr() def move_left(): y,x = curses.getyx() curses.move(y,x-1) def move_right(): y,x = curses.getyx() curses.move(y,x+1) def move_up(): y,x = curses.getyx() curses.move(y-1,x) def move_down(): y,x = curses.getyx() curses.move(y+1,x) def move_line_home() y,x = curses.getyx() curses.move(y,0) def move_line_end() y,x = curses.getyx() maxy,maxx = scr.getmaxyx() curses.move(y,maxx) def move_page_home(): curses.move(0,0) def move_page_end(): y,x = scr.getmaxyx() curses.move(y,x)
Convert the following code from C# to Python, ensuring the logic remains intact.
static void Main(string[] args) { Console.Write("\n\n\n\n Cursor is here --> "); System.Threading.Thread.Sleep(3000); Console.CursorLeft = Console.CursorLeft - 1; System.Threading.Thread.Sleep(3000); Console.CursorLeft = Console.CursorLeft + 1; System.Threading.Thread.Sleep(3000); Console.CursorTop = Console.CursorTop - 1; System.Threading.Thread.Sleep(3000); Console.CursorTop = Console.CursorTop + 1; System.Threading.Thread.Sleep(3000); Console.CursorLeft = 0; System.Threading.Thread.Sleep(3000); Console.CursorLeft = Console.BufferWidth - 1; System.Threading.Thread.Sleep(3000); Console.SetCursorPosition(0,0); System.Threading.Thread.Sleep(3000); Console.SetCursorPosition(Console.BufferWidth-1, Console.WindowHeight-1); System.Threading.Thread.Sleep(3000); }
import curses scr = curses.initscr() def move_left(): y,x = curses.getyx() curses.move(y,x-1) def move_right(): y,x = curses.getyx() curses.move(y,x+1) def move_up(): y,x = curses.getyx() curses.move(y-1,x) def move_down(): y,x = curses.getyx() curses.move(y+1,x) def move_line_home() y,x = curses.getyx() curses.move(y,0) def move_line_end() y,x = curses.getyx() maxy,maxx = scr.getmaxyx() curses.move(y,maxx) def move_page_home(): curses.move(0,0) def move_page_end(): y,x = scr.getmaxyx() curses.move(y,x)
Port the following code from C# to Python with equivalent syntax and logic.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RosettaCodeTasks.FourBitAdder { public struct BitAdderOutput { public bool S { get; set; } public bool C { get; set; } public override string ToString ( ) { return "S" + ( S ? "1" : "0" ) + "C" + ( C ? "1" : "0" ); } } public struct Nibble { public bool _1 { get; set; } public bool _2 { get; set; } public bool _3 { get; set; } public bool _4 { get; set; } public override string ToString ( ) { return ( _4 ? "1" : "0" ) + ( _3 ? "1" : "0" ) + ( _2 ? "1" : "0" ) + ( _1 ? "1" : "0" ); } } public struct FourBitAdderOutput { public Nibble N { get; set; } public bool C { get; set; } public override string ToString ( ) { return N.ToString ( ) + "c" + ( C ? "1" : "0" ); } } public static class LogicGates { public static bool Not ( bool A ) { return !A; } public static bool And ( bool A, bool B ) { return A && B; } public static bool Or ( bool A, bool B ) { return A || B; } public static bool Xor ( bool A, bool B ) { return Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); } } public static class ConstructiveBlocks { public static BitAdderOutput HalfAdder ( bool A, bool B ) { return new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) }; } public static BitAdderOutput FullAdder ( bool A, bool B, bool CI ) { BitAdderOutput HA1 = HalfAdder ( CI, A ); BitAdderOutput HA2 = HalfAdder ( HA1.S, B ); return new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) }; } public static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI ) { BitAdderOutput FA1 = FullAdder ( A._1, B._1, CI ); BitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C ); BitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C ); BitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C ); return new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C }; } public static void Test ( ) { Console.WriteLine ( "Four Bit Adder" ); for ( int i = 0; i < 256; i++ ) { Nibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false }; Nibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false }; if ( (i & 1) == 1) { A._1 = true; } if ( ( i & 2 ) == 2 ) { A._2 = true; } if ( ( i & 4 ) == 4 ) { A._3 = true; } if ( ( i & 8 ) == 8 ) { A._4 = true; } if ( ( i & 16 ) == 16 ) { B._1 = true; } if ( ( i & 32 ) == 32) { B._2 = true; } if ( ( i & 64 ) == 64 ) { B._3 = true; } if ( ( i & 128 ) == 128 ) { B._4 = true; } Console.WriteLine ( "{0} + {1} = {2}", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) ); } Console.WriteLine ( ); } } }
from myhdl import * @block def NOTgate( a, q ): @always_comb def NOTgateLogic(): q.next = not a return NOTgateLogic @block def ANDgate( a, b, q ): @always_comb def ANDgateLogic(): q.next = a and b return ANDgateLogic @block def ORgate( a, b, q ): @always_comb def ORgateLogic(): q.next = a or b return ORgateLogic @block def XORgate( a, b, q ): nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)] inv0 = NOTgate( a, nota ) inv1 = NOTgate( b, notb ) and2a = ANDgate( a, notb, annotb ) and2b = ANDgate( b, nota, bnnota ) or2a = ORgate( annotb, bnnota, q ) return inv0, inv1, and2a, and2b, or2a @block def HalfAdder( in_a, in_b, summ, carry ): and2a = ANDgate(in_a, in_b, carry) xor2a = XORgate(in_a, in_b, summ) return and2a, xor2a @block def FullAdder( fa_c0, fa_a, fa_b, fa_s, fa_c1 ): ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)] HalfAdder01 = HalfAdder( fa_c0, fa_a, ha1_s, ha1_c1 ) HalfAdder02 = HalfAdder( ha1_s, fa_b, fa_s, ha2_c1 ) or2a = ORgate(ha1_c1, ha2_c1, fa_c1) return HalfAdder01, HalfAdder02, or2a @block def Adder4b( ina, inb, cOut, sum4): cl = [Signal(bool()) for i in range(0,4)] sl = [Signal(bool()) for i in range(4)] HalfAdder0 = HalfAdder( ina(0), inb(0), sl[0], cl[1] ) FullAdder1 = FullAdder( cl[1], ina(1), inb(1), sl[1], cl[2] ) FullAdder2 = FullAdder( cl[2], ina(2), inb(2), sl[2], cl[3] ) FullAdder3 = FullAdder( cl[3], ina(3), inb(3), sl[3], cOut ) sc = ConcatSignal(*reversed(sl)) @always_comb def list2intbv(): sum4.next = sc return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv t_co, t_s, t_a, t_b, dbug = [Signal(bool(0)) for i in range(5)] ina4, inb4, sum4 = [Signal(intbv(0)[4:]) for i in range(3)] from random import randrange @block def Test_Adder4b(): dut = Adder4b( ina4, inb4, t_co, sum4 ) @instance def check(): print( "\n b a | c1 s \n -------------------" ) for i in range(15): ina4.next, inb4.next = randrange(2**4), randrange(2**4) yield delay(5) print( " %2d %2d | %2d %2d " \ % (ina4,inb4, t_co,sum4) ) assert t_co * 16 + sum4 == ina4 + inb4 print() return dut, check def main(): simInst = Test_Adder4b() simInst.name = "mySimInst" simInst.config_sim(trace=True) simInst.run_sim(duration=None) inst = Adder4b( ina4, inb4, t_co, sum4 ) inst.convert(hdl='VHDL') inst.convert(hdl='Verilog') if __name__ == '__main__': main()
Generate a Python translation of this C# snippet without changing its computational steps.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RosettaCodeTasks.FourBitAdder { public struct BitAdderOutput { public bool S { get; set; } public bool C { get; set; } public override string ToString ( ) { return "S" + ( S ? "1" : "0" ) + "C" + ( C ? "1" : "0" ); } } public struct Nibble { public bool _1 { get; set; } public bool _2 { get; set; } public bool _3 { get; set; } public bool _4 { get; set; } public override string ToString ( ) { return ( _4 ? "1" : "0" ) + ( _3 ? "1" : "0" ) + ( _2 ? "1" : "0" ) + ( _1 ? "1" : "0" ); } } public struct FourBitAdderOutput { public Nibble N { get; set; } public bool C { get; set; } public override string ToString ( ) { return N.ToString ( ) + "c" + ( C ? "1" : "0" ); } } public static class LogicGates { public static bool Not ( bool A ) { return !A; } public static bool And ( bool A, bool B ) { return A && B; } public static bool Or ( bool A, bool B ) { return A || B; } public static bool Xor ( bool A, bool B ) { return Or ( And ( A, Not ( B ) ), ( And ( Not ( A ), B ) ) ); } } public static class ConstructiveBlocks { public static BitAdderOutput HalfAdder ( bool A, bool B ) { return new BitAdderOutput ( ) { S = LogicGates.Xor ( A, B ), C = LogicGates.And ( A, B ) }; } public static BitAdderOutput FullAdder ( bool A, bool B, bool CI ) { BitAdderOutput HA1 = HalfAdder ( CI, A ); BitAdderOutput HA2 = HalfAdder ( HA1.S, B ); return new BitAdderOutput ( ) { S = HA2.S, C = LogicGates.Or ( HA1.C, HA2.C ) }; } public static FourBitAdderOutput FourBitAdder ( Nibble A, Nibble B, bool CI ) { BitAdderOutput FA1 = FullAdder ( A._1, B._1, CI ); BitAdderOutput FA2 = FullAdder ( A._2, B._2, FA1.C ); BitAdderOutput FA3 = FullAdder ( A._3, B._3, FA2.C ); BitAdderOutput FA4 = FullAdder ( A._4, B._4, FA3.C ); return new FourBitAdderOutput ( ) { N = new Nibble ( ) { _1 = FA1.S, _2 = FA2.S, _3 = FA3.S, _4 = FA4.S }, C = FA4.C }; } public static void Test ( ) { Console.WriteLine ( "Four Bit Adder" ); for ( int i = 0; i < 256; i++ ) { Nibble A = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false }; Nibble B = new Nibble ( ) { _1 = false, _2 = false, _3 = false, _4 = false }; if ( (i & 1) == 1) { A._1 = true; } if ( ( i & 2 ) == 2 ) { A._2 = true; } if ( ( i & 4 ) == 4 ) { A._3 = true; } if ( ( i & 8 ) == 8 ) { A._4 = true; } if ( ( i & 16 ) == 16 ) { B._1 = true; } if ( ( i & 32 ) == 32) { B._2 = true; } if ( ( i & 64 ) == 64 ) { B._3 = true; } if ( ( i & 128 ) == 128 ) { B._4 = true; } Console.WriteLine ( "{0} + {1} = {2}", A.ToString ( ), B.ToString ( ), FourBitAdder( A, B, false ).ToString ( ) ); } Console.WriteLine ( ); } } }
from myhdl import * @block def NOTgate( a, q ): @always_comb def NOTgateLogic(): q.next = not a return NOTgateLogic @block def ANDgate( a, b, q ): @always_comb def ANDgateLogic(): q.next = a and b return ANDgateLogic @block def ORgate( a, b, q ): @always_comb def ORgateLogic(): q.next = a or b return ORgateLogic @block def XORgate( a, b, q ): nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)] inv0 = NOTgate( a, nota ) inv1 = NOTgate( b, notb ) and2a = ANDgate( a, notb, annotb ) and2b = ANDgate( b, nota, bnnota ) or2a = ORgate( annotb, bnnota, q ) return inv0, inv1, and2a, and2b, or2a @block def HalfAdder( in_a, in_b, summ, carry ): and2a = ANDgate(in_a, in_b, carry) xor2a = XORgate(in_a, in_b, summ) return and2a, xor2a @block def FullAdder( fa_c0, fa_a, fa_b, fa_s, fa_c1 ): ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)] HalfAdder01 = HalfAdder( fa_c0, fa_a, ha1_s, ha1_c1 ) HalfAdder02 = HalfAdder( ha1_s, fa_b, fa_s, ha2_c1 ) or2a = ORgate(ha1_c1, ha2_c1, fa_c1) return HalfAdder01, HalfAdder02, or2a @block def Adder4b( ina, inb, cOut, sum4): cl = [Signal(bool()) for i in range(0,4)] sl = [Signal(bool()) for i in range(4)] HalfAdder0 = HalfAdder( ina(0), inb(0), sl[0], cl[1] ) FullAdder1 = FullAdder( cl[1], ina(1), inb(1), sl[1], cl[2] ) FullAdder2 = FullAdder( cl[2], ina(2), inb(2), sl[2], cl[3] ) FullAdder3 = FullAdder( cl[3], ina(3), inb(3), sl[3], cOut ) sc = ConcatSignal(*reversed(sl)) @always_comb def list2intbv(): sum4.next = sc return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv t_co, t_s, t_a, t_b, dbug = [Signal(bool(0)) for i in range(5)] ina4, inb4, sum4 = [Signal(intbv(0)[4:]) for i in range(3)] from random import randrange @block def Test_Adder4b(): dut = Adder4b( ina4, inb4, t_co, sum4 ) @instance def check(): print( "\n b a | c1 s \n -------------------" ) for i in range(15): ina4.next, inb4.next = randrange(2**4), randrange(2**4) yield delay(5) print( " %2d %2d | %2d %2d " \ % (ina4,inb4, t_co,sum4) ) assert t_co * 16 + sum4 == ina4 + inb4 print() return dut, check def main(): simInst = Test_Adder4b() simInst.name = "mySimInst" simInst.config_sim(trace=True) simInst.run_sim(duration=None) inst = Adder4b( ina4, inb4, t_co, sum4 ) inst.convert(hdl='VHDL') inst.convert(hdl='Verilog') if __name__ == '__main__': main()
Convert the following code from C# to Python, ensuring the logic remains intact.
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace Unix_ls { public class UnixLS { public static void Main(string[] args) { UnixLS ls = new UnixLS(); ls.list(args.Length.Equals(0) ? "." : args[0]); } private void list(string folder) { foreach (FileSystemInfo fileSystemInfo in new DirectoryInfo(folder).EnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly)) { Console.WriteLine(fileSystemInfo.Name); } } } }
>>> import os >>> print('\n'.join(sorted(os.listdir('.')))) DLLs Doc LICENSE.txt Lib NEWS.txt README.txt Scripts Tools include libs python.exe pythonw.exe tcl >>>
Produce a functionally identical Python code for the snippet given in C#.
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace Unix_ls { public class UnixLS { public static void Main(string[] args) { UnixLS ls = new UnixLS(); ls.list(args.Length.Equals(0) ? "." : args[0]); } private void list(string folder) { foreach (FileSystemInfo fileSystemInfo in new DirectoryInfo(folder).EnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly)) { Console.WriteLine(fileSystemInfo.Name); } } } }
>>> import os >>> print('\n'.join(sorted(os.listdir('.')))) DLLs Doc LICENSE.txt Lib NEWS.txt README.txt Scripts Tools include libs python.exe pythonw.exe tcl >>>
Change the programming language of this snippet from C# to Python without modifying what it does.
using System; using System.Text; namespace Rosetta { class Program { static byte[] MyEncoder(int codepoint) => Encoding.UTF8.GetBytes(char.ConvertFromUtf32(codepoint)); static string MyDecoder(byte[] utf8bytes) => Encoding.UTF8.GetString(utf8bytes); static void Main(string[] args) { Console.OutputEncoding = Encoding.UTF8; foreach (int unicodePoint in new int[] { 0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E}) { byte[] asUtf8bytes = MyEncoder(unicodePoint); string theCharacter = MyDecoder(asUtf8bytes); Console.WriteLine("{0,8} {1,5} {2,-15}", unicodePoint.ToString("X4"), theCharacter, BitConverter.ToString(asUtf8bytes)); } } } }
from unicodedata import name def unicode_code(ch): return 'U+{:04x}'.format(ord(ch)) def utf8hex(ch): return " ".join([hex(c)[2:] for c in ch.encode('utf8')]).upper() if __name__ == "__main__": print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'UTF-8 encoding (hex)')) chars = ['A', 'ö', 'Ж', '€', '𝄞'] for char in chars: print('{:<11} {:<36} {:<15} {:<15}'.format(char, name(char), unicode_code(char), utf8hex(char)))
Transform the following C# implementation into Python, maintaining the same output and logic.
using System; namespace MagicSquareDoublyEven { class Program { static void Main(string[] args) { int n = 8; var result = MagicSquareDoublyEven(n); for (int i = 0; i < result.GetLength(0); i++) { for (int j = 0; j < result.GetLength(1); j++) Console.Write("{0,2} ", result[i, j]); Console.WriteLine(); } Console.WriteLine("\nMagic constant: {0} ", (n * n + 1) * n / 2); Console.ReadLine(); } private static int[,] MagicSquareDoublyEven(int n) { if (n < 4 || n % 4 != 0) throw new ArgumentException("base must be a positive " + "multiple of 4"); int bits = 0b1001_0110_0110_1001; int size = n * n; int mult = n / 4; int[,] result = new int[n, n]; for (int r = 0, i = 0; r < n; r++) { for (int c = 0; c < n; c++, i++) { int bitPos = c / mult + (r / mult) * 4; result[r, c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i; } } return result; } } }
def MagicSquareDoublyEven(order): sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ] n1 = order/4 for r in range(n1): r1 = sq[r][n1:-n1] r2 = sq[order -r - 1][n1:-n1] r1.reverse() r2.reverse() sq[r][n1:-n1] = r2 sq[order -r - 1][n1:-n1] = r1 for r in range(n1, order-n1): r1 = sq[r][:n1] r2 = sq[order -r - 1][order-n1:] r1.reverse() r2.reverse() sq[r][:n1] = r2 sq[order -r - 1][order-n1:] = r1 return sq def printsq(s): n = len(s) bl = len(str(n**2))+1 for i in range(n): print ''.join( [ ("%"+str(bl)+"s")%(str(x)) for x in s[i]] ) print "\nMagic constant = %d"%sum(s[0]) printsq(MagicSquareDoublyEven(8))
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 Same_Fringe { class Program { static void Main() { var rnd = new Random(110456); var randList = Enumerable.Range(0, 20).Select(i => rnd.Next(1000)).ToList(); var bt1 = new BinTree<int>(randList); Shuffle(randList, 428); var bt2 = new BinTree<int>(randList); Console.WriteLine(bt1.CompareTo(bt2) ? "True compare worked" : "True compare failed"); bt1.Insert(0); Console.WriteLine(bt1.CompareTo(bt2) ? "False compare failed" : "False compare worked"); } static void Shuffle<T>(List<T> values, int seed) { var rnd = new Random(seed); for (var i = 0; i < values.Count - 2; i++) { var iSwap = rnd.Next(values.Count - i) + i; var tmp = values[iSwap]; values[iSwap] = values[i]; values[i] = tmp; } } } class BinTree<T> where T:IComparable { private BinTree<T> _left; private BinTree<T> _right; private T _value; private BinTree<T> Left { get { return _left; } } private BinTree<T> Right { get { return _right; } } private T Value { get { return _value; } } public bool IsLeaf { get { return Left == null; } } private BinTree(BinTree<T> left, BinTree<T> right, T value) { _left = left; _right = right; _value = value; } public BinTree(T value) : this(null, null, value) { } public BinTree(IEnumerable<T> values) { _value = values.First(); foreach (var value in values.Skip(1)) { Insert(value); } } public void Insert(T value) { if (IsLeaf) { if (value.CompareTo(Value) < 0) { _left = new BinTree<T>(value); _right = new BinTree<T>(Value); } else { _left = new BinTree<T>(Value); _right = new BinTree<T>(value); _value = value; } } else { if (value.CompareTo(Value) < 0) { Left.Insert(value); } else { Right.Insert(value); } } } public IEnumerable<T> GetLeaves() { if (IsLeaf) { yield return Value; yield break; } foreach (var val in Left.GetLeaves()) { yield return val; } foreach (var val in Right.GetLeaves()) { yield return val; } } internal bool CompareTo(BinTree<T> other) { return other.GetLeaves().Zip(GetLeaves(), (t1, t2) => t1.CompareTo(t2) == 0).All(f => f); } } }
try: from itertools import zip_longest as izip_longest except: from itertools import izip_longest def fringe(tree): for node1 in tree: if isinstance(node1, tuple): for node2 in fringe(node1): yield node2 else: yield node1 def same_fringe(tree1, tree2): return all(node1 == node2 for node1, node2 in izip_longest(fringe(tree1), fringe(tree2))) if __name__ == '__main__': a = 1, 2, 3, 4, 5, 6, 7, 8 b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8)))) c = (((1, 2), 3), 4), 5, 6, 7, 8 x = 1, 2, 3, 4, 5, 6, 7, 8, 9 y = 0, 2, 3, 4, 5, 6, 7, 8 z = 1, 2, (4, 3), 5, 6, 7, 8 assert same_fringe(a, a) assert same_fringe(a, b) assert same_fringe(a, c) assert not same_fringe(a, x) assert not same_fringe(a, y) assert not same_fringe(a, z)
Ensure the translated Python code behaves exactly like the original C# snippet.
using System; using BI = System.Numerics.BigInteger; class Program { static void Main(string[] args) { for (BI x = 3; BI.Log10(x) < 22; x = (x - 2) * 10 + 3) Console.WriteLine("{1,43} {0,-20}", x, x * x); } }
[print("( " + "1"*i + "3 ) ^ 2 = " + str(int("1"*i + "3")**2)) for i in range(0,8)]
Translate this program into Python but keep the logic exactly as in C#.
using System; using BI = System.Numerics.BigInteger; class Program { static void Main(string[] args) { for (BI x = 3; BI.Log10(x) < 22; x = (x - 2) * 10 + 3) Console.WriteLine("{1,43} {0,-20}", x, x * x); } }
[print("( " + "1"*i + "3 ) ^ 2 = " + str(int("1"*i + "3")**2)) for i in range(0,8)]
Convert this C# block to Python, preserving its control flow and logic.
using System; using System.Collections.Generic; namespace PeacefulChessQueenArmies { using Position = Tuple<int, int>; enum Piece { Empty, Black, White } class Program { static bool IsAttacking(Position queen, Position pos) { return queen.Item1 == pos.Item1 || queen.Item2 == pos.Item2 || Math.Abs(queen.Item1 - pos.Item1) == Math.Abs(queen.Item2 - pos.Item2); } static bool Place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) { if (m == 0) { return true; } bool placingBlack = true; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { var pos = new Position(i, j); foreach (var queen in pBlackQueens) { if (queen.Equals(pos) || !placingBlack && IsAttacking(queen, pos)) { goto inner; } } foreach (var queen in pWhiteQueens) { if (queen.Equals(pos) || placingBlack && IsAttacking(queen, pos)) { goto inner; } } if (placingBlack) { pBlackQueens.Add(pos); placingBlack = false; } else { pWhiteQueens.Add(pos); if (Place(m - 1, n, pBlackQueens, pWhiteQueens)) { return true; } pBlackQueens.RemoveAt(pBlackQueens.Count - 1); pWhiteQueens.RemoveAt(pWhiteQueens.Count - 1); placingBlack = true; } inner: { } } } if (!placingBlack) { pBlackQueens.RemoveAt(pBlackQueens.Count - 1); } return false; } static void PrintBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) { var board = new Piece[n * n]; foreach (var queen in blackQueens) { board[queen.Item1 * n + queen.Item2] = Piece.Black; } foreach (var queen in whiteQueens) { board[queen.Item1 * n + queen.Item2] = Piece.White; } for (int i = 0; i < board.Length; i++) { if (i != 0 && i % n == 0) { Console.WriteLine(); } switch (board[i]) { case Piece.Black: Console.Write("B "); break; case Piece.White: Console.Write("W "); break; case Piece.Empty: int j = i / n; int k = i - j * n; if (j % 2 == k % 2) { Console.Write(" "); } else { Console.Write("# "); } break; } } Console.WriteLine("\n"); } static void Main() { var nms = new int[,] { {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3}, {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5}, {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6}, {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7}, }; for (int i = 0; i < nms.GetLength(0); i++) { Console.WriteLine("{0} black and {0} white queens on a {1} x {1} board:", nms[i, 1], nms[i, 0]); List<Position> blackQueens = new List<Position>(); List<Position> whiteQueens = new List<Position>(); if (Place(nms[i, 1], nms[i, 0], blackQueens, whiteQueens)) { PrintBoard(nms[i, 0], blackQueens, whiteQueens); } else { Console.WriteLine("No solution exists.\n"); } } } } }
from itertools import combinations, product, count from functools import lru_cache, reduce _bbullet, _wbullet = '\u2022\u25E6' _or = set.__or__ def place(m, n): "Place m black and white queens, peacefully, on an n-by-n board" board = set(product(range(n), repeat=2)) placements = {frozenset(c) for c in combinations(board, m)} for blacks in placements: black_attacks = reduce(_or, (queen_attacks_from(pos, n) for pos in blacks), set()) for whites in {frozenset(c) for c in combinations(board - black_attacks, m)}: if not black_attacks & whites: return blacks, whites return set(), set() @lru_cache(maxsize=None) def queen_attacks_from(pos, n): x0, y0 = pos a = set([pos]) a.update((x, y0) for x in range(n)) a.update((x0, y) for y in range(n)) for x1 in range(n): y1 = y0 -x0 +x1 if 0 <= y1 < n: a.add((x1, y1)) y1 = y0 +x0 -x1 if 0 <= y1 < n: a.add((x1, y1)) return a def pboard(black_white, n): "Print board" if black_white is None: blk, wht = set(), set() else: blk, wht = black_white print(f" f"on a {n}-by-{n} board:", end='') for x, y in product(range(n), repeat=2): if y == 0: print() xy = (x, y) ch = ('?' if xy in blk and xy in wht else 'B' if xy in blk else 'W' if xy in wht else _bbullet if (x + y)%2 else _wbullet) print('%s' % ch, end='') print() if __name__ == '__main__': n=2 for n in range(2, 7): print() for m in count(1): ans = place(m, n) if ans[0]: pboard(ans, n) else: print (f" break print('\n') m, n = 5, 7 ans = place(m, n) pboard(ans, n)
Keep all operations the same but rewrite the snippet in Python.
using System; using System.Collections.Generic; using System.Text; namespace MoveToFront { class Program { private static char[] symbolTable; private static void setSymbolTable() { symbolTable = "abcdefghijklmnopqrstuvwxyz".ToCharArray(); } private static void moveToFront(int charIndex) { char toFront = symbolTable[charIndex]; for (int j = charIndex; j > 0; j--) { symbolTable[j] = symbolTable[j - 1]; } symbolTable[0] = toFront; } public static int[] Encode(string input) { setSymbolTable(); var output = new List<int>(); foreach (char c in input) { for (int i = 0; i < 26; i++) { if (symbolTable[i] == c) { output.Add(i); moveToFront(i); break; } } } return output.ToArray(); } public static string Decode(int[] input) { setSymbolTable(); var output = new StringBuilder(input.Length); foreach (int n in input) { output.Append(symbolTable[n]); moveToFront(n); } return output.ToString(); } static void Main(string[] args) { string[] testInputs = new string[] { "broood", "bananaaa", "hiphophiphop" }; int[] encoding; foreach (string s in testInputs) { Console.WriteLine($"Encoding for '{s}':"); encoding = Encode(s); foreach (int i in encoding) { Console.Write($"{i} "); } Console.WriteLine($"\nDecoding for '{s}':"); Console.WriteLine($"{Decode(encoding)}\n"); } } } }
from __future__ import print_function from string import ascii_lowercase SYMBOLTABLE = list(ascii_lowercase) def move2front_encode(strng, symboltable): sequence, pad = [], symboltable[::] for char in strng: indx = pad.index(char) sequence.append(indx) pad = [pad.pop(indx)] + pad return sequence def move2front_decode(sequence, symboltable): chars, pad = [], symboltable[::] for indx in sequence: char = pad[indx] chars.append(char) pad = [pad.pop(indx)] + pad return ''.join(chars) if __name__ == '__main__': for s in ['broood', 'bananaaa', 'hiphophiphop']: encode = move2front_encode(s, SYMBOLTABLE) print('%14r encodes to %r' % (s, encode), end=', ') decode = move2front_decode(encode, SYMBOLTABLE) print('which decodes back to %r' % decode) assert s == decode, 'Whoops!'
Change the programming language of this snippet from C# to Python without modifying what it does.
using System; using static System.Console; class Program { static void Main(string[] args) { for (int i=0,j=-6,k=1,c=0,s=0;s<1600000;s+=c+=k+=j+=6) Write("{0,-7}{1}",s, (i+=i==3?-4:1)==0?"\n":" "); } }
def main(): fila = 0 lenCubos = 51 print("Suma de N cubos para n = [0..49]\n") for n in range(1, lenCubos): sumCubos = 0 for m in range(1, n): sumCubos = sumCubos + (m ** 3) fila += 1 print(f'{sumCubos:7} ', end='') if fila % 5 == 0: print(" ") print(f"\nEncontrados {fila} cubos.") if __name__ == '__main__': main()
Maintain the same structure and functionality when rewriting this code in Python.
using System.Diagnostics; namespace Execute { class Program { static void Main(string[] args) { Process.Start("cmd.exe", "/c dir"); } } }
import os exit_code = os.system('ls') output = os.popen('ls').read()
Write the same algorithm in Python as shown in this C# implementation.
using System; using System.Xml; using System.Xml.Schema; using System.IO; public class Test { public static void Main() { XmlSchemaSet sc = new XmlSchemaSet(); sc.Add(null, "http: XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.Schemas = sc; settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); XmlReader reader = XmlReader.Create("http: while (reader.Read()); Console.WriteLine("The XML file is valid for the given xsd file"); } private static void ValidationCallBack(object sender, ValidationEventArgs e) { Console.WriteLine("Validation Error: {0}", e.Message); } }
from __future__ import print_function import lxml from lxml import etree if __name__=="__main__": parser = etree.XMLParser(dtd_validation=True) schema_root = etree.XML() schema = etree.XMLSchema(schema_root) parser = etree.XMLParser(schema = schema) try: root = etree.fromstring("<a>5</a>", parser) print ("Finished validating good xml") except lxml.etree.XMLSyntaxError as err: print (err) parser = etree.XMLParser(schema = schema) try: root = etree.fromstring("<a>5<b>foobar</b></a>", parser) except lxml.etree.XMLSyntaxError as err: print (err)
Produce a language-to-language conversion: from C# to Python, same semantics.
using System; using System.Collections; using System.Collections.Generic; using System.Linq; public static class LIS { public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) => values == null ? throw new ArgumentNullException() : FindRecImpl(values, Sequence<T>.Empty, 0, comparer ?? Comparer<T>.Default).Reverse(); private static Sequence<T> FindRecImpl<T>(IList<T> values, Sequence<T> current, int index, IComparer<T> comparer) { if (index == values.Count) return current; if (current.Length > 0 && comparer.Compare(values[index], current.Value) <= 0) return FindRecImpl(values, current, index + 1, comparer); return Max( FindRecImpl(values, current, index + 1, comparer), FindRecImpl(values, current + values[index], index + 1, comparer) ); } private static Sequence<T> Max<T>(Sequence<T> a, Sequence<T> b) => a.Length < b.Length ? b : a; class Sequence<T> : IEnumerable<T> { public static readonly Sequence<T> Empty = new Sequence<T>(default(T), null); public Sequence(T value, Sequence<T> tail) { Value = value; Tail = tail; Length = tail == null ? 0 : tail.Length + 1; } public T Value { get; } public Sequence<T> Tail { get; } public int Length { get; } public static Sequence<T> operator +(Sequence<T> s, T value) => new Sequence<T>(value, s); public IEnumerator<T> GetEnumerator() { for (var s = this; s.Length > 0; s = s.Tail) yield return s.Value; } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }
def longest_increasing_subsequence(X): N = len(X) P = [0] * N M = [0] * (N+1) L = 0 for i in range(N): lo = 1 hi = L while lo <= hi: mid = (lo+hi)//2 if (X[M[mid]] < X[i]): lo = mid+1 else: hi = mid-1 newL = lo P[i] = M[newL-1] M[newL] = i if (newL > L): L = newL S = [] k = M[L] for i in range(L-1, -1, -1): S.append(X[k]) k = P[k] return S[::-1] if __name__ == '__main__': for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]: print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))
Change the programming language of this snippet from C# to Python without modifying what it does.
public protected internal protected internal private private protected
>>> x="From global scope" >>> def outerfunc(): x = "From scope at outerfunc" def scoped_local(): x = "scope local" return "scoped_local scope gives x = " + x print(scoped_local()) def scoped_nonlocal(): nonlocal x return "scoped_nonlocal scope gives x = " + x print(scoped_nonlocal()) def scoped_global(): global x return "scoped_global scope gives x = " + x print(scoped_global()) def scoped_notdefinedlocally(): return "scoped_notdefinedlocally scope gives x = " + x print(scoped_notdefinedlocally()) >>> outerfunc() scoped_local scope gives x = scope local scoped_nonlocal scope gives x = From scope at outerfunc scoped_global scope gives x = From global scope scoped_notdefinedlocally scope gives x = From global scope >>>
Convert this C# block to Python, preserving its control flow and logic.
using System; using System.Collections; using System.Collections.Generic; using System.Text; using static System.Linq.Enumerable; public static class BraceExpansion { enum TokenType { OpenBrace, CloseBrace, Separator, Text, Alternate, Concat } const char L = '{', R = '}', S = ','; public static void Main() { string[] input = { "It{{em,alic}iz,erat}e{d,}, please.", "~/{Downloads,Pictures}/*.{jpg,gif,png}", @"{,{,gotta have{ ,\, again\, }}more }cowbell!", @"{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}" }; foreach (string text in input) Expand(text); } static void Expand(string input) { Token token = Tokenize(input); foreach (string value in token) Console.WriteLine(value); Console.WriteLine(); } static Token Tokenize(string input) { var tokens = new List<Token>(); var buffer = new StringBuilder(); bool escaping = false; int level = 0; foreach (char c in input) { (escaping, level, tokens, buffer) = c switch { _ when escaping => (false, level, tokens, buffer.Append(c)), '\\' => (true, level, tokens, buffer.Append(c)), L => (escaping, level + 1, tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.OpenBrace)), buffer), S when level > 0 => (escaping, level, tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.Separator)), buffer), R when level > 0 => (escaping, level - 1, tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.CloseBrace)).Merge(), buffer), _ => (escaping, level, tokens, buffer.Append(c)) }; } if (buffer.Length > 0) tokens.Add(buffer.Flush()); for (int i = 0; i < tokens.Count; i++) { if (tokens[i].Type == TokenType.OpenBrace || tokens[i].Type == TokenType.Separator) { tokens[i] = tokens[i].Value; } } return new Token(tokens, TokenType.Concat); } static List<Token> Merge(this List<Token> list) { int separators = 0; int last = list.Count - 1; for (int i = list.Count - 3; i >= 0; i--) { if (list[i].Type == TokenType.Separator) { separators++; Concat(list, i + 1, last); list.RemoveAt(i); last = i; } else if (list[i].Type == TokenType.OpenBrace) { Concat(list, i + 1, last); if (separators > 0) { list[i] = new Token(list.Range((i+1)..^1), TokenType.Alternate); list.RemoveRange(i+1, list.Count - i - 1); } else { list[i] = L.ToString(); list[^1] = R.ToString(); Concat(list, i, list.Count); } break; } } return list; } static void Concat(List<Token> list, int s, int e) { for (int i = e - 2; i >= s; i--) { (Token a, Token b) = (list[i], list[i+1]); switch (a.Type, b.Type) { case (TokenType.Text, TokenType.Text): list[i] = a.Value + b.Value; list.RemoveAt(i+1); break; case (TokenType.Concat, TokenType.Concat): a.SubTokens.AddRange(b.SubTokens); list.RemoveAt(i+1); break; case (TokenType.Concat, TokenType.Text) when b.Value == "": list.RemoveAt(i+1); break; case (TokenType.Text, TokenType.Concat) when a.Value == "": list.RemoveAt(i); break; default: list[i] = new Token(new [] { a, b }, TokenType.Concat); list.RemoveAt(i+1); break; } } } private struct Token : IEnumerable<string> { private List<Token>? _subTokens; public string Value { get; } public TokenType Type { get; } public List<Token> SubTokens => _subTokens ??= new List<Token>(); public Token(string value, TokenType type) => (Value, Type, _subTokens) = (value, type, null); public Token(IEnumerable<Token> subTokens, TokenType type) => (Value, Type, _subTokens) = ("", type, subTokens.ToList()); public static implicit operator Token(string value) => new Token(value, TokenType.Text); public IEnumerator<string> GetEnumerator() => (Type switch { TokenType.Concat => SubTokens.Select(t => t.AsEnumerable()).CartesianProduct().Select(p => string.Join("", p)), TokenType.Alternate => from t in SubTokens from s in t select s, _ => Repeat(Value, 1) }).GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) { IEnumerable<IEnumerable<T>> emptyProduct = new[] { Empty<T>() }; return sequences.Aggregate( emptyProduct, (accumulator, sequence) => from acc in accumulator from item in sequence select acc.Concat(new [] { item })); } static List<Token> With(this List<Token> list, Token token) { list.Add(token); return list; } static IEnumerable<Token> Range(this List<Token> list, Range range) { int start = range.Start.GetOffset(list.Count); int end = range.End.GetOffset(list.Count); for (int i = start; i < end; i++) yield return list[i]; } static string Flush(this StringBuilder builder) { string result = builder.ToString(); builder.Clear(); return result; } }
def getitem(s, depth=0): out = [""] while s: c = s[0] if depth and (c == ',' or c == '}'): return out,s if c == '{': x = getgroup(s[1:], depth+1) if x: out,s = [a+b for a in out for b in x[0]], x[1] continue if c == '\\' and len(s) > 1: s, c = s[1:], c + s[1] out, s = [a+c for a in out], s[1:] return out,s def getgroup(s, depth): out, comma = [], False while s: g,s = getitem(s, depth) if not s: break out += g if s[0] == '}': if comma: return out, s[1:] return ['{' + a + '}' for a in out], s[1:] if s[0] == ',': comma,s = True, s[1:] return None for s in .split('\n'): print "\n\t".join([s] + getitem(s)[0]) + "\n"
Convert this C# snippet to Python and keep its semantics consistent.
using System; using System.ComponentModel; using System.Windows.Forms; class RosettaInteractionForm : Form { class NumberModel: INotifyPropertyChanged { Random rnd = new Random(); public event PropertyChangedEventHandler PropertyChanged = delegate {}; int _value; public int Value { get { return _value; } set { _value = value; PropertyChanged(this, new PropertyChangedEventArgs("Value")); } } public void ResetToRandom(){ Value = rnd.Next(5000); } } NumberModel model = new NumberModel{ Value = 0}; RosettaInteractionForm() { var tbNumber = new MaskedTextBox { Mask="0000", ResetOnSpace = false, Dock = DockStyle.Top }; tbNumber.DataBindings.Add("Text", model, "Value"); var btIncrement = new Button{Text = "Increment", Dock = DockStyle.Bottom}; btIncrement.Click += delegate { model.Value++; }; var btDecrement = new Button{Text = "Decrement", Dock = DockStyle.Bottom}; btDecrement.Click += delegate { model.Value--; }; var btRandom = new Button{ Text="Reset to Random", Dock = DockStyle.Bottom }; btRandom.Click += delegate { if (MessageBox.Show("Are you sure?", "Are you sure?", MessageBoxButtons.YesNo) == DialogResult.Yes) model.ResetToRandom(); }; Controls.Add(tbNumber); Controls.Add(btIncrement); Controls.Add(btDecrement); Controls.Add(btRandom); } static void Main() { Application.Run(new RosettaInteractionForm()); } }
import random, tkMessageBox from Tkinter import * window = Tk() window.geometry("300x50+100+100") options = { "padx":5, "pady":5} s=StringVar() s.set(1) def increase(): s.set(int(s.get())+1) def rand(): if tkMessageBox.askyesno("Confirmation", "Reset to random value ?"): s.set(random.randrange(0,5000)) def update(e): if not e.char.isdigit(): tkMessageBox.showerror('Error', 'Invalid input !') return "break" e = Entry(text=s) e.grid(column=0, row=0, **options) e.bind('<Key>', update) b1 = Button(text="Increase", command=increase, **options ) b1.grid(column=1, row=0, **options) b2 = Button(text="Random", command=rand, **options) b2.grid(column=2, row=0, **options) mainloop()
Generate an equivalent Python version of this C# code.
class Program { private static Random rnd = new Random(); public static int one_of_n(int n) { int currentChoice = 1; for (int i = 2; i <= n; i++) { double outerLimit = 1D / (double)i; if (rnd.NextDouble() < outerLimit) currentChoice = i; } return currentChoice; } static void Main(string[] args) { Dictionary<int, int> results = new Dictionary<int, int>(); for (int i = 1; i < 11; i++) results.Add(i, 0); for (int i = 0; i < 1000000; i++) { int result = one_of_n(10); results[result] = results[result] + 1; } for (int i = 1; i < 11; i++) Console.WriteLine("{0}\t{1}", i, results[i]); Console.ReadLine(); } }
from random import randrange try: range = xrange except: pass def one_of_n(lines): choice = None for i, line in enumerate(lines): if randrange(i+1) == 0: choice = line return choice def one_of_n_test(n=10, trials=1000000): bins = [0] * n if n: for i in range(trials): bins[one_of_n(range(n))] += 1 return bins print(one_of_n_test())
Change the programming language of this snippet from C# to Python without modifying what it does.
using System; namespace AdditionChains { class Program { static int[] Prepend(int n, int[] seq) { int[] result = new int[seq.Length + 1]; Array.Copy(seq, 0, result, 1, seq.Length); result[0] = n; return result; } static Tuple<int, int> CheckSeq(int pos, int[] seq, int n, int min_len) { if (pos > min_len || seq[0] > n) return new Tuple<int, int>(min_len, 0); if (seq[0] == n) return new Tuple<int, int>(pos, 1); if (pos < min_len) return TryPerm(0, pos, seq, n, min_len); return new Tuple<int, int>(min_len, 0); } static Tuple<int, int> TryPerm(int i, int pos, int[] seq, int n, int min_len) { if (i > pos) return new Tuple<int, int>(min_len, 0); Tuple<int, int> res1 = CheckSeq(pos + 1, Prepend(seq[0] + seq[i], seq), n, min_len); Tuple<int, int> res2 = TryPerm(i + 1, pos, seq, n, res1.Item1); if (res2.Item1 < res1.Item1) return res2; if (res2.Item1 == res1.Item1) return new Tuple<int, int>(res2.Item1, res1.Item2 + res2.Item2); throw new Exception("TryPerm exception"); } static Tuple<int, int> InitTryPerm(int x) { return TryPerm(0, 0, new int[] { 1 }, x, 12); } static void FindBrauer(int num) { Tuple<int, int> res = InitTryPerm(num); Console.WriteLine(); Console.WriteLine("N = {0}", num); Console.WriteLine("Minimum length of chains: L(n)= {0}", res.Item1); Console.WriteLine("Number of minimum length Brauer chains: {0}", res.Item2); } static void Main(string[] args) { int[] nums = new int[] { 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 }; Array.ForEach(nums, n => FindBrauer(n)); } } }
def prepend(n, seq): return [n] + seq def check_seq(pos, seq, n, min_len): if pos > min_len or seq[0] > n: return min_len, 0 if seq[0] == n: return pos, 1 if pos < min_len: return try_perm(0, pos, seq, n, min_len) return min_len, 0 def try_perm(i, pos, seq, n, min_len): if i > pos: return min_len, 0 res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len) res2 = try_perm(i + 1, pos, seq, n, res1[0]) if res2[0] < res1[0]: return res2 if res2[0] == res1[0]: return res2[0], res1[1] + res2[1] raise Exception("try_perm exception") def init_try_perm(x): return try_perm(0, 0, [1], x, 12) def find_brauer(num): res = init_try_perm(num) print print "N = ", num print "Minimum length of chains: L(n) = ", res[0] print "Number of minimum length Brauer chains: ", res[1] nums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379] for i in nums: find_brauer(i)
Port the following code from C# to Python with equivalent syntax and logic.
using System; namespace Repeat { class Program { static void Repeat(int count, Action<int> fn) { if (null == fn) { throw new ArgumentNullException("fn"); } for (int i = 0; i < count; i++) { fn.Invoke(i + 1); } } static void Main(string[] args) { Repeat(3, x => Console.WriteLine("Example {0}", x)); } } }
def repeat(f,n): for i in range(n): f(); def procedure(): print("Example"); repeat(procedure,3);
Ensure the translated Python code behaves exactly like the original C# snippet.
public class Program { static void Main() { System.Console.WriteLine(42.ModInverse(2017)); } } public static class IntExtensions { public static int ModInverse(this int a, int m) { if (m == 1) return 0; int m0 = m; (int x, int y) = (1, 0); while (a > 1) { int q = a / m; (a, m) = (m, a % m); (x, y) = (y, x - q * y); } return x < 0 ? x + m0 : x; } }
>>> def extended_gcd(aa, bb): lastremainder, remainder = abs(aa), abs(bb) x, lastx, y, lasty = 0, 1, 1, 0 while remainder: lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder) x, lastx = lastx - quotient*x, x y, lasty = lasty - quotient*y, y return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1) >>> def modinv(a, m): g, x, y = extended_gcd(a, m) if g != 1: raise ValueError return x % m >>> modinv(42, 2017) 1969 >>>
Maintain the same structure and functionality when rewriting this code in Python.
using System.Text; using System.Net.Sockets; using System.Net; namespace WebServer { class GoodByeWorld { static void Main(string[] args) { const string msg = "<html>\n<body>\nGoodbye, world!\n</body>\n</html>\n"; const int port = 8080; bool serverRunning = true; TcpListener tcpListener = new TcpListener(IPAddress.Any, port); tcpListener.Start(); while (serverRunning) { Socket socketConnection = tcpListener.AcceptSocket(); byte[] bMsg = Encoding.ASCII.GetBytes(msg.ToCharArray(), 0, (int)msg.Length); socketConnection.Send(bMsg); socketConnection.Disconnect(true); } } } }
from wsgiref.simple_server import make_server def app(environ, start_response): start_response('200 OK', [('Content-Type','text/html')]) yield b"<h1>Goodbye, World!</h1>" server = make_server('127.0.0.1', 8080, app) server.serve_forever()
Convert this C# snippet to Python and keep its semantics consistent.
using System; using System.Collections.Generic; using System.Linq; using static System.Console; class Program { static string fmt(int[] a) { var sb = new System.Text.StringBuilder(); for (int i = 0; i < a.Length; i++) sb.Append(string.Format("{0,5}{1}", a[i], i % 10 == 9 ? "\n" : " ")); return sb.ToString(); } static void Main(string[] args) { var sw = System.Diagnostics.Stopwatch.StartNew(); var pr = PG.Sundaram(15_500_000).Take(1_000_000).ToArray(); sw.Stop(); Write("The first 100 odd prime numbers:\n{0}\n", fmt(pr.Take(100).ToArray())); Write("The millionth odd prime number: {0}", pr.Last()); Write("\n{0} ms", sw.Elapsed.TotalMilliseconds); } } class PG { public static IEnumerable<int> Sundaram(int n) { int i = 1, k = (n + 1) >> 1, t = 1, v = 1, d = 1, s = 1; var comps = new bool[k + 1]; for (; t < k; t = ((++i + (s += d += 2)) << 1) - d - 2) while ((t += d + 2) < k) comps[t] = true; for (; v < k; v++) if (!comps[v]) yield return (v << 1) + 1; } }
from numpy import log def sieve_of_Sundaram(nth, print_all=True): assert nth > 0, "nth must be a positive integer" k = int((2.4 * nth * log(nth)) // 2) integers_list = [True] * k for i in range(1, k): j = i while i + j + 2 * i * j < k: integers_list[i + j + 2 * i * j] = False j += 1 pcount = 0 for i in range(1, k + 1): if integers_list[i]: pcount += 1 if print_all: print(f"{2 * i + 1:4}", end=' ') if pcount % 10 == 0: print() if pcount == nth: print(f"\nSundaram primes start with 3. The {nth}th Sundaram prime is {2 * i + 1}.\n") break sieve_of_Sundaram(100, True) sieve_of_Sundaram(1000000, False)
Produce a functionally identical Python code for the snippet given in C#.
using System; using System.Collections.Generic; using System.Linq; using static System.Console; class Program { static string fmt(int[] a) { var sb = new System.Text.StringBuilder(); for (int i = 0; i < a.Length; i++) sb.Append(string.Format("{0,5}{1}", a[i], i % 10 == 9 ? "\n" : " ")); return sb.ToString(); } static void Main(string[] args) { var sw = System.Diagnostics.Stopwatch.StartNew(); var pr = PG.Sundaram(15_500_000).Take(1_000_000).ToArray(); sw.Stop(); Write("The first 100 odd prime numbers:\n{0}\n", fmt(pr.Take(100).ToArray())); Write("The millionth odd prime number: {0}", pr.Last()); Write("\n{0} ms", sw.Elapsed.TotalMilliseconds); } } class PG { public static IEnumerable<int> Sundaram(int n) { int i = 1, k = (n + 1) >> 1, t = 1, v = 1, d = 1, s = 1; var comps = new bool[k + 1]; for (; t < k; t = ((++i + (s += d += 2)) << 1) - d - 2) while ((t += d + 2) < k) comps[t] = true; for (; v < k; v++) if (!comps[v]) yield return (v << 1) + 1; } }
from numpy import log def sieve_of_Sundaram(nth, print_all=True): assert nth > 0, "nth must be a positive integer" k = int((2.4 * nth * log(nth)) // 2) integers_list = [True] * k for i in range(1, k): j = i while i + j + 2 * i * j < k: integers_list[i + j + 2 * i * j] = False j += 1 pcount = 0 for i in range(1, k + 1): if integers_list[i]: pcount += 1 if print_all: print(f"{2 * i + 1:4}", end=' ') if pcount % 10 == 0: print() if pcount == nth: print(f"\nSundaram primes start with 3. The {nth}th Sundaram prime is {2 * i + 1}.\n") break sieve_of_Sundaram(100, True) sieve_of_Sundaram(1000000, False)
Change the programming language of this snippet from C# to Python without modifying what it does.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ChemicalCalculator { class Program { static Dictionary<string, double> atomicMass = new Dictionary<string, double>() { {"H", 1.008 }, {"He", 4.002602}, {"Li", 6.94}, {"Be", 9.0121831}, {"B", 10.81}, {"C", 12.011}, {"N", 14.007}, {"O", 15.999}, {"F", 18.998403163}, {"Ne", 20.1797}, {"Na", 22.98976928}, {"Mg", 24.305}, {"Al", 26.9815385}, {"Si", 28.085}, {"P", 30.973761998}, {"S", 32.06}, {"Cl", 35.45}, {"Ar", 39.948}, {"K", 39.0983}, {"Ca", 40.078}, {"Sc", 44.955908}, {"Ti", 47.867}, {"V", 50.9415}, {"Cr", 51.9961}, {"Mn", 54.938044}, {"Fe", 55.845}, {"Co", 58.933194}, {"Ni", 58.6934}, {"Cu", 63.546}, {"Zn", 65.38}, {"Ga", 69.723}, {"Ge", 72.630}, {"As", 74.921595}, {"Se", 78.971}, {"Br", 79.904}, {"Kr", 83.798}, {"Rb", 85.4678}, {"Sr", 87.62}, {"Y", 88.90584}, {"Zr", 91.224}, {"Nb", 92.90637}, {"Mo", 95.95}, {"Ru", 101.07}, {"Rh", 102.90550}, {"Pd", 106.42}, {"Ag", 107.8682}, {"Cd", 112.414}, {"In", 114.818}, {"Sn", 118.710}, {"Sb", 121.760}, {"Te", 127.60}, {"I", 126.90447}, {"Xe", 131.293}, {"Cs", 132.90545196}, {"Ba", 137.327}, {"La", 138.90547}, {"Ce", 140.116}, {"Pr", 140.90766}, {"Nd", 144.242}, {"Pm", 145}, {"Sm", 150.36}, {"Eu", 151.964}, {"Gd", 157.25}, {"Tb", 158.92535}, {"Dy", 162.500}, {"Ho", 164.93033}, {"Er", 167.259}, {"Tm", 168.93422}, {"Yb", 173.054}, {"Lu", 174.9668}, {"Hf", 178.49}, {"Ta", 180.94788}, {"W", 183.84}, {"Re", 186.207}, {"Os", 190.23}, {"Ir", 192.217}, {"Pt", 195.084}, {"Au", 196.966569}, {"Hg", 200.592}, {"Tl", 204.38}, {"Pb", 207.2}, {"Bi", 208.98040}, {"Po", 209}, {"At", 210}, {"Rn", 222}, {"Fr", 223}, {"Ra", 226}, {"Ac", 227}, {"Th", 232.0377}, {"Pa", 231.03588}, {"U", 238.02891}, {"Np", 237}, {"Pu", 244}, {"Am", 243}, {"Cm", 247}, {"Bk", 247}, {"Cf", 251}, {"Es", 252}, {"Fm", 257}, {"Uue", 315}, {"Ubn", 299}, }; static double Evaluate(string s) { s += "["; double sum = 0.0; string symbol = ""; string number = ""; for (int i = 0; i < s.Length; ++i) { var c = s[i]; if ('@' <= c && c <= '[') { int n = 1; if (number != "") { n = int.Parse(number); } if (symbol != "") { sum += atomicMass[symbol] * n; } if (c == '[') { break; } symbol = c.ToString(); number = ""; } else if ('a' <= c && c <= 'z') { symbol += c; } else if ('0' <= c && c <= '9') { number += c; } else { throw new Exception(string.Format("Unexpected symbol {0} in molecule", c)); } } return sum; } static string ReplaceFirst(string text, string search, string replace) { int pos = text.IndexOf(search); if (pos < 0) { return text; } return text.Substring(0, pos) + replace + text.Substring(pos + search.Length); } static string ReplaceParens(string s) { char letter = 's'; while (true) { var start = s.IndexOf('('); if (start == -1) { break; } for (int i = start + 1; i < s.Length; ++i) { if (s[i] == ')') { var expr = s.Substring(start + 1, i - start - 1); var symbol = string.Format("@{0}", letter); s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol); atomicMass[symbol] = Evaluate(expr); letter++; break; } if (s[i] == '(') { start = i; continue; } } } return s; } static void Main() { var molecules = new string[]{ "H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12", "COOH(C(CH3)2)3CH3", "C6H4O2(OH)4", "C27H46O", "Uue" }; foreach (var molecule in molecules) { var mass = Evaluate(ReplaceParens(molecule)); Console.WriteLine("{0,17} -> {1,7:0.000}", molecule, mass); } } } }
assert 1.008 == molar_mass('H') assert 2.016 == molar_mass('H2') assert 18.015 == molar_mass('H2O') assert 34.014 == molar_mass('H2O2') assert 34.014 == molar_mass('(HO)2') assert 142.036 == molar_mass('Na2SO4') assert 84.162 == molar_mass('C6H12') assert 186.295 == molar_mass('COOH(C(CH3)2)3CH3') assert 176.124 == molar_mass('C6H4O2(OH)4') assert 386.664 == molar_mass('C27H46O') assert 315 == molar_mass('Uue')
Translate this program into Python but keep the logic exactly as in C#.
var objDE = new System.DirectoryServices.DirectoryEntry("LDAP:
import ldap l = ldap.initialize("ldap://ldap.example.com") try: l.protocol_version = ldap.VERSION3 l.set_option(ldap.OPT_REFERRALS, 0) bind = l.simple_bind_s("me@example.com", "password") finally: l.unbind()
Can you help me rewrite this code in Python instead of C#, keeping it the same logically?
using System; namespace PythagoreanQuadruples { class Program { const int MAX = 2200; const int MAX2 = MAX * MAX * 2; static void Main(string[] args) { bool[] found = new bool[MAX + 1]; bool[] a2b2 = new bool[MAX2 + 1]; int s = 3; for(int a = 1; a <= MAX; a++) { int a2 = a * a; for (int b=a; b<=MAX; b++) { a2b2[a2 + b * b] = true; } } for (int c = 1; c <= MAX; c++) { int s1 = s; s += 2; int s2 = s; for (int d = c + 1; d <= MAX; d++) { if (a2b2[s1]) found[d] = true; s1 += s2; s2 += 2; } } Console.WriteLine("The values of d <= {0} which can't be represented:", MAX); for (int d = 1; d < MAX; d++) { if (!found[d]) Console.Write("{0} ", d); } Console.WriteLine(); } } }
def quad(top=2200): r = [False] * top ab = [False] * (top * 2)**2 for a in range(1, top): for b in range(a, top): ab[a * a + b * b] = True s = 3 for c in range(1, top): s1, s, s2 = s, s + 2, s + 2 for d in range(c + 1, top): if ab[s1]: r[d] = True s1 += s2 s2 += 2 return [i for i, val in enumerate(r) if not val and i] if __name__ == '__main__': n = 2200 print(f"Those values of d in 1..{n} that can't be represented: {quad(n)}")
Convert the following code from C# to Python, ensuring the logic remains intact.
using System; namespace PythagoreanQuadruples { class Program { const int MAX = 2200; const int MAX2 = MAX * MAX * 2; static void Main(string[] args) { bool[] found = new bool[MAX + 1]; bool[] a2b2 = new bool[MAX2 + 1]; int s = 3; for(int a = 1; a <= MAX; a++) { int a2 = a * a; for (int b=a; b<=MAX; b++) { a2b2[a2 + b * b] = true; } } for (int c = 1; c <= MAX; c++) { int s1 = s; s += 2; int s2 = s; for (int d = c + 1; d <= MAX; d++) { if (a2b2[s1]) found[d] = true; s1 += s2; s2 += 2; } } Console.WriteLine("The values of d <= {0} which can't be represented:", MAX); for (int d = 1; d < MAX; d++) { if (!found[d]) Console.Write("{0} ", d); } Console.WriteLine(); } } }
def quad(top=2200): r = [False] * top ab = [False] * (top * 2)**2 for a in range(1, top): for b in range(a, top): ab[a * a + b * b] = True s = 3 for c in range(1, top): s1, s, s2 = s, s + 2, s + 2 for d in range(c + 1, top): if ab[s1]: r[d] = True s1 += s2 s2 += 2 return [i for i, val in enumerate(r) if not val and i] if __name__ == '__main__': n = 2200 print(f"Those values of d in 1..{n} that can't be represented: {quad(n)}")
Convert this C# block to Python, preserving its control flow and logic.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using static System.Console; public enum Colour { Red, Green, White, Yellow, Blue } public enum Nationality { Englishman, Swede, Dane, Norwegian,German } public enum Pet { Dog, Birds, Cats, Horse, Zebra } public enum Drink { Coffee, Tea, Milk, Beer, Water } public enum Smoke { PallMall, Dunhill, Blend, BlueMaster, Prince} public static class ZebraPuzzle { private static (Colour[] colours, Drink[] drinks, Smoke[] smokes, Pet[] pets, Nationality[] nations) _solved; static ZebraPuzzle() { var solve = from colours in Permute<Colour>() where (colours,Colour.White).IsRightOf(colours, Colour.Green) from nations in Permute<Nationality>() where nations[0] == Nationality.Norwegian where (nations, Nationality.Englishman).IsSameIndex(colours, Colour.Red) where (nations,Nationality.Norwegian).IsNextTo(colours,Colour.Blue) from drinks in Permute<Drink>() where drinks[2] == Drink.Milk where (drinks, Drink.Coffee).IsSameIndex(colours, Colour.Green) where (drinks, Drink.Tea).IsSameIndex(nations, Nationality.Dane) from pets in Permute<Pet>() where (pets, Pet.Dog).IsSameIndex(nations, Nationality.Swede) from smokes in Permute<Smoke>() where (smokes, Smoke.PallMall).IsSameIndex(pets, Pet.Birds) where (smokes, Smoke.Dunhill).IsSameIndex(colours, Colour.Yellow) where (smokes, Smoke.Blend).IsNextTo(pets, Pet.Cats) where (smokes, Smoke.Dunhill).IsNextTo(pets, Pet.Horse) where (smokes, Smoke.BlueMaster).IsSameIndex(drinks, Drink.Beer) where (smokes, Smoke.Prince).IsSameIndex(nations, Nationality.German) where (drinks,Drink.Water).IsNextTo(smokes,Smoke.Blend) select (colours, drinks, smokes, pets, nations); _solved = solve.First(); } private static int IndexOf<T>(this T[] arr, T obj) => Array.IndexOf(arr, obj); private static bool IsRightOf<T, U>(this (T[] a, T v) right, U[] a, U v) => right.a.IndexOf(right.v) == a.IndexOf(v) + 1; private static bool IsSameIndex<T, U>(this (T[] a, T v)x, U[] a, U v) => x.a.IndexOf(x.v) == a.IndexOf(v); private static bool IsNextTo<T, U>(this (T[] a, T v)x, U[] a, U v) => (x.a,x.v).IsRightOf(a, v) || (a,v).IsRightOf(x.a,x.v); public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> values) { if (values.Count() == 1) return values.ToSingleton(); return values.SelectMany(v => Permutations(values.Except(v.ToSingleton())),(v, p) => p.Prepend(v)); } public static IEnumerable<T[]> Permute<T>() => ToEnumerable<T>().Permutations().Select(p=>p.ToArray()); private static IEnumerable<T> ToSingleton<T>(this T item){ yield return item; } private static IEnumerable<T> ToEnumerable<T>() => Enum.GetValues(typeof(T)).Cast<T>(); public static new String ToString() { var sb = new StringBuilder(); sb.AppendLine("House Colour Drink Nationality Smokes Pet"); sb.AppendLine("───── ────── ──────── ─────────── ────────── ─────"); var (colours, drinks, smokes, pets, nations) = _solved; for (var i = 0; i < 5; i++) sb.AppendLine($"{i+1,5} {colours[i],-6} {drinks[i],-8} {nations[i],-11} {smokes[i],-10} {pets[i],-10}"); return sb.ToString(); } public static void Main(string[] arguments) { var owner = _solved.nations[_solved.pets.IndexOf(Pet.Zebra)]; WriteLine($"The zebra owner is {owner}"); Write(ToString()); Read(); } }
from logpy import * from logpy.core import lall import time def lefto(q, p, list): return membero((q,p), zip(list, list[1:])) def nexto(q, p, list): return conde([lefto(q, p, list)], [lefto(p, q, list)]) houses = var() zebraRules = lall( (eq, (var(), var(), var(), var(), var()), houses), (membero, ('Englishman', var(), var(), var(), 'red'), houses), (membero, ('Swede', var(), var(), 'dog', var()), houses), (membero, ('Dane', var(), 'tea', var(), var()), houses), (lefto, (var(), var(), var(), var(), 'green'), (var(), var(), var(), var(), 'white'), houses), (membero, (var(), var(), 'coffee', var(), 'green'), houses), (membero, (var(), 'Pall Mall', var(), 'birds', var()), houses), (membero, (var(), 'Dunhill', var(), var(), 'yellow'), houses), (eq, (var(), var(), (var(), var(), 'milk', var(), var()), var(), var()), houses), (eq, (('Norwegian', var(), var(), var(), var()), var(), var(), var(), var()), houses), (nexto, (var(), 'Blend', var(), var(), var()), (var(), var(), var(), 'cats', var()), houses), (nexto, (var(), 'Dunhill', var(), var(), var()), (var(), var(), var(), 'horse', var()), houses), (membero, (var(), 'Blue Master', 'beer', var(), var()), houses), (membero, ('German', 'Prince', var(), var(), var()), houses), (nexto, ('Norwegian', var(), var(), var(), var()), (var(), var(), var(), var(), 'blue'), houses), (nexto, (var(), 'Blend', var(), var(), var()), (var(), var(), 'water', var(), var()), houses), (membero, (var(), var(), var(), 'zebra', var()), houses) ) t0 = time.time() solutions = run(0, houses, zebraRules) t1 = time.time() dur = t1-t0 count = len(solutions) zebraOwner = [house for house in solutions[0] if 'zebra' in house][0][0] print "%i solutions in %.2f seconds" % (count, dur) print "The %s is the owner of the zebra" % zebraOwner print "Here are all the houses:" for line in solutions[0]: print str(line)
Please provide an equivalent version of this C# code in Python.
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Net; class Program { static List<string> GetTitlesFromCategory(string category) { string searchQueryFormat = "http: List<string> results = new List<string>(); string cmcontinue = string.Empty; do { string cmContinueKeyValue; if (cmcontinue.Length > 0) cmContinueKeyValue = String.Format("&cmcontinue={0}", cmcontinue); else cmContinueKeyValue = String.Empty; string query = String.Format(searchQueryFormat, category, cmContinueKeyValue); string content = new WebClient().DownloadString(query); results.AddRange(new Regex("\"title\":\"(.+?)\"").Matches(content).Cast<Match>().Select(x => x.Groups[1].Value)); cmcontinue = Regex.Match(content, @"{""cmcontinue"":""([^""]+)""}", RegexOptions.IgnoreCase).Groups["1"].Value; } while (cmcontinue.Length > 0); return results; } static string[] GetUnimplementedTasksFromLanguage(string language) { List<string> alltasks = GetTitlesFromCategory("Programming_Tasks"); List<string> lang = GetTitlesFromCategory(language); return alltasks.Where(x => !lang.Contains(x)).ToArray(); } static void Main(string[] args) { string[] unimpl = GetUnimplementedTasksFromLanguage(args[0]); foreach (string i in unimpl) Console.WriteLine(i); } }
from operator import attrgetter from typing import Iterator import mwclient URL = 'www.rosettacode.org' API_PATH = '/mw/' def unimplemented_tasks(language: str, *, url: str, api_path: str) -> Iterator[str]: site = mwclient.Site(url, path=api_path) all_tasks = site.categories['Programming Tasks'] language_tasks = site.categories[language] name = attrgetter('name') all_tasks_names = map(name, all_tasks) language_tasks_names = set(map(name, language_tasks)) for task in all_tasks_names: if task not in language_tasks_names: yield task if __name__ == '__main__': tasks = unimplemented_tasks('Python', url=URL, api_path=API_PATH) print(*tasks, sep='\n')
Write the same code in Python as shown below in C#.
using System; using System.Linq; class Program { static void Main(string[] args) { double x, xi, y, yi, z, zi; x = 2.0; xi = 0.5; y = 4.0; yi = 0.25; z = x + y; zi = 1.0 / (x + y); var numlist = new[] { x, y, z }; var numlisti = new[] { xi, yi, zi }; var multiplied = numlist.Zip(numlisti, (n1, n2) => { Func<double, double> multiplier = m => n1 * n2 * m; return multiplier; }); foreach (var multiplier in multiplied) Console.WriteLine(multiplier(0.5)); } }
IDLE 2.6.1 >>> >>> x,xi, y,yi = 2.0,0.5, 4.0,0.25 >>> >>> z = x + y >>> zi = 1.0 / (x + y) >>> >>> multiplier = lambda n1, n2: (lambda m: n1 * n2 * m) >>> >>> numlist = [x, y, z] >>> numlisti = [xi, yi, zi] >>> >>> [multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)] [0.5, 0.5, 0.5] >>>
Generate a Python translation of this C# snippet without changing its computational steps.
using System; using System.Linq; class Program { static void Main(string[] args) { double x, xi, y, yi, z, zi; x = 2.0; xi = 0.5; y = 4.0; yi = 0.25; z = x + y; zi = 1.0 / (x + y); var numlist = new[] { x, y, z }; var numlisti = new[] { xi, yi, zi }; var multiplied = numlist.Zip(numlisti, (n1, n2) => { Func<double, double> multiplier = m => n1 * n2 * m; return multiplier; }); foreach (var multiplier in multiplied) Console.WriteLine(multiplier(0.5)); } }
IDLE 2.6.1 >>> >>> x,xi, y,yi = 2.0,0.5, 4.0,0.25 >>> >>> z = x + y >>> zi = 1.0 / (x + y) >>> >>> multiplier = lambda n1, n2: (lambda m: n1 * n2 * m) >>> >>> numlist = [x, y, z] >>> numlisti = [xi, yi, zi] >>> >>> [multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)] [0.5, 0.5, 0.5] >>>
Change the programming language of this snippet from C# to Python without modifying what it does.
using System.Collections.Generic; using System.Linq; using System.Text; namespace SokobanSolver { public class SokobanSolver { private class Board { public string Cur { get; internal set; } public string Sol { get; internal set; } public int X { get; internal set; } public int Y { get; internal set; } public Board(string cur, string sol, int x, int y) { Cur = cur; Sol = sol; X = x; Y = y; } } private string destBoard, currBoard; private int playerX, playerY, nCols; SokobanSolver(string[] board) { nCols = board[0].Length; StringBuilder destBuf = new StringBuilder(); StringBuilder currBuf = new StringBuilder(); for (int r = 0; r < board.Length; r++) { for (int c = 0; c < nCols; c++) { char ch = board[r][c]; destBuf.Append(ch != '$' && ch != '@' ? ch : ' '); currBuf.Append(ch != '.' ? ch : ' '); if (ch == '@') { this.playerX = c; this.playerY = r; } } } destBoard = destBuf.ToString(); currBoard = currBuf.ToString(); } private string Move(int x, int y, int dx, int dy, string trialBoard) { int newPlayerPos = (y + dy) * nCols + x + dx; if (trialBoard[newPlayerPos] != ' ') return null; char[] trial = trialBoard.ToCharArray(); trial[y * nCols + x] = ' '; trial[newPlayerPos] = '@'; return new string(trial); } private string Push(int x, int y, int dx, int dy, string trialBoard) { int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx; if (trialBoard[newBoxPos] != ' ') return null; char[] trial = trialBoard.ToCharArray(); trial[y * nCols + x] = ' '; trial[(y + dy) * nCols + x + dx] = '@'; trial[newBoxPos] = '$'; return new string(trial); } private bool IsSolved(string trialBoard) { for (int i = 0; i < trialBoard.Length; i++) if ((destBoard[i] == '.') != (trialBoard[i] == '$')) return false; return true; } private string Solve() { char[,] dirLabels = { { 'u', 'U' }, { 'r', 'R' }, { 'd', 'D' }, { 'l', 'L' } }; int[,] dirs = { { 0, -1 }, { 1, 0 }, { 0, 1 }, { -1, 0 } }; ISet<string> history = new HashSet<string>(); LinkedList<Board> open = new LinkedList<Board>(); history.Add(currBoard); open.AddLast(new Board(currBoard, string.Empty, playerX, playerY)); while (!open.Count.Equals(0)) { Board item = open.First(); open.RemoveFirst(); string cur = item.Cur; string sol = item.Sol; int x = item.X; int y = item.Y; for (int i = 0; i < dirs.GetLength(0); i++) { string trial = cur; int dx = dirs[i, 0]; int dy = dirs[i, 1]; if (trial[(y + dy) * nCols + x + dx] == '$') { if ((trial = Push(x, y, dx, dy, trial)) != null) { if (!history.Contains(trial)) { string newSol = sol + dirLabels[i, 1]; if (IsSolved(trial)) return newSol; open.AddLast(new Board(trial, newSol, x + dx, y + dy)); history.Add(trial); } } } else if ((trial = Move(x, y, dx, dy, trial)) != null) { if (!history.Contains(trial)) { string newSol = sol + dirLabels[i, 0]; open.AddLast(new Board(trial, newSol, x + dx, y + dy)); history.Add(trial); } } } } return "No solution"; } public static void Main(string[] a) { string level = "#######," + "# #," + "# #," + "#. # #," + "#. $$ #," + "#.$$ #," + "#.# @#," + "#######"; System.Console.WriteLine("Level:\n"); foreach (string line in level.Split(',')) { System.Console.WriteLine(line); } System.Console.WriteLine("\nSolution:\n"); System.Console.WriteLine(new SokobanSolver(level.Split(',')).Solve()); } } }
from array import array from collections import deque import psyco data = [] nrows = 0 px = py = 0 sdata = "" ddata = "" def init(board): global data, nrows, sdata, ddata, px, py data = filter(None, board.splitlines()) nrows = max(len(r) for r in data) maps = {' ':' ', '.': '.', '@':' ', ' mapd = {' ':' ', '.': ' ', '@':'@', ' for r, row in enumerate(data): for c, ch in enumerate(row): sdata += maps[ch] ddata += mapd[ch] if ch == '@': px = c py = r def push(x, y, dx, dy, data): if sdata[(y+2*dy) * nrows + x+2*dx] == ' data[(y+2*dy) * nrows + x+2*dx] != ' ': return None data2 = array("c", data) data2[y * nrows + x] = ' ' data2[(y+dy) * nrows + x+dx] = '@' data2[(y+2*dy) * nrows + x+2*dx] = '*' return data2.tostring() def is_solved(data): for i in xrange(len(data)): if (sdata[i] == '.') != (data[i] == '*'): return False return True def solve(): open = deque([(ddata, "", px, py)]) visited = set([ddata]) dirs = ((0, -1, 'u', 'U'), ( 1, 0, 'r', 'R'), (0, 1, 'd', 'D'), (-1, 0, 'l', 'L')) lnrows = nrows while open: cur, csol, x, y = open.popleft() for di in dirs: temp = cur dx, dy = di[0], di[1] if temp[(y+dy) * lnrows + x+dx] == '*': temp = push(x, y, dx, dy, temp) if temp and temp not in visited: if is_solved(temp): return csol + di[3] open.append((temp, csol + di[3], x+dx, y+dy)) visited.add(temp) else: if sdata[(y+dy) * lnrows + x+dx] == ' temp[(y+dy) * lnrows + x+dx] != ' ': continue data2 = array("c", temp) data2[y * lnrows + x] = ' ' data2[(y+dy) * lnrows + x+dx] = '@' temp = data2.tostring() if temp not in visited: if is_solved(temp): return csol + di[2] open.append((temp, csol + di[2], x+dx, y+dy)) visited.add(temp) return "No solution" level = """\ psyco.full() init(level) print level, "\n\n", solve()
Can you help me rewrite this code in Python instead of C#, keeping it the same logically?
using System; using BI = System.Numerics.BigInteger; using static System.Console; class Program { static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) { q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }   static string dump(int digs, bool show = false) { int gb = 1, dg = ++digs + gb, z; BI t1 = 1, t2 = 9, t3 = 1, te, su = 0, t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1; for (BI n = 0; n < dg; n++) { if (n > 0) t3 *= BI.Pow(n, 6); te = t1 * t2 / t3; if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z); else te /= BI.Pow (10, -z); if (show && n < 10) WriteLine("{0,2} {1,62}", n, te * 32 / 3 / t); su += te; if (te < 10) { if (show) WriteLine("\n{0} iterations required for {1} digits " + "after the decimal point.\n", n, --digs); break; } for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j; t2 += 126 + 532 * (d += 2); } string s = string.Format("{0}", isqrt(BI.Pow(10, dg * 2 + 3) / su / 32 * 3 * BI.Pow((BI)10, dg + 5))); return s[0] + "." + s.Substring(1, digs); } static void Main(string[] args) { WriteLine(dump(70, true)); } }
import mpmath as mp with mp.workdps(72): def integer_term(n): p = 532 * n * n + 126 * n + 9 return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6) def exponent_term(n): return -(mp.mpf("6.0") * n + 3) def nthterm(n): return integer_term(n) * mp.mpf("10.0")**exponent_term(n) for n in range(10): print("Term ", n, ' ', int(integer_term(n))) def almkvist_guillera(floatprecision): summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0') for n in range(100000000): nextadd = summed + nthterm(n) if abs(nextadd - summed) < 10.0**(-floatprecision): break summed = nextadd return nextadd print('\nπ to 70 digits is ', end='') mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71) print('mpmath π is ', end='') mp.nprint(mp.pi, 71)
Write the same algorithm in Python as shown in this C# implementation.
using System; using BI = System.Numerics.BigInteger; using static System.Console; class Program { static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) { q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }   static string dump(int digs, bool show = false) { int gb = 1, dg = ++digs + gb, z; BI t1 = 1, t2 = 9, t3 = 1, te, su = 0, t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1; for (BI n = 0; n < dg; n++) { if (n > 0) t3 *= BI.Pow(n, 6); te = t1 * t2 / t3; if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z); else te /= BI.Pow (10, -z); if (show && n < 10) WriteLine("{0,2} {1,62}", n, te * 32 / 3 / t); su += te; if (te < 10) { if (show) WriteLine("\n{0} iterations required for {1} digits " + "after the decimal point.\n", n, --digs); break; } for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j; t2 += 126 + 532 * (d += 2); } string s = string.Format("{0}", isqrt(BI.Pow(10, dg * 2 + 3) / su / 32 * 3 * BI.Pow((BI)10, dg + 5))); return s[0] + "." + s.Substring(1, digs); } static void Main(string[] args) { WriteLine(dump(70, true)); } }
import mpmath as mp with mp.workdps(72): def integer_term(n): p = 532 * n * n + 126 * n + 9 return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6) def exponent_term(n): return -(mp.mpf("6.0") * n + 3) def nthterm(n): return integer_term(n) * mp.mpf("10.0")**exponent_term(n) for n in range(10): print("Term ", n, ' ', int(integer_term(n))) def almkvist_guillera(floatprecision): summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0') for n in range(100000000): nextadd = summed + nthterm(n) if abs(nextadd - summed) < 10.0**(-floatprecision): break summed = nextadd return nextadd print('\nπ to 70 digits is ', end='') mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71) print('mpmath π is ', end='') mp.nprint(mp.pi, 71)
Maintain the same structure and functionality when rewriting this code in Python.
using System.Collections.Generic; using System.Linq; using static System.Console; class Program { static bool soas(int n, IEnumerable<int> f) { if (n <= 0) return false; if (f.Contains(n)) return true; switch(n.CompareTo(f.Sum())) { case 1: return false; case 0: return true; case -1: var rf = f.Reverse().ToList(); var d = n - rf[0]; rf.RemoveAt(0); return soas(d, rf) || soas(n, rf); } return true; } static bool ip(int n) { var f = Enumerable.Range(1, n >> 1).Where(d => n % d == 0).ToList(); return Enumerable.Range(1, n - 1).ToList().TrueForAll(i => soas(i, f)); } static void Main() { int c = 0, m = 333; for (int i = 1; i <= m; i += i == 1 ? 1 : 2) if (ip(i) || i == 1) Write("{0,3} {1}", i, ++c % 10 == 0 ? "\n" : ""); Write("\nFound {0} practical numbers between 1 and {1} inclusive.\n", c, m); do Write("\n{0,5} is a{1}practical number.", m = m < 500 ? m << 1 : m * 10 + 6, ip(m) ? " " : "n im"); while (m < 1e4); } }
from itertools import chain, cycle, accumulate, combinations from typing import List, Tuple def factors5(n: int) -> List[int]: def prime_powers(n): for c in accumulate(chain([2, 1, 2], cycle([2,4]))): if c*c > n: break if n%c: continue d,p = (), c while not n%c: n,p,d = n//c, p*c, d + (p,) yield(d) if n > 1: yield((n,)) r = [1] for e in prime_powers(n): r += [a*b for a in r for b in e] return r[:-1] def powerset(s: List[int]) -> List[Tuple[int, ...]]: return chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1)) def is_practical(x: int) -> bool: if x == 1: return True if x %2: return False f = factors5(x) ps = powerset(f) found = {y for y in {sum(i) for i in ps} if 1 <= y < x} return len(found) == x - 1 if __name__ == '__main__': n = 333 p = [x for x in range(1, n + 1) if is_practical(x)] print(f"There are {len(p)} Practical numbers from 1 to {n}:") print(' ', str(p[:10])[1:-1], '...', str(p[-10:])[1:-1]) x = 666 print(f"\nSTRETCH GOAL: {x} is {'not ' if not is_practical(x) else ''}Practical.")
Translate the given C# code snippet into Python without altering its behavior.
using System.Linq; using System.Collections.Generic; using TG = System.Tuple<int, int>; using static System.Console; class Program { static void Main(string[] args) { const int mil = (int)1e6; foreach (var amt in new int[] { 1, 2, 6, 12, 18 }) { int lmt = mil * amt, lg = 0, ng, d, ld = 0; var desc = new string[] { "A", "", "De" }; int[] mx = new int[] { 0, 0, 0 }, bi = new int[] { 0, 0, 0 }, c = new int[] { 2, 2, 2 }; WriteLine("For primes up to {0:n0}:", lmt); var pr = PG.Primes(lmt).ToArray(); for (int i = 0; i < pr.Length; i++) { ng = pr[i].Item2; d = ng.CompareTo(lg) + 1; if (ld == d) c[2 - d]++; else { if (c[d] > mx[d]) { mx[d] = c[d]; bi[d] = i - mx[d] - 1; } c[d] = 2; } ld = d; lg = ng; } for (int r = 0; r <= 2; r += 2) { Write("{0}scending, found run of {1} consecutive primes:\n {2} ", desc[r], mx[r] + 1, pr[bi[r]++].Item1); foreach (var itm in pr.Skip(bi[r]).Take(mx[r])) Write("({0}) {1} ", itm.Item2, itm.Item1); WriteLine(r == 0 ? "" : "\n"); } } } } class PG { public static IEnumerable<TG> Primes(int lim) { bool[] flags = new bool[lim + 1]; int j = 3, lj = 2; for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8) if (!flags[j]) { yield return new TG(j, j - lj); lj = 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 new TG(j, j - lj); lj = j; } } }
from sympy import sieve primelist = list(sieve.primerange(2,1000000)) listlen = len(primelist) pindex = 1 old_diff = -1 curr_list=[primelist[0]] longest_list=[] while pindex < listlen: diff = primelist[pindex] - primelist[pindex-1] if diff > old_diff: curr_list.append(primelist[pindex]) if len(curr_list) > len(longest_list): longest_list = curr_list else: curr_list = [primelist[pindex-1],primelist[pindex]] old_diff = diff pindex += 1 print(longest_list) pindex = 1 old_diff = -1 curr_list=[primelist[0]] longest_list=[] while pindex < listlen: diff = primelist[pindex] - primelist[pindex-1] if diff < old_diff: curr_list.append(primelist[pindex]) if len(curr_list) > len(longest_list): longest_list = curr_list else: curr_list = [primelist[pindex-1],primelist[pindex]] old_diff = diff pindex += 1 print(longest_list)
Transform the following C# implementation into Python, maintaining the same output and logic.
double d = 1; d = 1d; d = 1D; d = 1.2; d = 1.2d; d = .2; d = 12e-12; d = 12E-12; d = 1_234e-1_2; float f = 1; f = 1f; f = 1F; f = 1.2f; f = .2f; f = 12e-12f; f = 12E-12f; f = 1_234e-1_2f; decimal m = 1; m = 1m; m = 1m; m = 1.2m; m = .2m; m = 12e-12m; m = 12E-12m; m = 1_234e-1_2m;
2.3 .3 .3e4 .3e+34 .3e-34 2.e34
Port the following code from C# to Python with equivalent syntax and logic.
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)[] numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)}; private (int dx, int dy)[] moves; public static void Main() { var numbrixSolver = new Solver(numbrixMoves); Print(numbrixSolver.Solve(false, new [,] { { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 46, 45, 0, 55, 74, 0, 0 }, { 0, 38, 0, 0, 43, 0, 0, 78, 0 }, { 0, 35, 0, 0, 0, 0, 0, 71, 0 }, { 0, 0, 33, 0, 0, 0, 59, 0, 0 }, { 0, 17, 0, 0, 0, 0, 0, 67, 0 }, { 0, 18, 0, 0, 11, 0, 0, 64, 0 }, { 0, 0, 24, 21, 0, 1, 2, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, })); Print(numbrixSolver.Solve(false, new [,] { { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 11, 12, 15, 18, 21, 62, 61, 0 }, { 0, 6, 0, 0, 0, 0, 0, 60, 0 }, { 0, 33, 0, 0, 0, 0, 0, 57, 0 }, { 0, 32, 0, 0, 0, 0, 0, 56, 0 }, { 0, 37, 0, 1, 0, 0, 0, 73, 0 }, { 0, 38, 0, 0, 0, 0, 0, 72, 0 }, { 0, 43, 44, 47, 48, 51, 76, 77, 0 }, { 0, 0, 0, 0, 0, 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 neighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]] exists = [] lastNumber = 0 wid = 0 hei = 0 def find_next(pa, x, y, z): for i in range(4): a = x + neighbours[i][0] b = y + neighbours[i][1] if wid > a > -1 and hei > b > -1: if pa[a][b] == z: return a, b return -1, -1 def find_solution(pa, x, y, z): if z > lastNumber: return 1 if exists[z] == 1: s = find_next(pa, x, y, z) if s[0] < 0: return 0 return find_solution(pa, s[0], s[1], z + 1) for i in range(4): a = x + neighbours[i][0] b = y + neighbours[i][1] if wid > a > -1 and hei > b > -1: if pa[a][b] == 0: pa[a][b] = z r = find_solution(pa, a, b, z + 1) if r == 1: return 1 pa[a][b] = 0 return 0 def solve(pz, w, h): global lastNumber, wid, hei, exists lastNumber = w * h wid = w hei = h exists = [0 for j in range(lastNumber + 1)] pa = [[0 for j in range(h)] for i in range(w)] st = pz.split() idx = 0 for j in range(h): for i in range(w): if st[idx] == ".": idx += 1 else: pa[i][j] = int(st[idx]) exists[pa[i][j]] = 1 idx += 1 x = 0 y = 0 t = w * h + 1 for j in range(h): for i in range(w): if pa[i][j] != 0 and pa[i][j] < t: t = pa[i][j] x = i y = j return find_solution(pa, x, y, t + 1), pa def show_result(r): if r[0] == 1: for j in range(hei): for i in range(wid): stdout.write(" {:0{}d}".format(r[1][i][j], 2)) print() else: stdout.write("No Solution!\n") print() r = solve(". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17" " . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1 2 . . . . . . . . . . .", 9, 9) show_result(r) r = solve(". . . . . . . . . . 11 12 15 18 21 62 61 . . 6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37" " . 1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .", 9, 9) show_result(r) r = solve("17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55" " . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45", 9, 9) show_result(r)
Generate a Python translation of this C# snippet without changing its computational steps.
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)[] numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)}; private (int dx, int dy)[] moves; public static void Main() { var numbrixSolver = new Solver(numbrixMoves); Print(numbrixSolver.Solve(false, new [,] { { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 46, 45, 0, 55, 74, 0, 0 }, { 0, 38, 0, 0, 43, 0, 0, 78, 0 }, { 0, 35, 0, 0, 0, 0, 0, 71, 0 }, { 0, 0, 33, 0, 0, 0, 59, 0, 0 }, { 0, 17, 0, 0, 0, 0, 0, 67, 0 }, { 0, 18, 0, 0, 11, 0, 0, 64, 0 }, { 0, 0, 24, 21, 0, 1, 2, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, })); Print(numbrixSolver.Solve(false, new [,] { { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 11, 12, 15, 18, 21, 62, 61, 0 }, { 0, 6, 0, 0, 0, 0, 0, 60, 0 }, { 0, 33, 0, 0, 0, 0, 0, 57, 0 }, { 0, 32, 0, 0, 0, 0, 0, 56, 0 }, { 0, 37, 0, 1, 0, 0, 0, 73, 0 }, { 0, 38, 0, 0, 0, 0, 0, 72, 0 }, { 0, 43, 44, 47, 48, 51, 76, 77, 0 }, { 0, 0, 0, 0, 0, 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 neighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]] exists = [] lastNumber = 0 wid = 0 hei = 0 def find_next(pa, x, y, z): for i in range(4): a = x + neighbours[i][0] b = y + neighbours[i][1] if wid > a > -1 and hei > b > -1: if pa[a][b] == z: return a, b return -1, -1 def find_solution(pa, x, y, z): if z > lastNumber: return 1 if exists[z] == 1: s = find_next(pa, x, y, z) if s[0] < 0: return 0 return find_solution(pa, s[0], s[1], z + 1) for i in range(4): a = x + neighbours[i][0] b = y + neighbours[i][1] if wid > a > -1 and hei > b > -1: if pa[a][b] == 0: pa[a][b] = z r = find_solution(pa, a, b, z + 1) if r == 1: return 1 pa[a][b] = 0 return 0 def solve(pz, w, h): global lastNumber, wid, hei, exists lastNumber = w * h wid = w hei = h exists = [0 for j in range(lastNumber + 1)] pa = [[0 for j in range(h)] for i in range(w)] st = pz.split() idx = 0 for j in range(h): for i in range(w): if st[idx] == ".": idx += 1 else: pa[i][j] = int(st[idx]) exists[pa[i][j]] = 1 idx += 1 x = 0 y = 0 t = w * h + 1 for j in range(h): for i in range(w): if pa[i][j] != 0 and pa[i][j] < t: t = pa[i][j] x = i y = j return find_solution(pa, x, y, t + 1), pa def show_result(r): if r[0] == 1: for j in range(hei): for i in range(wid): stdout.write(" {:0{}d}".format(r[1][i][j], 2)) print() else: stdout.write("No Solution!\n") print() r = solve(". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17" " . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1 2 . . . . . . . . . . .", 9, 9) show_result(r) r = solve(". . . . . . . . . . 11 12 15 18 21 62 61 . . 6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37" " . 1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .", 9, 9) show_result(r) r = solve("17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55" " . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45", 9, 9) show_result(r)
Translate the given C# code snippet into Python without altering its behavior.
using System; public delegate Church Church(Church f); public static class ChurchNumeral { public static readonly Church ChurchZero = _ => x => x; public static readonly Church ChurchOne = f => f; public static Church Successor(this Church n) => f => x => f(n(f)(x)); public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x)); public static Church Multiply(this Church m, Church n) => f => m(n(f)); public static Church Exponent(this Church m, Church n) => n(m); public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne); public static Church Predecessor(this Church n) => f => x => n(g => h => h(g(f)))(_ => x)(a => a); public static Church Subtract(this Church m, Church n) => n(Predecessor)(m); static Church looper(this Church v, Church d) => v(_ => v.divr(d).Successor())(ChurchZero); static Church divr(this Church n, Church d) => n.Subtract(d).looper(d); public static Church Divide(this Church dvdnd, Church dvsr) => (dvdnd.Successor()).divr(dvsr); public static Church FromInt(int i) => i <= 0 ? ChurchZero : Successor(FromInt(i - 1)); public static int ToInt(this Church ch) { int count = 0; ch(x => { count++; return x; })(null); return count; } public static void Main() { Church c3 = FromInt(3); Church c4 = c3.Successor(); Church c11 = FromInt(11); Church c12 = c11.Successor(); int sum = c3.Add(c4).ToInt(); int product = c3.Multiply(c4).ToInt(); int exp43 = c4.Exponent(c3).ToInt(); int exp34 = c3.Exponent(c4).ToInt(); int tst0 = ChurchZero.IsZero().ToInt(); int pred4 = c4.Predecessor().ToInt(); int sub43 = c4.Subtract(c3).ToInt(); int div11by3 = c11.Divide(c3).ToInt(); int div12by3 = c12.Divide(c3).ToInt(); Console.Write($"{sum} {product} {exp43} {exp34} {tst0} "); Console.WriteLine($"{pred4} {sub43} {div11by3} {div12by3}"); } }
from itertools import repeat from functools import reduce def churchZero(): return lambda f: identity def churchSucc(cn): return lambda f: compose(f)(cn(f)) def churchAdd(m): return lambda n: lambda f: compose(m(f))(n(f)) def churchMult(m): return lambda n: compose(m)(n) def churchExp(m): return lambda n: n(m) def churchFromInt(n): return lambda f: ( foldl (compose) (identity) (replicate(n)(f)) ) def churchFromInt_(n): if 0 == n: return churchZero() else: return churchSucc(churchFromInt(n - 1)) def intFromChurch(cn): return cn(succ)(0) def main(): 'Tests' cThree = churchFromInt(3) cFour = churchFromInt(4) print(list(map(intFromChurch, [ churchAdd(cThree)(cFour), churchMult(cThree)(cFour), churchExp(cFour)(cThree), churchExp(cThree)(cFour), ]))) def compose(f): return lambda g: lambda x: g(f(x)) def foldl(f): def go(acc, xs): return reduce(lambda a, x: f(a)(x), xs, acc) return lambda acc: lambda xs: go(acc, xs) def identity(x): return x def replicate(n): return lambda x: repeat(x, n) def succ(x): return 1 + x if isinstance(x, int) else ( chr(1 + ord(x)) ) if __name__ == '__main__': main()
Write the same algorithm in Python as shown in this C# implementation.
using System; public delegate Church Church(Church f); public static class ChurchNumeral { public static readonly Church ChurchZero = _ => x => x; public static readonly Church ChurchOne = f => f; public static Church Successor(this Church n) => f => x => f(n(f)(x)); public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x)); public static Church Multiply(this Church m, Church n) => f => m(n(f)); public static Church Exponent(this Church m, Church n) => n(m); public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne); public static Church Predecessor(this Church n) => f => x => n(g => h => h(g(f)))(_ => x)(a => a); public static Church Subtract(this Church m, Church n) => n(Predecessor)(m); static Church looper(this Church v, Church d) => v(_ => v.divr(d).Successor())(ChurchZero); static Church divr(this Church n, Church d) => n.Subtract(d).looper(d); public static Church Divide(this Church dvdnd, Church dvsr) => (dvdnd.Successor()).divr(dvsr); public static Church FromInt(int i) => i <= 0 ? ChurchZero : Successor(FromInt(i - 1)); public static int ToInt(this Church ch) { int count = 0; ch(x => { count++; return x; })(null); return count; } public static void Main() { Church c3 = FromInt(3); Church c4 = c3.Successor(); Church c11 = FromInt(11); Church c12 = c11.Successor(); int sum = c3.Add(c4).ToInt(); int product = c3.Multiply(c4).ToInt(); int exp43 = c4.Exponent(c3).ToInt(); int exp34 = c3.Exponent(c4).ToInt(); int tst0 = ChurchZero.IsZero().ToInt(); int pred4 = c4.Predecessor().ToInt(); int sub43 = c4.Subtract(c3).ToInt(); int div11by3 = c11.Divide(c3).ToInt(); int div12by3 = c12.Divide(c3).ToInt(); Console.Write($"{sum} {product} {exp43} {exp34} {tst0} "); Console.WriteLine($"{pred4} {sub43} {div11by3} {div12by3}"); } }
from itertools import repeat from functools import reduce def churchZero(): return lambda f: identity def churchSucc(cn): return lambda f: compose(f)(cn(f)) def churchAdd(m): return lambda n: lambda f: compose(m(f))(n(f)) def churchMult(m): return lambda n: compose(m)(n) def churchExp(m): return lambda n: n(m) def churchFromInt(n): return lambda f: ( foldl (compose) (identity) (replicate(n)(f)) ) def churchFromInt_(n): if 0 == n: return churchZero() else: return churchSucc(churchFromInt(n - 1)) def intFromChurch(cn): return cn(succ)(0) def main(): 'Tests' cThree = churchFromInt(3) cFour = churchFromInt(4) print(list(map(intFromChurch, [ churchAdd(cThree)(cFour), churchMult(cThree)(cFour), churchExp(cFour)(cThree), churchExp(cThree)(cFour), ]))) def compose(f): return lambda g: lambda x: g(f(x)) def foldl(f): def go(acc, xs): return reduce(lambda a, x: f(a)(x), xs, acc) return lambda acc: lambda xs: go(acc, xs) def identity(x): return x def replicate(n): return lambda x: repeat(x, n) def succ(x): return 1 + x if isinstance(x, int) else ( chr(1 + ord(x)) ) if __name__ == '__main__': main()
Translate the given C# code snippet into Python without altering its behavior.
using System; public delegate Church Church(Church f); public static class ChurchNumeral { public static readonly Church ChurchZero = _ => x => x; public static readonly Church ChurchOne = f => f; public static Church Successor(this Church n) => f => x => f(n(f)(x)); public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x)); public static Church Multiply(this Church m, Church n) => f => m(n(f)); public static Church Exponent(this Church m, Church n) => n(m); public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne); public static Church Predecessor(this Church n) => f => x => n(g => h => h(g(f)))(_ => x)(a => a); public static Church Subtract(this Church m, Church n) => n(Predecessor)(m); static Church looper(this Church v, Church d) => v(_ => v.divr(d).Successor())(ChurchZero); static Church divr(this Church n, Church d) => n.Subtract(d).looper(d); public static Church Divide(this Church dvdnd, Church dvsr) => (dvdnd.Successor()).divr(dvsr); public static Church FromInt(int i) => i <= 0 ? ChurchZero : Successor(FromInt(i - 1)); public static int ToInt(this Church ch) { int count = 0; ch(x => { count++; return x; })(null); return count; } public static void Main() { Church c3 = FromInt(3); Church c4 = c3.Successor(); Church c11 = FromInt(11); Church c12 = c11.Successor(); int sum = c3.Add(c4).ToInt(); int product = c3.Multiply(c4).ToInt(); int exp43 = c4.Exponent(c3).ToInt(); int exp34 = c3.Exponent(c4).ToInt(); int tst0 = ChurchZero.IsZero().ToInt(); int pred4 = c4.Predecessor().ToInt(); int sub43 = c4.Subtract(c3).ToInt(); int div11by3 = c11.Divide(c3).ToInt(); int div12by3 = c12.Divide(c3).ToInt(); Console.Write($"{sum} {product} {exp43} {exp34} {tst0} "); Console.WriteLine($"{pred4} {sub43} {div11by3} {div12by3}"); } }
from itertools import repeat from functools import reduce def churchZero(): return lambda f: identity def churchSucc(cn): return lambda f: compose(f)(cn(f)) def churchAdd(m): return lambda n: lambda f: compose(m(f))(n(f)) def churchMult(m): return lambda n: compose(m)(n) def churchExp(m): return lambda n: n(m) def churchFromInt(n): return lambda f: ( foldl (compose) (identity) (replicate(n)(f)) ) def churchFromInt_(n): if 0 == n: return churchZero() else: return churchSucc(churchFromInt(n - 1)) def intFromChurch(cn): return cn(succ)(0) def main(): 'Tests' cThree = churchFromInt(3) cFour = churchFromInt(4) print(list(map(intFromChurch, [ churchAdd(cThree)(cFour), churchMult(cThree)(cFour), churchExp(cFour)(cThree), churchExp(cThree)(cFour), ]))) def compose(f): return lambda g: lambda x: g(f(x)) def foldl(f): def go(acc, xs): return reduce(lambda a, x: f(a)(x), xs, acc) return lambda acc: lambda xs: go(acc, xs) def identity(x): return x def replicate(n): return lambda x: repeat(x, n) def succ(x): return 1 + x if isinstance(x, int) else ( chr(1 + ord(x)) ) if __name__ == '__main__': main()
Translate the given C# code snippet into Python without altering its behavior.
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)[] hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)}, private (int dx, int dy)[] moves; public static void Main() { Print(new Solver(hopidoMoves).Solve(false, ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...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 neighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]] cnt = 0 pWid = 0 pHei = 0 def is_valid(a, b): return -1 < a < pWid and -1 < b < pHei def iterate(pa, x, y, v): if v > cnt: return 1 for i in range(len(neighbours)): a = x + neighbours[i][0] b = y + neighbours[i][1] if is_valid(a, b) and pa[a][b] == 0: pa[a][b] = v r = iterate(pa, a, b, v + 1) if r == 1: return r pa[a][b] = 0 return 0 def solve(pz, w, h): global cnt, pWid, pHei pa = [[-1 for j in range(h)] for i in range(w)] f = 0 pWid = w pHei = h for j in range(h): for i in range(w): if pz[f] == "1": pa[i][j] = 0 cnt += 1 f += 1 for y in range(h): for x in range(w): if pa[x][y] == 0: pa[x][y] = 1 if 1 == iterate(pa, x, y, 2): return 1, pa pa[x][y] = 0 return 0, pa r = solve("011011011111111111111011111000111000001000", 7, 6) if r[0] == 1: for j in range(6): for i in range(7): if r[1][i][j] == -1: stdout.write(" ") else: stdout.write(" {:0{}d}".format(r[1][i][j], 2)) print() else: stdout.write("No solution!")
Generate a Python translation of this C# snippet without changing its computational steps.
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)[] hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)}, private (int dx, int dy)[] moves; public static void Main() { Print(new Solver(hopidoMoves).Solve(false, ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...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 neighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]] cnt = 0 pWid = 0 pHei = 0 def is_valid(a, b): return -1 < a < pWid and -1 < b < pHei def iterate(pa, x, y, v): if v > cnt: return 1 for i in range(len(neighbours)): a = x + neighbours[i][0] b = y + neighbours[i][1] if is_valid(a, b) and pa[a][b] == 0: pa[a][b] = v r = iterate(pa, a, b, v + 1) if r == 1: return r pa[a][b] = 0 return 0 def solve(pz, w, h): global cnt, pWid, pHei pa = [[-1 for j in range(h)] for i in range(w)] f = 0 pWid = w pHei = h for j in range(h): for i in range(w): if pz[f] == "1": pa[i][j] = 0 cnt += 1 f += 1 for y in range(h): for x in range(w): if pa[x][y] == 0: pa[x][y] = 1 if 1 == iterate(pa, x, y, 2): return 1, pa pa[x][y] = 0 return 0, pa r = solve("011011011111111111111011111000111000001000", 7, 6) if r[0] == 1: for j in range(6): for i in range(7): if r[1][i][j] == -1: stdout.write(" ") else: stdout.write(" {:0{}d}".format(r[1][i][j], 2)) print() else: stdout.write("No solution!")
Convert this C# block to Python, preserving its control flow and logic.
using System; using System.Collections.Generic; using static System.Linq.Enumerable; public static class NonogramSolver { public static void Main2() { foreach (var (x, y) in new [] { ("C BA CB BB F AE F A B", "AB CA AE GA E C D C"), ("F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", "D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA"), ("CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC", "BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC"), ("E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G", "E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM") }) { Solve(x, y); Console.WriteLine(); } } static void Solve(string rowLetters, string columnLetters) { var r = rowLetters.Split(" ").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray(); var c = columnLetters.Split(" ").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray(); Solve(r, c); } static void Solve(int[][] rowRuns, int[][] columnRuns) { int len = columnRuns.Length; var rows = rowRuns.Select(row => Generate(len, row)).ToList(); var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList(); Reduce(rows, columns); foreach (var list in rows) { if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced()); else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced()); } } static List<BitSet> Generate(int length, params int[] runs) { var list = new List<BitSet>(); BitSet initial = BitSet.Empty; int[] sums = new int[runs.Length]; sums[0] = 0; for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1; for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]); Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0); return list; } static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) { if (index == runs.Length) { result.Add(current); return; } while (current.Value < max.Value) { Generate(result, max, runs, sums, current, index + 1, shift); current = current.ShiftLeftAt(sums[index] + shift); shift++; } } static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) { for (int count = 1; count > 0; ) { foreach (var (rowIndex, row) in rows.WithIndex()) { var allOn = row.Aggregate((a, b) => a & b); var allOff = row.Aggregate((a, b) => a | b); foreach (var (columnIndex, column) in columns.WithIndex()) { count = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex)); count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex)); } } foreach (var (columnIndex, column) in columns.WithIndex()) { var allOn = column.Aggregate((a, b) => a & b); var allOff = column.Aggregate((a, b) => a | b); foreach (var (rowIndex, row) in rows.WithIndex()) { count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex)); count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex)); } } } } static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) { int i = 0; foreach (T element in source) { yield return (i++, element); } } static string Reverse(this string s) { char[] array = s.ToCharArray(); Array.Reverse(array); return new string(array); } static string Spaced(this IEnumerable<char> s) => string.Join(" ", s); struct BitSet { public static BitSet Empty => default; private readonly int bits; public int Value => bits; private BitSet(int bits) => this.bits = bits; public BitSet Add(int item) => new BitSet(bits | (1 << item)); public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1))); public bool Contains(int item) => (bits & (1 << item)) != 0; public BitSet ShiftLeftAt(int index) => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1))); public override string ToString() => Convert.ToString(bits, 2); public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits); public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits); } }
from itertools import izip def gen_row(w, s): def gen_seg(o, sp): if not o: return [[2] * sp] return [[2] * x + o[0] + tail for x in xrange(1, sp - len(o) + 2) for tail in gen_seg(o[1:], sp - x)] return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))] def deduce(hr, vr): def allowable(row): return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row) def fits(a, b): return all(x & y for x, y in izip(a, b)) def fix_col(n): c = [x[n] for x in can_do] cols[n] = [x for x in cols[n] if fits(x, c)] for i, x in enumerate(allowable(cols[n])): if x != can_do[i][n]: mod_rows.add(i) can_do[i][n] &= x def fix_row(n): c = can_do[n] rows[n] = [x for x in rows[n] if fits(x, c)] for i, x in enumerate(allowable(rows[n])): if x != can_do[n][i]: mod_cols.add(i) can_do[n][i] &= x def show_gram(m): for x in m: print " ".join("x print w, h = len(vr), len(hr) rows = [gen_row(w, x) for x in hr] cols = [gen_row(h, x) for x in vr] can_do = map(allowable, rows) mod_rows, mod_cols = set(), set(xrange(w)) while mod_cols: for i in mod_cols: fix_col(i) mod_cols = set() for i in mod_rows: fix_row(i) mod_rows = set() if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)): print "Solution would be unique" else: print "Solution may not be unique, doing exhaustive search:" out = [0] * h def try_all(n = 0): if n >= h: for j in xrange(w): if [x[j] for x in out] not in cols[j]: return 0 show_gram(out) return 1 sol = 0 for x in rows[n]: out[n] = x sol += try_all(n + 1) return sol n = try_all() if not n: print "No solution." elif n == 1: print "Unique solution." else: print n, "solutions." print def solve(p, show_runs=True): s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()] for l in p.splitlines()] if show_runs: print "Horizontal runs:", s[0] print "Vertical runs:", s[1] deduce(s[0], s[1]) def main(): fn = "nonogram_problems.txt" for p in (x for x in open(fn).read().split("\n\n") if x): solve(p) print "Extra example not solvable by deduction alone:" solve("B B A A\nB B A A") print "Extra example where there is no solution:" solve("B A A\nA A A") main()
Convert the following code from C# to Python, ensuring the logic remains intact.
using System; using System.Collections.Generic; using static System.Linq.Enumerable; public static class NonogramSolver { public static void Main2() { foreach (var (x, y) in new [] { ("C BA CB BB F AE F A B", "AB CA AE GA E C D C"), ("F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", "D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA"), ("CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC", "BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC"), ("E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G", "E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM") }) { Solve(x, y); Console.WriteLine(); } } static void Solve(string rowLetters, string columnLetters) { var r = rowLetters.Split(" ").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray(); var c = columnLetters.Split(" ").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray(); Solve(r, c); } static void Solve(int[][] rowRuns, int[][] columnRuns) { int len = columnRuns.Length; var rows = rowRuns.Select(row => Generate(len, row)).ToList(); var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList(); Reduce(rows, columns); foreach (var list in rows) { if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced()); else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced()); } } static List<BitSet> Generate(int length, params int[] runs) { var list = new List<BitSet>(); BitSet initial = BitSet.Empty; int[] sums = new int[runs.Length]; sums[0] = 0; for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1; for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]); Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0); return list; } static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) { if (index == runs.Length) { result.Add(current); return; } while (current.Value < max.Value) { Generate(result, max, runs, sums, current, index + 1, shift); current = current.ShiftLeftAt(sums[index] + shift); shift++; } } static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) { for (int count = 1; count > 0; ) { foreach (var (rowIndex, row) in rows.WithIndex()) { var allOn = row.Aggregate((a, b) => a & b); var allOff = row.Aggregate((a, b) => a | b); foreach (var (columnIndex, column) in columns.WithIndex()) { count = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex)); count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex)); } } foreach (var (columnIndex, column) in columns.WithIndex()) { var allOn = column.Aggregate((a, b) => a & b); var allOff = column.Aggregate((a, b) => a | b); foreach (var (rowIndex, row) in rows.WithIndex()) { count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex)); count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex)); } } } } static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) { int i = 0; foreach (T element in source) { yield return (i++, element); } } static string Reverse(this string s) { char[] array = s.ToCharArray(); Array.Reverse(array); return new string(array); } static string Spaced(this IEnumerable<char> s) => string.Join(" ", s); struct BitSet { public static BitSet Empty => default; private readonly int bits; public int Value => bits; private BitSet(int bits) => this.bits = bits; public BitSet Add(int item) => new BitSet(bits | (1 << item)); public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1))); public bool Contains(int item) => (bits & (1 << item)) != 0; public BitSet ShiftLeftAt(int index) => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1))); public override string ToString() => Convert.ToString(bits, 2); public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits); public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits); } }
from itertools import izip def gen_row(w, s): def gen_seg(o, sp): if not o: return [[2] * sp] return [[2] * x + o[0] + tail for x in xrange(1, sp - len(o) + 2) for tail in gen_seg(o[1:], sp - x)] return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))] def deduce(hr, vr): def allowable(row): return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row) def fits(a, b): return all(x & y for x, y in izip(a, b)) def fix_col(n): c = [x[n] for x in can_do] cols[n] = [x for x in cols[n] if fits(x, c)] for i, x in enumerate(allowable(cols[n])): if x != can_do[i][n]: mod_rows.add(i) can_do[i][n] &= x def fix_row(n): c = can_do[n] rows[n] = [x for x in rows[n] if fits(x, c)] for i, x in enumerate(allowable(rows[n])): if x != can_do[n][i]: mod_cols.add(i) can_do[n][i] &= x def show_gram(m): for x in m: print " ".join("x print w, h = len(vr), len(hr) rows = [gen_row(w, x) for x in hr] cols = [gen_row(h, x) for x in vr] can_do = map(allowable, rows) mod_rows, mod_cols = set(), set(xrange(w)) while mod_cols: for i in mod_cols: fix_col(i) mod_cols = set() for i in mod_rows: fix_row(i) mod_rows = set() if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)): print "Solution would be unique" else: print "Solution may not be unique, doing exhaustive search:" out = [0] * h def try_all(n = 0): if n >= h: for j in xrange(w): if [x[j] for x in out] not in cols[j]: return 0 show_gram(out) return 1 sol = 0 for x in rows[n]: out[n] = x sol += try_all(n + 1) return sol n = try_all() if not n: print "No solution." elif n == 1: print "Unique solution." else: print n, "solutions." print def solve(p, show_runs=True): s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()] for l in p.splitlines()] if show_runs: print "Horizontal runs:", s[0] print "Vertical runs:", s[1] deduce(s[0], s[1]) def main(): fn = "nonogram_problems.txt" for p in (x for x in open(fn).read().split("\n\n") if x): solve(p) print "Extra example not solvable by deduction alone:" solve("B B A A\nB B A A") print "Extra example where there is no solution:" solve("B A A\nA A A") main()
Change the following C# code into Python without altering its purpose.
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Wordseach { static class Program { readonly static int[,] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}}; class Grid { public char[,] Cells = new char[nRows, nCols]; public List<string> Solutions = new List<string>(); public int NumAttempts; } readonly static int nRows = 10; readonly static int nCols = 10; readonly static int gridSize = nRows * nCols; readonly static int minWords = 25; readonly static Random rand = new Random(); static void Main(string[] args) { PrintResult(CreateWordSearch(ReadWords("unixdict.txt"))); } private static List<string> ReadWords(string filename) { int maxLen = Math.Max(nRows, nCols); return System.IO.File.ReadAllLines(filename) .Select(s => s.Trim().ToLower()) .Where(s => Regex.IsMatch(s, "^[a-z]{3," + maxLen + "}$")) .ToList(); } private static Grid CreateWordSearch(List<string> words) { int numAttempts = 0; while (++numAttempts < 100) { words.Shuffle(); var grid = new Grid(); int messageLen = PlaceMessage(grid, "Rosetta Code"); int target = gridSize - messageLen; int cellsFilled = 0; foreach (var word in words) { cellsFilled += TryPlaceWord(grid, word); if (cellsFilled == target) { if (grid.Solutions.Count >= minWords) { grid.NumAttempts = numAttempts; return grid; } else break; } } } return null; } private static int TryPlaceWord(Grid grid, string word) { int randDir = rand.Next(dirs.GetLength(0)); int randPos = rand.Next(gridSize); for (int dir = 0; dir < dirs.GetLength(0); dir++) { dir = (dir + randDir) % dirs.GetLength(0); for (int pos = 0; pos < gridSize; pos++) { pos = (pos + randPos) % gridSize; int lettersPlaced = TryLocation(grid, word, dir, pos); if (lettersPlaced > 0) return lettersPlaced; } } return 0; } private static int TryLocation(Grid grid, string word, int dir, int pos) { int r = pos / nCols; int c = pos % nCols; int len = word.Length; if ((dirs[dir, 0] == 1 && (len + c) > nCols) || (dirs[dir, 0] == -1 && (len - 1) > c) || (dirs[dir, 1] == 1 && (len + r) > nRows) || (dirs[dir, 1] == -1 && (len - 1) > r)) return 0; int rr, cc, i, overlaps = 0; for (i = 0, rr = r, cc = c; i < len; i++) { if (grid.Cells[rr, cc] != 0 && grid.Cells[rr, cc] != word[i]) { return 0; } cc += dirs[dir, 0]; rr += dirs[dir, 1]; } for (i = 0, rr = r, cc = c; i < len; i++) { if (grid.Cells[rr, cc] == word[i]) overlaps++; else grid.Cells[rr, cc] = word[i]; if (i < len - 1) { cc += dirs[dir, 0]; rr += dirs[dir, 1]; } } int lettersPlaced = len - overlaps; if (lettersPlaced > 0) { grid.Solutions.Add($"{word,-10} ({c},{r})({cc},{rr})"); } return lettersPlaced; } private static int PlaceMessage(Grid grid, string msg) { msg = Regex.Replace(msg.ToUpper(), "[^A-Z]", ""); int messageLen = msg.Length; if (messageLen > 0 && messageLen < gridSize) { int gapSize = gridSize / messageLen; for (int i = 0; i < messageLen; i++) { int pos = i * gapSize + rand.Next(gapSize); grid.Cells[pos / nCols, pos % nCols] = msg[i]; } return messageLen; } return 0; } public static void Shuffle<T>(this IList<T> list) { int n = list.Count; while (n > 1) { n--; int k = rand.Next(n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; } } private static void PrintResult(Grid grid) { if (grid == null || grid.NumAttempts == 0) { Console.WriteLine("No grid to display"); return; } int size = grid.Solutions.Count; Console.WriteLine("Attempts: " + grid.NumAttempts); Console.WriteLine("Number of words: " + size); Console.WriteLine("\n 0 1 2 3 4 5 6 7 8 9"); for (int r = 0; r < nRows; r++) { Console.Write("\n{0} ", r); for (int c = 0; c < nCols; c++) Console.Write(" {0} ", grid.Cells[r, c]); } Console.WriteLine("\n"); for (int i = 0; i < size - 1; i += 2) { Console.WriteLine("{0} {1}", grid.Solutions[i], grid.Solutions[i + 1]); } if (size % 2 == 1) Console.WriteLine(grid.Solutions[size - 1]); Console.ReadLine(); } } }
import re from random import shuffle, randint dirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]] n_rows = 10 n_cols = 10 grid_size = n_rows * n_cols min_words = 25 class Grid: def __init__(self): self.num_attempts = 0 self.cells = [['' for _ in range(n_cols)] for _ in range(n_rows)] self.solutions = [] def read_words(filename): max_len = max(n_rows, n_cols) words = [] with open(filename, "r") as file: for line in file: s = line.strip().lower() if re.match(r'^[a-z]{3,' + re.escape(str(max_len)) + r'}$', s) is not None: words.append(s) return words def place_message(grid, msg): msg = re.sub(r'[^A-Z]', "", msg.upper()) message_len = len(msg) if 0 < message_len < grid_size: gap_size = grid_size // message_len for i in range(0, message_len): pos = i * gap_size + randint(0, gap_size) grid.cells[pos // n_cols][pos % n_cols] = msg[i] return message_len return 0 def try_location(grid, word, direction, pos): r = pos // n_cols c = pos % n_cols length = len(word) if (dirs[direction][0] == 1 and (length + c) > n_cols) or \ (dirs[direction][0] == -1 and (length - 1) > c) or \ (dirs[direction][1] == 1 and (length + r) > n_rows) or \ (dirs[direction][1] == -1 and (length - 1) > r): return 0 rr = r cc = c i = 0 overlaps = 0 while i < length: if grid.cells[rr][cc] != '' and grid.cells[rr][cc] != word[i]: return 0 cc += dirs[direction][0] rr += dirs[direction][1] i += 1 rr = r cc = c i = 0 while i < length: if grid.cells[rr][cc] == word[i]: overlaps += 1 else: grid.cells[rr][cc] = word[i] if i < length - 1: cc += dirs[direction][0] rr += dirs[direction][1] i += 1 letters_placed = length - overlaps if letters_placed > 0: grid.solutions.append("{0:<10} ({1},{2})({3},{4})".format(word, c, r, cc, rr)) return letters_placed def try_place_word(grid, word): rand_dir = randint(0, len(dirs)) rand_pos = randint(0, grid_size) for direction in range(0, len(dirs)): direction = (direction + rand_dir) % len(dirs) for pos in range(0, grid_size): pos = (pos + rand_pos) % grid_size letters_placed = try_location(grid, word, direction, pos) if letters_placed > 0: return letters_placed return 0 def create_word_search(words): grid = None num_attempts = 0 while num_attempts < 100: num_attempts += 1 shuffle(words) grid = Grid() message_len = place_message(grid, "Rosetta Code") target = grid_size - message_len cells_filled = 0 for word in words: cells_filled += try_place_word(grid, word) if cells_filled == target: if len(grid.solutions) >= min_words: grid.num_attempts = num_attempts return grid else: break return grid def print_result(grid): if grid is None or grid.num_attempts == 0: print("No grid to display") return size = len(grid.solutions) print("Attempts: {0}".format(grid.num_attempts)) print("Number of words: {0}".format(size)) print("\n 0 1 2 3 4 5 6 7 8 9\n") for r in range(0, n_rows): print("{0} ".format(r), end='') for c in range(0, n_cols): print(" %c " % grid.cells[r][c], end='') print() print() for i in range(0, size - 1, 2): print("{0} {1}".format(grid.solutions[i], grid.solutions[i+1])) if size % 2 == 1: print(grid.solutions[size - 1]) if __name__ == "__main__": print_result(create_word_search(read_words("unixdict.txt")))
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 >>>