Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Maintain the same structure and functionality when rewriting this code in C#. | 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
... | 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.GetLengt... |
Transform the following Python implementation into C#, maintaining the same output and logic. | 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 sa... | 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);
... |
Maintain the same structure and functionality when rewriting this code in C#. | [print("( " + "1"*i + "3 ) ^ 2 = " + str(int("1"*i + "3")**2)) for i in range(0,8)]
| 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); } }
|
Port the following code from Python to C# with equivalent syntax and logic. | [print("( " + "1"*i + "3 ) ^ 2 = " + str(int("1"*i + "3")**2)) for i in range(0,8)]
| 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); } }
|
Ensure the translated C# code behaves exactly like the original Python snippet. | 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 ... | 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... |
Rewrite this program in C# while keeping its functionality equivalent to the Python version. | 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
re... | 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 vo... |
Maintain the same structure and functionality when rewriting this code in C#. | 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:
... | 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":" "); } }
|
Preserve the algorithm and functionality while converting the code from Python to C#. | import os
exit_code = os.system('ls')
output = os.popen('ls').read()
| using System.Diagnostics;
namespace Execute
{
class Program
{
static void Main(string[] args)
{
Process.Start("cmd.exe", "/c dir");
}
}
}
|
Produce a language-to-language conversion: from Python to C#, same semantics. |
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 ... | 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... |
Translate this program into C# but keep the logic exactly as in Python. | 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
... | 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>.E... |
Write the same algorithm in C# as shown in this Python implementation. | >>> 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(... | public
protected
internal
protected internal
private
private protected
|
Produce a functionally identical C# code for the snippet given in Python. | 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... | 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 M... |
Translate the given Python code snippet into C# without altering its behavior. | 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))
... | 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 _v... |
Produce a language-to-language conversion: from Python to C#, same semantics. | 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 ... | 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)
... |
Port the following code from Python to C# with equivalent syntax and logic. | 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):
... | 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> CheckS... |
Translate the given Python code snippet into C# without altering its behavior. |
def repeat(f,n):
for i in range(n):
f();
def procedure():
print("Example");
repeat(procedure,3);
| 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);
}
}
... |
Convert this Python snippet to C# and keep its semantics consistent. | >>> 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 l... | 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) {
... |
Write the same algorithm in C# as shown in this Python implementation. | 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()
| 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 s... |
Write the same code in C# as shown below in Python. | 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]... | 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 ==... |
Write the same code in C# as shown below in Python. | 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]... | 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 ==... |
Can you help me rewrite this code in C# instead of Python, keeping it the same logically? | 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 ... | 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}... |
Convert the following code from Python to C#, ensuring the logic remains intact. | 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()
|
var objDE = new System.DirectoryServices.DirectoryEntry("LDAP:
|
Convert this Python block to C#, preserving its control flow and logic. | 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]:
... | 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 ... |
Rewrite this program in C# while keeping its functionality equivalent to the Python version. | 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]:
... | 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 ... |
Port the following code from Python to C# with equivalent syntax and logic. | 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),
(memb... | 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, ... |
Rewrite the snippet below in C# so it works the same as the original Python code. |
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, p... | 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 cmconti... |
Change the following Python code into C# without altering its purpose. | 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]
>>>
| 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[] { x... |
Maintain the same structure and functionality when rewriting this code in C#. | 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]
>>>
| 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[] { x... |
Rewrite the snippet below in C# so it works the same as the original Python code. | 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 =... | 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... |
Maintain the same structure and functionality when rewriting this code in C#. | 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")**ex... | 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) {... |
Can you help me rewrite this code in C# instead of Python, keeping it the same logically? | 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")**ex... | 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) {... |
Port the provided Python code into C# while preserving the original functionality. | 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
... | 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: v... |
Produce a language-to-language conversion: from Python to C#, same semantics. | 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])
i... | 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, ... |
Port the provided Python code into C# while preserving the original functionality. | 2.3
.3
.3e4
.3e+34
.3e-34
2.e34
| 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;
|
Preserve the algorithm and functionality while converting the code from Python to C#. | 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:
... | 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... |
Write a version of this Python function in C# with identical behavior. | 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:
... | 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... |
Convert the following code from Python to C#, ensuring the logic remains intact. |
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)
... | 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 ... |
Write a version of this Python function in C# with identical behavior. |
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)
... | 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 ... |
Generate an equivalent C# version of this Python code. |
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)
... | 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 ... |
Transform the following Python implementation into C#, maintaining the same output and logic. | 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 + neighb... | 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)},
priva... |
Produce a language-to-language conversion: from Python to C#, same semantics. | 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 + neighb... | 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)},
priva... |
Preserve the algorithm and functionality while converting the code from Python to C#. | 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 ... | 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",
... |
Change the following Python code into C# without altering its purpose. | 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 ... | 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",
... |
Please provide an equivalent version of this Python code in C#. | 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 r... | 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
{
... |
Port the provided Python code into C# while preserving the original functionality. | >>> 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
>>>
| 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... |
Port the provided Python code into C# while preserving the original functionality. | >>> 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
>>>
| 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... |
Ensure the translated C# code behaves exactly like the original Python snippet. | >>> 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
>>>
| 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... |
Write the same algorithm in C# as shown in this Python implementation. |
import pickle
class Entity:
def __init__(self):
self.name = "Entity"
def printName(self):
print self.name
class Person(Entity):
def __init__(self):
self.name = "Cletus"
instance1 = Person()
instance1.printName()
instance2 = Entity()
instance2.printName()
target = file("objects.dat", "w")
pickle... | using System;
using System.IO;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
namespace Object_serialization
{
[Serializable] public class Being
{
public bool Alive { get; set; }
}
[Serializable] public class Animal: Being
{
public Animal() { }
public An... |
Can you help me rewrite this code in C# instead of Python, keeping it the same logically? |
from __future__ import print_function
class Node(object):
def __init__(self):
self.edges = {}
self.link = None
self.len = 0
class Eertree(object):
def __init__(self):
self.nodes = []
self.rto = Node()
self.rte = Node()
self.rto.link = self.rte.link = self.rto;
self.rto.len = -1
self.r... | using System;
using System.Collections.Generic;
namespace Eertree {
class Node {
public Node(int length) {
this.Length = length;
this.Edges = new Dictionary<char, int>();
}
public Node(int length, Dictionary<char, int> edges, int suffix) {
t... |
Maintain the same structure and functionality when rewriting this code in C#. |
from __future__ import print_function
class Node(object):
def __init__(self):
self.edges = {}
self.link = None
self.len = 0
class Eertree(object):
def __init__(self):
self.nodes = []
self.rto = Node()
self.rte = Node()
self.rto.link = self.rte.link = self.rto;
self.rto.len = -1
self.r... | using System;
using System.Collections.Generic;
namespace Eertree {
class Node {
public Node(int length) {
this.Length = length;
this.Edges = new Dictionary<char, int>();
}
public Node(int length, Dictionary<char, int> edges, int suffix) {
t... |
Rewrite this program in C# while keeping its functionality equivalent to the Python version. |
from datetime import date
def longYear(y):
return 52 < date(y, 12, 28).isocalendar()[1]
def main():
for year in [
x for x in range(2000, 1 + 2100)
if longYear(x)
]:
print(year)
if __name__ == '__main__':
main()
| using static System.Console;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
public static class Program
{
public static void Main()
{
WriteLine("Long years in the 21st century:");
WriteLine(string.Join(" ", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == ... |
Can you help me rewrite this code in C# instead of Python, keeping it the same logically? | from sympy import divisors
from sympy.combinatorics.subsets import Subset
def isZumkeller(n):
d = divisors(n)
s = sum(d)
if not s % 2 and max(d) <= s/2:
for x in range(1, 2**len(d)):
if sum(Subset.unrank_binary(x, d).subset) == s/2:
return True
return False
def ... | using System;
using System.Collections.Generic;
using System.Linq;
namespace ZumkellerNumbers {
class Program {
static List<int> GetDivisors(int n) {
List<int> divs = new List<int> {
1, n
};
for (int i = 2; i * i <= n; i++) {
if (n % i == ... |
Write the same code in C# as shown below in Python. | base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
result = {**base, **update}
print(result)
| using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main() {
var baseData = new Dictionary<string, object> {
["name"] = "Rocket Skates",
["price"] = 12.75,
["color"] = "yellow"
};
var updateData = n... |
Can you help me rewrite this code in C# instead of Python, keeping it the same logically? | base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
result = {**base, **update}
print(result)
| using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main() {
var baseData = new Dictionary<string, object> {
["name"] = "Rocket Skates",
["price"] = 12.75,
["color"] = "yellow"
};
var updateData = n... |
Translate the given Python code snippet into C# without altering its behavior. | from itertools import count, islice
from _pydecimal import getcontext, Decimal
def metallic_ratio(b):
m, n = 1, 1
while True:
yield m, n
m, n = m*b + n, m
def stable(b, prec):
def to_decimal(b):
for m,n in metallic_ratio(b):
yield Decimal(m)/Decimal(n)
getcontext()... | using static System.Math;
using static System.Console;
using BI = System.Numerics.BigInteger;
class Program {
static BI IntSqRoot(BI v, BI res) {
BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;
dl = d; d = term - res; } return term; }
static stri... |
Port the provided Python code into C# while preserving the original functionality. | from itertools import count, islice
from _pydecimal import getcontext, Decimal
def metallic_ratio(b):
m, n = 1, 1
while True:
yield m, n
m, n = m*b + n, m
def stable(b, prec):
def to_decimal(b):
for m,n in metallic_ratio(b):
yield Decimal(m)/Decimal(n)
getcontext()... | using static System.Math;
using static System.Console;
using BI = System.Numerics.BigInteger;
class Program {
static BI IntSqRoot(BI v, BI res) {
BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;
dl = d; d = term - res; } return term; }
static stri... |
Transform the following Python implementation into C#, maintaining the same output and logic. | import random, sys
def makerule(data, context):
rule = {}
words = data.split(' ')
index = context
for word in words[index:]:
key = ' '.join(words[index-context:index])
if key in rule:
rule[key].append(word)
else:
rule[key] = [word]
index... | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace MarkovChainTextGenerator {
class Program {
static string Join(string a, string b) {
return a + " " + b;
}
static string Markov(string filePath, int keySize, int outputSize) {
... |
Translate the given Python code snippet into C# without altering its behavior. | from collections import namedtuple, deque
from pprint import pprint as pp
inf = float('inf')
Edge = namedtuple('Edge', ['start', 'end', 'cost'])
class Graph():
def __init__(self, edges):
self.edges = [Edge(*edge) for edge in edges]
self.vertices = {e.start for e in self.edges} | {e.en... | using static System.Linq.Enumerable;
using static System.String;
using static System.Console;
using System.Collections.Generic;
using System;
using EdgeList = System.Collections.Generic.List<(int node, double weight)>;
public static class Dijkstra
{
public static void Main() {
Graph graph = new Graph(6);
... |
Produce a functionally identical C# code for the snippet given in Python. | import copy, random
def bitcount(n):
return bin(n).count("1")
def reoderingSign(i, j):
k = i >> 1
sum = 0
while k != 0:
sum += bitcount(k & j)
k = k >> 1
return 1.0 if ((sum & 1) == 0) else -1.0
class Vector:
def __init__(self, da):
self.dims = da
def dot(self, ot... | using System;
using System.Text;
namespace GeometricAlgebra {
struct Vector {
private readonly double[] dims;
public Vector(double[] da) {
dims = da;
}
public static Vector operator -(Vector v) {
return v * -1.0;
}
public static Vector oper... |
Generate a C# translation of this Python snippet without changing its computational steps. | class Node:
def __init__(self, sub="", children=None):
self.sub = sub
self.ch = children or []
class SuffixTree:
def __init__(self, str):
self.nodes = [Node()]
for i in range(len(str)):
self.addSuffix(str[i:])
def addSuffix(self, suf):
n = 0
i = ... | using System;
using System.Collections.Generic;
namespace SuffixTree {
class Node {
public string sub;
public List<int> ch = new List<int>();
public Node() {
sub = "";
}
public Node(string sub, params int[] children) {
this.sub... |
Please provide an equivalent version of this Python code in C#. | class Node:
def __init__(self, sub="", children=None):
self.sub = sub
self.ch = children or []
class SuffixTree:
def __init__(self, str):
self.nodes = [Node()]
for i in range(len(str)):
self.addSuffix(str[i:])
def addSuffix(self, suf):
n = 0
i = ... | using System;
using System.Collections.Generic;
namespace SuffixTree {
class Node {
public string sub;
public List<int> ch = new List<int>();
public Node() {
sub = "";
}
public Node(string sub, params int[] children) {
this.sub... |
Change the programming language of this snippet from Python to C# without modifying what it does. | myDict = { "hello": 13,
"world": 31,
"!" : 71 }
for key, value in myDict.items():
print ("key = %s, value = %s" % (key, value))
for key in myDict:
print ("key = %s" % key)
for key in myDict.keys():
print ("key = %s" % key)
for value in myDict.values():
print ("value = %s" % value)
| using System;
using System.Collections.Generic;
namespace AssocArrays
{
class Program
{
static void Main(string[] args)
{
Dictionary<string,int> assocArray = new Dictionary<string,int>();
assocArray["Hello"] = 1;
assocArray.Add("World", 2);
asso... |
Port the provided Python code into C# while preserving the original functionality. | >>> class num(int):
def __init__(self, b):
if 1 <= b <= 10:
return int.__init__(self+0)
else:
raise ValueError,"Value %s should be >=0 and <= 10" % b
>>> x = num(3)
>>> x = num(11)
Traceback (most recent call last):
File "<pyshell
x = num(11)
File "<pyshell... | using System;
using System.Globalization;
struct LimitedInt : IComparable, IComparable<LimitedInt>, IConvertible, IEquatable<LimitedInt>, IFormattable
{
const int MIN_VALUE = 1;
const int MAX_VALUE = 10;
public static readonly LimitedInt MinValue = new LimitedInt(MIN_VALUE);
public static readonly Lim... |
Change the programming language of this snippet from Python to C# without modifying what it does. | from sys import stdout
moves = [
[-1, -2], [1, -2], [-1, 2], [1, 2],
[-2, -1], [-2, 1], [2, -1], [2, 1]
]
def solve(pz, sz, sx, sy, idx, cnt):
if idx > cnt:
return 1
for i in range(len(moves)):
x = sx + moves[i][0]
y = sy + moves[i][1]
if sz > x > -1 and sz > y > -1 an... | using System.Collections;
using System.Collections.Generic;
using static System.Console;
using static System.Math;
using static System.Linq.Enumerable;
public class Solver
{
private static readonly (int dx, int dy)[]
knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)};
pri... |
Port the following code from Python to C# with equivalent syntax and logic. | from sys import stdout
moves = [
[-1, -2], [1, -2], [-1, 2], [1, 2],
[-2, -1], [-2, 1], [2, -1], [2, 1]
]
def solve(pz, sz, sx, sy, idx, cnt):
if idx > cnt:
return 1
for i in range(len(moves)):
x = sx + moves[i][0]
y = sy + moves[i][1]
if sz > x > -1 and sz > y > -1 an... | using System.Collections;
using System.Collections.Generic;
using static System.Console;
using static System.Math;
using static System.Linq.Enumerable;
public class Solver
{
private static readonly (int dx, int dy)[]
knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)};
pri... |
Convert this Python block to C#, preserving its control flow and logic. | from collections import defaultdict
def hashJoin(table1, index1, table2, index2):
h = defaultdict(list)
for s in table1:
h[s[index1]].append(s)
return [(s, r) for r in table2 for s in h[r[index2]]]
table1 = [(27, "Jonah"),
(18, "Alan"),
(28, "Glory"),
(18, "... | using System;
using System.Collections.Generic;
using System.Linq;
namespace HashJoin
{
public class AgeName
{
public AgeName(byte age, string name)
{
Age = age;
Name = name;
}
public byte Age { get; private set; }
public string Name { get; privat... |
Write the same code in C# as shown below in Python. |
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
if __name__ == '__main__':
for p in range(3, 999):
if not isPrime(p):
continue
for q in range(p+1, 1000//p):
if not isPrime(q):
... | using System; using static System.Console; using System.Collections;
using System.Linq; using System.Collections.Generic;
class Program { static void Main(string[] args) {
int lmt = 1000, amt, c = 0, sr = (int)Math.Sqrt(lmt), lm2; var res = new List<int>();
var pr = PG.Primes(lmt / 3 + 5).ToArray(); lm2 = pr.O... |
Translate the given Python code snippet into C# without altering its behavior. |
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
if __name__ == '__main__':
for p in range(3, 999):
if not isPrime(p):
continue
for q in range(p+1, 1000//p):
if not isPrime(q):
... | using System; using static System.Console; using System.Collections;
using System.Linq; using System.Collections.Generic;
class Program { static void Main(string[] args) {
int lmt = 1000, amt, c = 0, sr = (int)Math.Sqrt(lmt), lm2; var res = new List<int>();
var pr = PG.Primes(lmt / 3 + 5).ToArray(); lm2 = pr.O... |
Generate a C# translation of this Python snippet without changing its computational steps. | from __future__ import print_function
from __future__ import division
def extended_synthetic_division(dividend, divisor):
out = list(dividend)
normalizer = divisor[0]
for i in xrange(len(dividend)-(len(divisor)-1)):
out[i] /= normalizer
coef... | using System;
using System.Collections.Generic;
using System.Linq;
namespace SyntheticDivision
{
class Program
{
static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)
{
List<int> output = dividend.ToList();
int normalizer = divisor... |
Change the programming language of this snippet from Python to C# without modifying what it does. | from __future__ import print_function
from __future__ import division
def extended_synthetic_division(dividend, divisor):
out = list(dividend)
normalizer = divisor[0]
for i in xrange(len(dividend)-(len(divisor)-1)):
out[i] /= normalizer
coef... | using System;
using System.Collections.Generic;
using System.Linq;
namespace SyntheticDivision
{
class Program
{
static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)
{
List<int> output = dividend.ToList();
int normalizer = divisor... |
Generate an equivalent C# version of this Python code. | from __future__ import print_function
from __future__ import division
def extended_synthetic_division(dividend, divisor):
out = list(dividend)
normalizer = divisor[0]
for i in xrange(len(dividend)-(len(divisor)-1)):
out[i] /= normalizer
coef... | using System;
using System.Collections.Generic;
using System.Linq;
namespace SyntheticDivision
{
class Program
{
static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)
{
List<int> output = dividend.ToList();
int normalizer = divisor... |
Keep all operations the same but rewrite the snippet in C#. | class Example(object):
def foo(self):
print("this is foo")
def bar(self):
print("this is bar")
def __getattr__(self, name):
def method(*args):
print("tried to handle unknown method " + name)
if args:
print("it had arguments: " + str(args))
... | using System;
using System.Dynamic;
class Example : DynamicObject
{
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
result = null;
Console.WriteLine("This is {0}.", binder.Name);
return true;
}
}
class Program
{
static void M... |
Convert this Python snippet to C# and keep its semantics consistent. | def dList(n, start):
start -= 1
a = range(n)
a[start] = a[0]
a[0] = start
a[1:] = sorted(a[1:])
first = a[1]
r = []
def recurse(last):
if (last == first):
for j,v in enumerate(a[1:]):
if j + 1 == v:
... | using System;
using System.Collections.Generic;
using System.Linq;
namespace LatinSquares {
using matrix = List<List<int>>;
class Program {
static void Swap<T>(ref T a, ref T b) {
var t = a;
a = b;
b = t;
}
static matrix DList(int n, int start) {
... |
Change the programming language of this snippet from Python to C# without modifying what it does. |
from random import randint, randrange
from operator import itemgetter, attrgetter
infinity = float('inf')
def bruteForceClosestPair(point):
numPoints = len(point)
if numPoints < 2:
return infinity, (None, None)
return min( ((abs(point[i] - point[j]), (point[i], point[j]))
for ... | class Segment
{
public Segment(PointF p1, PointF p2)
{
P1 = p1;
P2 = p2;
}
public readonly PointF P1;
public readonly PointF P2;
public float Length()
{
return (float)Math.Sqrt(LengthSquared());
}
public float LengthSquared()
{
return (P1.X - P2... |
Convert this Python snippet to C# and keep its semantics consistent. | var num = 12
var pointer = ptr(num)
print pointer
@unsafe
pointer.addr = 0xFFFE
| int i = 5;
int* p = &i;
|
Convert this Python block to C#, preserving its control flow and logic. | class Animal:
pass
class Dog(Animal):
pass
class Cat(Animal):
pass
class Lab(Dog):
pass
class Collie(Dog):
pass
| class Animal
{
}
class Dog : Animal
{
}
class Lab : Dog
{
}
class Collie : Dog
{
}
class Cat : Animal
{
}
|
Translate the given Python code snippet into C# without altering its behavior. | hash = dict()
hash = dict(red="FF0000", green="00FF00", blue="0000FF")
hash = { 'key1':1, 'key2':2, }
value = hash[key]
| System.Collections.HashTable map = new System.Collections.HashTable();
map["key1"] = "foo";
|
Convert this Python block to C#, preserving its control flow and logic. | size(300, 300)
background(0)
radius = min(width, height) / 2.0
cx, cy = width / 2, width / 2
for x in range(width):
for y in range(height):
rx = x - cx
ry = y - cy
s = sqrt(rx ** 2 + ry ** 2) / radius
if s <= 1.0:
h = ((atan2(ry, rx) / PI) + 1.0) /... |
public MainWindow()
{
InitializeComponent();
RenderOptions.SetBitmapScalingMode(imgMain, BitmapScalingMode.HighQuality);
imgMain.Source = new WriteableBitmap(480, 480, 96, 96, PixelFormats.Bgr32, null);
DrawHue(100);
}
void DrawHue(int saturation)
{
var bmp = (WriteableBitmap)imgMain.Source;... |
Preserve the algorithm and functionality while converting the code from Python to C#. | class Point(object):
def __init__(self, x=0.0, y=0.0):
self.x = x
self.y = y
def __repr__(self):
return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y)
class Circle(object):
def __init__(self, center=None, radius=1.0):
self.center = center or Point()
self.rad... | using System;
class Point
{
protected int x, y;
public Point() : this(0) {}
public Point(int x) : this(x,0) {}
public Point(int x, int y) { this.x = x; this.y = y; }
public int X { get { return x; } set { x = value; } }
public int Y { get { return y; } set { y = value; } }
public virtual void print() { Sy... |
Please provide an equivalent version of this Python code in C#. | class Point(object):
def __init__(self, x=0.0, y=0.0):
self.x = x
self.y = y
def __repr__(self):
return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y)
class Circle(object):
def __init__(self, center=None, radius=1.0):
self.center = center or Point()
self.rad... | using System;
class Point
{
protected int x, y;
public Point() : this(0) {}
public Point(int x) : this(x,0) {}
public Point(int x, int y) { this.x = x; this.y = y; }
public int X { get { return x; } set { x = value; } }
public int Y { get { return y; } set { y = value; } }
public virtual void print() { Sy... |
Generate a C# translation of this Python snippet without changing its computational steps. |
from math import floor, sqrt
from datetime import datetime
def main():
start = datetime.now()
for i in xrange(1, 10 ** 11):
if rare(i):
print "found a rare:", i
end = datetime.now()
print "time elapsed:", end - start
def is_square(n):
s = floor(sqrt(n + 0.5))
return s * s == n
def reverse(n):
return ... | using System;
using System.Collections.Generic;
using System.Linq;
using static System.Console;
using UI = System.UInt64;
using LST = System.Collections.Generic.List<System.Collections.Generic.List<sbyte>>;
using Lst = System.Collections.Generic.List<sbyte>;
using DT = System.DateTime;
class Program {
const sbyte... |
Translate this program into C# but keep the logic exactly as in Python. |
gridsize = (6, 4)
minerange = (0.2, 0.6)
try:
raw_input
except:
raw_input = input
import random
from itertools import product
from pprint import pprint as pp
def gridandmines(gridsize=gridsize, minerange=minerange):
xgrid, ygrid = gridsize
minmines, maxmines = minerange
minecount = xgri... | using System;
using System.Drawing;
using System.Windows.Forms;
class MineFieldModel
{
public int RemainingMinesCount{
get{
var count = 0;
ForEachCell((i,j)=>{
if (Mines[i,j] && !Marked[i,j])
count++;
});
return count;
... |
Ensure the translated C# code behaves exactly like the original Python snippet. |
from operator import le
from itertools import takewhile
def monotonicDigits(base):
def go(n):
return monotonic(le)(
showIntAtBase(base)(digitFromInt)(n)('')
)
return go
def monotonic(op):
def go(xs):
return all(map(op, xs, xs[1:]))
return go
def ... | using System.Linq; using System.Collections.Generic; using static System.Console; using static System.Math;
class Program {
static int ba; static string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
static string from10(int b) { string res = ""; int re; while (b > 0) {
b = Div... |
Can you help me rewrite this code in C# instead of Python, keeping it the same logically? |
from operator import le
from itertools import takewhile
def monotonicDigits(base):
def go(n):
return monotonic(le)(
showIntAtBase(base)(digitFromInt)(n)('')
)
return go
def monotonic(op):
def go(xs):
return all(map(op, xs, xs[1:]))
return go
def ... | using System.Linq; using System.Collections.Generic; using static System.Console; using static System.Math;
class Program {
static int ba; static string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
static string from10(int b) { string res = ""; int re; while (b > 0) {
b = Div... |
Translate this program into C# but keep the logic exactly as in Python. | class Parent(object):
__priv = 'private'
def __init__(self, name):
self.name = name
def __repr__(self):
return '%s(%s)' % (type(self).__name__, self.name)
def doNothing(self):
pass
import re
class Child(Parent):
__rePrivate = re.compile('^_(Child|Parent)... | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public static class Reflection
{
public static void Main() {
var t = new TestClass();
var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
foreach (var prop in GetPropert... |
Keep all operations the same but rewrite the snippet in C#. | class Parent(object):
__priv = 'private'
def __init__(self, name):
self.name = name
def __repr__(self):
return '%s(%s)' % (type(self).__name__, self.name)
def doNothing(self):
pass
import re
class Child(Parent):
__rePrivate = re.compile('^_(Child|Parent)... | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public static class Reflection
{
public static void Main() {
var t = new TestClass();
var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
foreach (var prop in GetPropert... |
Change the following Python code into C# without altering its purpose. | from functools import lru_cache
DIVS = {2, 3}
SUBS = {1}
class Minrec():
"Recursive, memoised minimised steps to 1"
def __init__(self, divs=DIVS, subs=SUBS):
self.divs, self.subs = divs, subs
@lru_cache(maxsize=None)
def _minrec(self, n):
"Recursive, memoised"
if n == 1:
... | using System;
using System.Collections.Generic;
using System.Linq;
public static class MinimalSteps
{
public static void Main() {
var (divisors, subtractors) = (new int[] { 2, 3 }, new [] { 1 });
var lookup = CreateLookup(2_000, divisors, subtractors);
Console.WriteLine($"Divisors: [{diviso... |
Port the provided Python code into C# while preserving the original functionality. | from itertools import zip_longest
txt =
parts = [line.rstrip("$").split("$") for line in txt.splitlines()]
widths = [max(len(word) for word in col)
for col in zip_longest(*parts, fillvalue='')]
for justify in "<_Left ^_Center >_Right".split():
j, jtext = justify.split('_')
print(f"{jtext} colum... | using System;
class ColumnAlignerProgram
{
delegate string Justification(string s, int width);
static string[] AlignColumns(string[] lines, Justification justification)
{
const char Separator = '$';
string[][] table = new string[lines.Length][];
int columns = 0;
for... |
Write a version of this Python function in C# with identical behavior. | import urllib.parse as up
url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1
print('url.scheme = ', url.scheme)
print('url.netloc = ', url.netloc)
print('url.hostname = ', url.hostname)
print('url.port = ', url.port)
print('url.path = ', url.path)
print('url.params = ', url.params)
p... | using System;
namespace RosettaUrlParse
{
class Program
{
static void ParseUrl(string url)
{
var u = new Uri(url);
Console.WriteLine("URL: {0}", u.AbsoluteUri);
Console.WriteLine("Scheme: {0}", u.Scheme);
Console.WriteLine("Host: ... |
Write the same algorithm in C# as shown in this Python implementation. | import urllib.parse as up
url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1
print('url.scheme = ', url.scheme)
print('url.netloc = ', url.netloc)
print('url.hostname = ', url.hostname)
print('url.port = ', url.port)
print('url.path = ', url.path)
print('url.params = ', url.params)
p... | using System;
namespace RosettaUrlParse
{
class Program
{
static void ParseUrl(string url)
{
var u = new Uri(url);
Console.WriteLine("URL: {0}", u.AbsoluteUri);
Console.WriteLine("Scheme: {0}", u.Scheme);
Console.WriteLine("Host: ... |
Port the following code from Python to C# with equivalent syntax and logic. |
def is_idoneal(num):
for a in range(1, num):
for b in range(a + 1, num):
if a * b + a + b > num:
break
for c in range(b + 1, num):
sum3 = a * b + b * c + a * c
if sum3 == num:
return False
if ... | using System;
class Program {
static void Main(string[] args) {
var sw = System.Diagnostics.Stopwatch.StartNew();
int a, b, c, i, n, s3, ab; var res = new int[65];
for (n = 1, i = 0; n < 1850; n++) {
bool found = true;
for (a = 1; a < n; a++)
for (b = a + 1, ab = a * b + a + b; b < ... |
Rewrite the snippet below in C# so it works the same as the original Python code. | ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
def convertToBase58(num):
sb = ''
while (num > 0):
r = num % 58
sb = sb + ALPHABET[r]
num = num // 58;
return sb[::-1]
s = 25420294593250030202636073700053352635053786165627414518
b = convertToBase58(s)
print("... | using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;
namespace Base58CheckEncoding {
class Program {
const string ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
static BigInteger ToBigInteger(string value, int @base) {
cons... |
Change the programming language of this snippet from Python to C# without modifying what it does. | ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
def convertToBase58(num):
sb = ''
while (num > 0):
r = num % 58
sb = sb + ALPHABET[r]
num = num // 58;
return sb[::-1]
s = 25420294593250030202636073700053352635053786165627414518
b = convertToBase58(s)
print("... | using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;
namespace Base58CheckEncoding {
class Program {
const string ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
static BigInteger ToBigInteger(string value, int @base) {
cons... |
Translate the given Python code snippet into C# without altering its behavior. | >>> name = raw_input("Enter a variable name: ")
Enter a variable name: X
>>> globals()[name] = 42
>>> X
42
| using System;
using System.Dynamic;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
string varname = Console.ReadLine();
dynamic expando = new ExpandoObject();
var map = expando as IDictionary<string, object>;
map.Add(varname, "Hello... |
Write the same algorithm in C# as shown in this Python implementation. | class Head():
def __init__(self, lo, hi=None, shift=0):
if hi is None: hi = lo
d = hi - lo
ds, ls, hs = str(d), str(lo), str(hi)
if d and len(ls) > len(ds):
assert(len(ls) - len(ds) + 1 > 21)
lo = int(str(lo)[:len(ls) - len(ds) + 1])
hi = int(str... | using System;
using System.IO;
using System.Numerics;
using System.Threading;
using System.Diagnostics;
using System.Globalization;
namespace Fibonacci {
class Program
{
private static readonly BigInteger[,] F = { { BigInteger.One, BigInteger.One }, { BigInteger.One, BigInteger.Zero } };
privat... |
Rewrite the snippet below in C# so it works the same as the original Python code. | class Head():
def __init__(self, lo, hi=None, shift=0):
if hi is None: hi = lo
d = hi - lo
ds, ls, hs = str(d), str(lo), str(hi)
if d and len(ls) > len(ds):
assert(len(ls) - len(ds) + 1 > 21)
lo = int(str(lo)[:len(ls) - len(ds) + 1])
hi = int(str... | using System;
using System.IO;
using System.Numerics;
using System.Threading;
using System.Diagnostics;
using System.Globalization;
namespace Fibonacci {
class Program
{
private static readonly BigInteger[,] F = { { BigInteger.One, BigInteger.One }, { BigInteger.One, BigInteger.Zero } };
privat... |
Rewrite the snippet below in C# so it works the same as the original Python code. |
T=[set([(0, 0)])]
def double(it):
for a, b in it:
yield a, b
yield b, a
def tails(n):
if len(T)<=n:
l = set()
for i in range(10):
for j in range(i, 10):
I = i*10**(n-1)
J = j*10**(n-1)
it = tails(n-1)
... | using System;
class Program {
static bool isPal(int n) {
int rev = 0, lr = -1, rem;
while (n > rev) {
n = Math.DivRem(n, 10, out rem);
if (lr < 0 && rem == 0) return false;
lr = rev; rev = 10 * rev + rem;
if (n == rev || n == lr) return true;
} return false; }
static void Main(... |
Convert the following code from Python to C#, ensuring the logic remains intact. | import re as RegEx
def Commatize( _string, _startPos=0, _periodLen=3, _separator="," ):
outString = ""
strPos = 0
matches = RegEx.findall( "[0-9]*", _string )
for match in matches[:-1]:
if not match:
outString += _string[ strPos ]
strPos += 1
else:
if len(match) > _periodLen:
leadIn = match[:_st... | static string[] inputs = {
"pi=3.14159265358979323846264338327950288419716939937510582097494459231",
"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).",
"\"-in Aus$+1411.8millions\"",
"===US$0017440 millions=== (in 2000 dollars)"
};
void Main()
{
inputs.Select(s => Commatize(s, 0, 3, ","))
... |
Can you help me rewrite this code in C# instead of Python, keeping it the same logically? | from collections import Counter
def cumulative_freq(freq):
cf = {}
total = 0
for b in range(256):
if b in freq:
cf[b] = total
total += freq[b]
return cf
def arithmethic_coding(bytes, radix):
freq = Counter(bytes)
cf = cumulative_freq(freq)
... | using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
namespace AruthmeticCoding {
using Freq = Dictionary<char, long>;
using Triple = Tuple<BigInteger, int, Dictionary<char, long>>;
class Program {
static Freq CumulativeFreq(Freq freq) {
... |
Translate this program into C# but keep the logic exactly as in Python. | def kosaraju(g):
class nonlocal: pass
size = len(g)
vis = [False]*size
l = [0]*size
nonlocal.x = size
t = [[]]*size
def visit(u):
if not vis[u]:
vis[u] = True
for v in g[u]:
visit(v)
t[v] = t[v] + [u]
non... | using System;
using System.Collections.Generic;
class Node
{
public enum Colors
{
Black, White, Gray
}
public Colors color { get; set; }
public int N { get; }
public Node(int n)
{
N = n;
color = Colors.White;
}
}
class Graph
{
public HashSet<Node> V { get; }
public Dictionary<Node, HashSet<Node>> A... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.