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 Python.
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace RosettaRecursiveDirectory { class Program { static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern) { var directoryStack = new Stack<DirectoryInfo>(); directoryStack.Push(new DirectoryInfo(rootPath)); while (directoryStack.Count > 0) { var dir = directoryStack.Pop(); try { foreach (var i in dir.GetDirectories()) directoryStack.Push(i); } catch (UnauthorizedAccessException) { continue; } foreach (var f in dir.GetFiles().Where(Pattern)) yield return f; } } static void Main(string[] args) { foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv")) Console.WriteLine(file.FullName); Console.WriteLine("Done."); } } }
from pathlib import Path for path in Path('.').rglob('*.*'): print(path)
Transform the following C# implementation into Python, maintaining the same output and logic.
public class Crc32 { #region Constants private const UInt32 s_generator = 0xEDB88320; #endregion #region Constructors public Crc32() { m_checksumTable = Enumerable.Range(0, 256).Select(i => { var tableEntry = (uint)i; for (var j = 0; j < 8; ++j) { tableEntry = ((tableEntry & 1) != 0) ? (s_generator ^ (tableEntry >> 1)) : (tableEntry >> 1); } return tableEntry; }).ToArray(); } #endregion #region Methods public UInt32 Get<T>(IEnumerable<T> byteStream) { try { return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8))); } catch (FormatException e) { throw new CrcException("Could not read the stream out as bytes.", e); } catch (InvalidCastException e) { throw new CrcException("Could not read the stream out as bytes.", e); } catch (OverflowException e) { throw new CrcException("Could not read the stream out as bytes.", e); } } #endregion #region Fields private readonly UInt32[] m_checksumTable; #endregion }
>>> s = 'The quick brown fox jumps over the lazy dog' >>> import zlib >>> hex(zlib.crc32(s)) '0x414fa339' >>> import binascii >>> hex(binascii.crc32(s)) '0x414fa339'
Translate the given C# code snippet into Python without altering its behavior.
public class MyClass { public MyClass() { } public void SomeMethod() { } private int _variable; public int Variable { get { return _variable; } set { _variable = value; } } public static void Main() { MyClass instance = new MyClass(); instance.SomeMethod(); instance.Variable = 99; System.Console.WriteLine( "Variable=" + instance.Variable.ToString() ); } }
class MyClass: name2 = 2 def __init__(self): self.name1 = 0 def someMethod(self): self.name1 = 1 MyClass.name2 = 3 myclass = MyClass() class MyOtherClass: count = 0 def __init__(self, name, gender="Male", age=None): MyOtherClass.count += 1 self.name = name self.gender = gender if age is not None: self.age = age def __del__(self): MyOtherClass.count -= 1 person1 = MyOtherClass("John") print person1.name, person1.gender print person1.age person2 = MyOtherClass("Jane", "Female", 23) print person2.name, person2.gender, person2.age
Convert the following code from C# to Python, ensuring the logic remains intact.
using System; using System.Collections.Generic; public class KaprekarNumbers { public static void Main() { int count = 0; foreach ( ulong i in _kaprekarGenerator(999999) ) { Console.WriteLine(i); count++; } Console.WriteLine("There are {0} Kaprekar numbers less than 1000000.", count); } private static IEnumerable<ulong> _kaprekarGenerator(ulong max) { ulong next = 1; yield return next; for ( next = 2; next <= max; next++ ) { ulong square = next * next; for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) { if ( square <= check ) break; ulong r = square % check; ulong q = (square - r) / check; if ( r != 0 && q + r == next ) { yield return next; break; } } } } }
>>> def k(n): n2 = str(n**2) for i in range(len(n2)): a, b = int(n2[:i] or 0), int(n2[i:]) if b and a + b == n: return n >>> [x for x in range(1,10000) if k(x)] [1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999] >>> len([x for x in range(1,1000000) if k(x)]) 54 >>>
Produce a functionally identical Python code for the snippet given in C#.
using System; using System.Collections.Generic; public class KaprekarNumbers { public static void Main() { int count = 0; foreach ( ulong i in _kaprekarGenerator(999999) ) { Console.WriteLine(i); count++; } Console.WriteLine("There are {0} Kaprekar numbers less than 1000000.", count); } private static IEnumerable<ulong> _kaprekarGenerator(ulong max) { ulong next = 1; yield return next; for ( next = 2; next <= max; next++ ) { ulong square = next * next; for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) { if ( square <= check ) break; ulong r = square % check; ulong q = (square - r) / check; if ( r != 0 && q + r == next ) { yield return next; break; } } } } }
>>> def k(n): n2 = str(n**2) for i in range(len(n2)): a, b = int(n2[:i] or 0), int(n2[i:]) if b and a + b == n: return n >>> [x for x in range(1,10000) if k(x)] [1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999] >>> len([x for x in range(1,1000000) if k(x)]) 54 >>>
Convert the following code from C# to Python, ensuring the logic remains intact.
using System; using System.Collections.Generic; public class KaprekarNumbers { public static void Main() { int count = 0; foreach ( ulong i in _kaprekarGenerator(999999) ) { Console.WriteLine(i); count++; } Console.WriteLine("There are {0} Kaprekar numbers less than 1000000.", count); } private static IEnumerable<ulong> _kaprekarGenerator(ulong max) { ulong next = 1; yield return next; for ( next = 2; next <= max; next++ ) { ulong square = next * next; for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) { if ( square <= check ) break; ulong r = square % check; ulong q = (square - r) / check; if ( r != 0 && q + r == next ) { yield return next; break; } } } } }
>>> def k(n): n2 = str(n**2) for i in range(len(n2)): a, b = int(n2[:i] or 0), int(n2[i:]) if b and a + b == n: return n >>> [x for x in range(1,10000) if k(x)] [1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999] >>> len([x for x in range(1,1000000) if k(x)]) 54 >>>
Maintain the same structure and functionality when rewriting this code in Python.
using System; using System.Collections.Generic; using System.Linq; namespace HofstadterFigureFigure { class HofstadterFigureFigure { readonly List<int> _r = new List<int>() {1}; readonly List<int> _s = new List<int>(); public IEnumerable<int> R() { int iR = 0; while (true) { if (iR >= _r.Count) { Advance(); } yield return _r[iR++]; } } public IEnumerable<int> S() { int iS = 0; while (true) { if (iS >= _s.Count) { Advance(); } yield return _s[iS++]; } } private void Advance() { int rCount = _r.Count; int oldR = _r[rCount - 1]; int sVal; switch (rCount) { case 1: sVal = 2; break; case 2: sVal = 4; break; default: sVal = _s[rCount - 1]; break; } _r.Add(_r[rCount - 1] + sVal); int newR = _r[rCount]; for (int iS = oldR + 1; iS < newR; iS++) { _s.Add(iS); } } } class Program { static void Main() { var hff = new HofstadterFigureFigure(); var rs = hff.R(); var arr = rs.Take(40).ToList(); foreach(var v in arr.Take(10)) { Console.WriteLine("{0}", v); } var hs = new HashSet<int>(arr); hs.UnionWith(hff.S().Take(960)); Console.WriteLine(hs.Count == 1000 ? "Verified" : "Oops! Something's wrong!"); } } }
def ffr(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffr.r[n] except IndexError: r, s = ffr.r, ffs.s ffr_n_1 = ffr(n-1) lastr = r[-1] s += list(range(s[-1] + 1, lastr)) if s[-1] < lastr: s += [lastr + 1] len_s = len(s) ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1] ans = ffr_n_1 + ffs_n_1 r.append(ans) return ans ffr.r = [None, 1] def ffs(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffs.s[n] except IndexError: r, s = ffr.r, ffs.s for i in range(len(r), n+2): ffr(i) if len(s) > n: return s[n] raise Exception("Whoops!") ffs.s = [None, 2] if __name__ == '__main__': first10 = [ffr(i) for i in range(1,11)] assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], "ffr() value error(s)" print("ffr(n) for n = [1..10] is", first10) bin = [None] + [0]*1000 for i in range(40, 0, -1): bin[ffr(i)] += 1 for i in range(960, 0, -1): bin[ffs(i)] += 1 if all(b == 1 for b in bin[1:1000]): print("All Integers 1..1000 found OK") else: print("All Integers 1..1000 NOT found only once: ERROR")
Port the provided C# code into Python while preserving the original functionality.
using System; using System.Collections.Generic; using System.Linq; namespace HofstadterFigureFigure { class HofstadterFigureFigure { readonly List<int> _r = new List<int>() {1}; readonly List<int> _s = new List<int>(); public IEnumerable<int> R() { int iR = 0; while (true) { if (iR >= _r.Count) { Advance(); } yield return _r[iR++]; } } public IEnumerable<int> S() { int iS = 0; while (true) { if (iS >= _s.Count) { Advance(); } yield return _s[iS++]; } } private void Advance() { int rCount = _r.Count; int oldR = _r[rCount - 1]; int sVal; switch (rCount) { case 1: sVal = 2; break; case 2: sVal = 4; break; default: sVal = _s[rCount - 1]; break; } _r.Add(_r[rCount - 1] + sVal); int newR = _r[rCount]; for (int iS = oldR + 1; iS < newR; iS++) { _s.Add(iS); } } } class Program { static void Main() { var hff = new HofstadterFigureFigure(); var rs = hff.R(); var arr = rs.Take(40).ToList(); foreach(var v in arr.Take(10)) { Console.WriteLine("{0}", v); } var hs = new HashSet<int>(arr); hs.UnionWith(hff.S().Take(960)); Console.WriteLine(hs.Count == 1000 ? "Verified" : "Oops! Something's wrong!"); } } }
def ffr(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffr.r[n] except IndexError: r, s = ffr.r, ffs.s ffr_n_1 = ffr(n-1) lastr = r[-1] s += list(range(s[-1] + 1, lastr)) if s[-1] < lastr: s += [lastr + 1] len_s = len(s) ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1] ans = ffr_n_1 + ffs_n_1 r.append(ans) return ans ffr.r = [None, 1] def ffs(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffs.s[n] except IndexError: r, s = ffr.r, ffs.s for i in range(len(r), n+2): ffr(i) if len(s) > n: return s[n] raise Exception("Whoops!") ffs.s = [None, 2] if __name__ == '__main__': first10 = [ffr(i) for i in range(1,11)] assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], "ffr() value error(s)" print("ffr(n) for n = [1..10] is", first10) bin = [None] + [0]*1000 for i in range(40, 0, -1): bin[ffr(i)] += 1 for i in range(960, 0, -1): bin[ffs(i)] += 1 if all(b == 1 for b in bin[1:1000]): print("All Integers 1..1000 found OK") else: print("All Integers 1..1000 NOT found only once: ERROR")
Translate this program into Python but keep the logic exactly as in C#.
static int Fib(int n) { if (n < 0) throw new ArgumentException("Must be non negativ", "n"); Func<int, int> fib = null; fib = p => p > 1 ? fib(p - 2) + fib(p - 1) : p; return fib(n); }
>>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args))) >>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2))) >>> [ Y(fib)(i) for i in range(-2, 10) ] [None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
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.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; public class TuringMachine { public static async Task Main() { var fiveStateBusyBeaver = new TuringMachine("A", '0', "H").WithTransitions( ("A", '0', '1', Right, "B"), ("A", '1', '1', Left, "C"), ("B", '0', '1', Right, "C"), ("B", '1', '1', Right, "B"), ("C", '0', '1', Right, "D"), ("C", '1', '0', Left, "E"), ("D", '0', '1', Left, "A"), ("D", '1', '1', Left, "D"), ("E", '0', '1', Stay, "H"), ("E", '1', '0', Left, "A") ); var busyBeaverTask = fiveStateBusyBeaver.TimeAsync(); var incrementer = new TuringMachine("q0", 'B', "qf").WithTransitions( ("q0", '1', '1', Right, "q0"), ("q0", 'B', '1', Stay, "qf") ) .WithInput("111"); foreach (var _ in incrementer.Run()) PrintLine(incrementer); PrintResults(incrementer); var threeStateBusyBeaver = new TuringMachine("a", '0', "halt").WithTransitions( ("a", '0', '1', Right, "b"), ("a", '1', '1', Left, "c"), ("b", '0', '1', Left, "a"), ("b", '1', '1', Right, "b"), ("c", '0', '1', Left, "b"), ("c", '1', '1', Stay, "halt") ); foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver); PrintResults(threeStateBusyBeaver); var sorter = new TuringMachine("A", '*', "X").WithTransitions( ("A", 'a', 'a', Right, "A"), ("A", 'b', 'B', Right, "B"), ("A", '*', '*', Left, "E"), ("B", 'a', 'a', Right, "B"), ("B", 'b', 'b', Right, "B"), ("B", '*', '*', Left, "C"), ("C", 'a', 'b', Left, "D"), ("C", 'b', 'b', Left, "C"), ("C", 'B', 'b', Left, "E"), ("D", 'a', 'a', Left, "D"), ("D", 'b', 'b', Left, "D"), ("D", 'B', 'a', Right, "A"), ("E", 'a', 'a', Left, "E"), ("E", '*', '*', Right, "X") ) .WithInput("babbababaa"); sorter.Run().Last(); Console.WriteLine("Sorted: " + sorter.TapeString); PrintResults(sorter); sorter.Reset().WithInput("bbbababaaabba"); sorter.Run().Last(); Console.WriteLine("Sorted: " + sorter.TapeString); PrintResults(sorter); Console.WriteLine(await busyBeaverTask); PrintResults(fiveStateBusyBeaver); void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + "\tState " + tm.State); void PrintResults(TuringMachine tm) { Console.WriteLine($"End state: {tm.State} = {(tm.Success ? "Success" : "Failure")}"); Console.WriteLine(tm.Steps + " steps"); Console.WriteLine("tape length: " + tm.TapeLength); Console.WriteLine(); } } public const int Left = -1, Stay = 0, Right = 1; private readonly Tape tape; private readonly string initialState; private readonly HashSet<string> terminatingStates; private Dictionary<(string state, char read), (char write, int move, string toState)> transitions; public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) { State = this.initialState = initialState; tape = new Tape(blankSymbol); this.terminatingStates = terminatingStates.ToHashSet(); } public TuringMachine WithTransitions( params (string state, char read, char write, int move, string toState)[] transitions) { this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState)); return this; } public TuringMachine Reset() { State = initialState; Steps = 0; tape.Reset(); return this; } public TuringMachine WithInput(string input) { tape.Input(input); return this; } public int Steps { get; private set; } public string State { get; private set; } public bool Success => terminatingStates.Contains(State); public int TapeLength => tape.Length; public string TapeString => tape.ToString(); public IEnumerable<string> Run() { yield return State; while (Step()) yield return State; } public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) { var chrono = Stopwatch.StartNew(); await RunAsync(cancel); chrono.Stop(); return chrono.Elapsed; } public Task RunAsync(CancellationToken cancel = default) => Task.Run(() => { while (Step()) cancel.ThrowIfCancellationRequested(); }); private bool Step() { if (!transitions.TryGetValue((State, tape.Current), out var action)) return false; tape.Current = action.write; tape.Move(action.move); State = action.toState; Steps++; return true; } private class Tape { private List<char> forwardTape = new List<char>(), backwardTape = new List<char>(); private int head = 0; private char blank; public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol); public void Reset() { backwardTape.Clear(); forwardTape.Clear(); head = 0; forwardTape.Add(blank); } public void Input(string input) { Reset(); forwardTape.Clear(); forwardTape.AddRange(input); } public void Move(int direction) { head += direction; if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank); if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank); } public char Current { get => head < 0 ? backwardTape[~head] : forwardTape[head]; set { if (head < 0) backwardTape[~head] = value; else forwardTape[head] = value; } } public int Length => backwardTape.Count + forwardTape.Count; public override string ToString() { int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1; var builder = new StringBuilder(" ", Length * 2 + 1); if (backwardTape.Count > 0) { builder.Append(string.Join(" ", backwardTape)).Append(" "); if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')'); for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]); } builder.Append(string.Join(" ", forwardTape)).Append(" "); if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')'); return builder.ToString(); } } }
from __future__ import print_function def run_utm( state = None, blank = None, rules = [], tape = [], halt = None, pos = 0): st = state if not tape: tape = [blank] if pos < 0: pos += len(tape) if pos >= len(tape) or pos < 0: raise Error( "bad init position") rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules) while True: print(st, '\t', end=" ") for i, v in enumerate(tape): if i == pos: print("[%s]" % (v,), end=" ") else: print(v, end=" ") print() if st == halt: break if (st, tape[pos]) not in rules: break (v1, dr, s1) = rules[(st, tape[pos])] tape[pos] = v1 if dr == 'left': if pos > 0: pos -= 1 else: tape.insert(0, blank) if dr == 'right': pos += 1 if pos >= len(tape): tape.append(blank) st = s1 print("incr machine\n") run_utm( halt = 'qf', state = 'q0', tape = list("111"), blank = 'B', rules = map(tuple, ["q0 1 1 right q0".split(), "q0 B 1 stay qf".split()] ) ) print("\nbusy beaver\n") run_utm( halt = 'halt', state = 'a', blank = '0', rules = map(tuple, ["a 0 1 right b".split(), "a 1 1 left c".split(), "b 0 1 left a".split(), "b 1 1 right b".split(), "c 0 1 left b".split(), "c 1 1 stay halt".split()] ) ) print("\nsorting test\n") run_utm(halt = 'STOP', state = 'A', blank = '0', tape = "2 2 2 1 2 2 1 2 1 2 1 2 1 2".split(), rules = map(tuple, ["A 1 1 right A".split(), "A 2 3 right B".split(), "A 0 0 left E".split(), "B 1 1 right B".split(), "B 2 2 right B".split(), "B 0 0 left C".split(), "C 1 2 left D".split(), "C 2 2 left C".split(), "C 3 2 left E".split(), "D 1 1 left D".split(), "D 2 2 left D".split(), "D 3 1 right A".split(), "E 1 1 left E".split(), "E 0 0 right STOP".split()] ) )
Translate this program into Python but keep the logic exactly as in C#.
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; public class TuringMachine { public static async Task Main() { var fiveStateBusyBeaver = new TuringMachine("A", '0', "H").WithTransitions( ("A", '0', '1', Right, "B"), ("A", '1', '1', Left, "C"), ("B", '0', '1', Right, "C"), ("B", '1', '1', Right, "B"), ("C", '0', '1', Right, "D"), ("C", '1', '0', Left, "E"), ("D", '0', '1', Left, "A"), ("D", '1', '1', Left, "D"), ("E", '0', '1', Stay, "H"), ("E", '1', '0', Left, "A") ); var busyBeaverTask = fiveStateBusyBeaver.TimeAsync(); var incrementer = new TuringMachine("q0", 'B', "qf").WithTransitions( ("q0", '1', '1', Right, "q0"), ("q0", 'B', '1', Stay, "qf") ) .WithInput("111"); foreach (var _ in incrementer.Run()) PrintLine(incrementer); PrintResults(incrementer); var threeStateBusyBeaver = new TuringMachine("a", '0', "halt").WithTransitions( ("a", '0', '1', Right, "b"), ("a", '1', '1', Left, "c"), ("b", '0', '1', Left, "a"), ("b", '1', '1', Right, "b"), ("c", '0', '1', Left, "b"), ("c", '1', '1', Stay, "halt") ); foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver); PrintResults(threeStateBusyBeaver); var sorter = new TuringMachine("A", '*', "X").WithTransitions( ("A", 'a', 'a', Right, "A"), ("A", 'b', 'B', Right, "B"), ("A", '*', '*', Left, "E"), ("B", 'a', 'a', Right, "B"), ("B", 'b', 'b', Right, "B"), ("B", '*', '*', Left, "C"), ("C", 'a', 'b', Left, "D"), ("C", 'b', 'b', Left, "C"), ("C", 'B', 'b', Left, "E"), ("D", 'a', 'a', Left, "D"), ("D", 'b', 'b', Left, "D"), ("D", 'B', 'a', Right, "A"), ("E", 'a', 'a', Left, "E"), ("E", '*', '*', Right, "X") ) .WithInput("babbababaa"); sorter.Run().Last(); Console.WriteLine("Sorted: " + sorter.TapeString); PrintResults(sorter); sorter.Reset().WithInput("bbbababaaabba"); sorter.Run().Last(); Console.WriteLine("Sorted: " + sorter.TapeString); PrintResults(sorter); Console.WriteLine(await busyBeaverTask); PrintResults(fiveStateBusyBeaver); void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + "\tState " + tm.State); void PrintResults(TuringMachine tm) { Console.WriteLine($"End state: {tm.State} = {(tm.Success ? "Success" : "Failure")}"); Console.WriteLine(tm.Steps + " steps"); Console.WriteLine("tape length: " + tm.TapeLength); Console.WriteLine(); } } public const int Left = -1, Stay = 0, Right = 1; private readonly Tape tape; private readonly string initialState; private readonly HashSet<string> terminatingStates; private Dictionary<(string state, char read), (char write, int move, string toState)> transitions; public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) { State = this.initialState = initialState; tape = new Tape(blankSymbol); this.terminatingStates = terminatingStates.ToHashSet(); } public TuringMachine WithTransitions( params (string state, char read, char write, int move, string toState)[] transitions) { this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState)); return this; } public TuringMachine Reset() { State = initialState; Steps = 0; tape.Reset(); return this; } public TuringMachine WithInput(string input) { tape.Input(input); return this; } public int Steps { get; private set; } public string State { get; private set; } public bool Success => terminatingStates.Contains(State); public int TapeLength => tape.Length; public string TapeString => tape.ToString(); public IEnumerable<string> Run() { yield return State; while (Step()) yield return State; } public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) { var chrono = Stopwatch.StartNew(); await RunAsync(cancel); chrono.Stop(); return chrono.Elapsed; } public Task RunAsync(CancellationToken cancel = default) => Task.Run(() => { while (Step()) cancel.ThrowIfCancellationRequested(); }); private bool Step() { if (!transitions.TryGetValue((State, tape.Current), out var action)) return false; tape.Current = action.write; tape.Move(action.move); State = action.toState; Steps++; return true; } private class Tape { private List<char> forwardTape = new List<char>(), backwardTape = new List<char>(); private int head = 0; private char blank; public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol); public void Reset() { backwardTape.Clear(); forwardTape.Clear(); head = 0; forwardTape.Add(blank); } public void Input(string input) { Reset(); forwardTape.Clear(); forwardTape.AddRange(input); } public void Move(int direction) { head += direction; if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank); if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank); } public char Current { get => head < 0 ? backwardTape[~head] : forwardTape[head]; set { if (head < 0) backwardTape[~head] = value; else forwardTape[head] = value; } } public int Length => backwardTape.Count + forwardTape.Count; public override string ToString() { int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1; var builder = new StringBuilder(" ", Length * 2 + 1); if (backwardTape.Count > 0) { builder.Append(string.Join(" ", backwardTape)).Append(" "); if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')'); for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]); } builder.Append(string.Join(" ", forwardTape)).Append(" "); if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')'); return builder.ToString(); } } }
from __future__ import print_function def run_utm( state = None, blank = None, rules = [], tape = [], halt = None, pos = 0): st = state if not tape: tape = [blank] if pos < 0: pos += len(tape) if pos >= len(tape) or pos < 0: raise Error( "bad init position") rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules) while True: print(st, '\t', end=" ") for i, v in enumerate(tape): if i == pos: print("[%s]" % (v,), end=" ") else: print(v, end=" ") print() if st == halt: break if (st, tape[pos]) not in rules: break (v1, dr, s1) = rules[(st, tape[pos])] tape[pos] = v1 if dr == 'left': if pos > 0: pos -= 1 else: tape.insert(0, blank) if dr == 'right': pos += 1 if pos >= len(tape): tape.append(blank) st = s1 print("incr machine\n") run_utm( halt = 'qf', state = 'q0', tape = list("111"), blank = 'B', rules = map(tuple, ["q0 1 1 right q0".split(), "q0 B 1 stay qf".split()] ) ) print("\nbusy beaver\n") run_utm( halt = 'halt', state = 'a', blank = '0', rules = map(tuple, ["a 0 1 right b".split(), "a 1 1 left c".split(), "b 0 1 left a".split(), "b 1 1 right b".split(), "c 0 1 left b".split(), "c 1 1 stay halt".split()] ) ) print("\nsorting test\n") run_utm(halt = 'STOP', state = 'A', blank = '0', tape = "2 2 2 1 2 2 1 2 1 2 1 2 1 2".split(), rules = map(tuple, ["A 1 1 right A".split(), "A 2 3 right B".split(), "A 0 0 left E".split(), "B 1 1 right B".split(), "B 2 2 right B".split(), "B 0 0 left C".split(), "C 1 2 left D".split(), "C 2 2 left C".split(), "C 3 2 left E".split(), "D 1 1 left D".split(), "D 2 2 left D".split(), "D 3 1 right A".split(), "E 1 1 left E".split(), "E 0 0 right STOP".split()] ) )
Preserve the algorithm and functionality while converting the code from C# to Python.
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; public class TuringMachine { public static async Task Main() { var fiveStateBusyBeaver = new TuringMachine("A", '0', "H").WithTransitions( ("A", '0', '1', Right, "B"), ("A", '1', '1', Left, "C"), ("B", '0', '1', Right, "C"), ("B", '1', '1', Right, "B"), ("C", '0', '1', Right, "D"), ("C", '1', '0', Left, "E"), ("D", '0', '1', Left, "A"), ("D", '1', '1', Left, "D"), ("E", '0', '1', Stay, "H"), ("E", '1', '0', Left, "A") ); var busyBeaverTask = fiveStateBusyBeaver.TimeAsync(); var incrementer = new TuringMachine("q0", 'B', "qf").WithTransitions( ("q0", '1', '1', Right, "q0"), ("q0", 'B', '1', Stay, "qf") ) .WithInput("111"); foreach (var _ in incrementer.Run()) PrintLine(incrementer); PrintResults(incrementer); var threeStateBusyBeaver = new TuringMachine("a", '0', "halt").WithTransitions( ("a", '0', '1', Right, "b"), ("a", '1', '1', Left, "c"), ("b", '0', '1', Left, "a"), ("b", '1', '1', Right, "b"), ("c", '0', '1', Left, "b"), ("c", '1', '1', Stay, "halt") ); foreach (var _ in threeStateBusyBeaver.Run()) PrintLine(threeStateBusyBeaver); PrintResults(threeStateBusyBeaver); var sorter = new TuringMachine("A", '*', "X").WithTransitions( ("A", 'a', 'a', Right, "A"), ("A", 'b', 'B', Right, "B"), ("A", '*', '*', Left, "E"), ("B", 'a', 'a', Right, "B"), ("B", 'b', 'b', Right, "B"), ("B", '*', '*', Left, "C"), ("C", 'a', 'b', Left, "D"), ("C", 'b', 'b', Left, "C"), ("C", 'B', 'b', Left, "E"), ("D", 'a', 'a', Left, "D"), ("D", 'b', 'b', Left, "D"), ("D", 'B', 'a', Right, "A"), ("E", 'a', 'a', Left, "E"), ("E", '*', '*', Right, "X") ) .WithInput("babbababaa"); sorter.Run().Last(); Console.WriteLine("Sorted: " + sorter.TapeString); PrintResults(sorter); sorter.Reset().WithInput("bbbababaaabba"); sorter.Run().Last(); Console.WriteLine("Sorted: " + sorter.TapeString); PrintResults(sorter); Console.WriteLine(await busyBeaverTask); PrintResults(fiveStateBusyBeaver); void PrintLine(TuringMachine tm) => Console.WriteLine(tm.TapeString + "\tState " + tm.State); void PrintResults(TuringMachine tm) { Console.WriteLine($"End state: {tm.State} = {(tm.Success ? "Success" : "Failure")}"); Console.WriteLine(tm.Steps + " steps"); Console.WriteLine("tape length: " + tm.TapeLength); Console.WriteLine(); } } public const int Left = -1, Stay = 0, Right = 1; private readonly Tape tape; private readonly string initialState; private readonly HashSet<string> terminatingStates; private Dictionary<(string state, char read), (char write, int move, string toState)> transitions; public TuringMachine(string initialState, char blankSymbol, params string[] terminatingStates) { State = this.initialState = initialState; tape = new Tape(blankSymbol); this.terminatingStates = terminatingStates.ToHashSet(); } public TuringMachine WithTransitions( params (string state, char read, char write, int move, string toState)[] transitions) { this.transitions = transitions.ToDictionary(k => (k.state, k.read), k => (k.write, k.move, k.toState)); return this; } public TuringMachine Reset() { State = initialState; Steps = 0; tape.Reset(); return this; } public TuringMachine WithInput(string input) { tape.Input(input); return this; } public int Steps { get; private set; } public string State { get; private set; } public bool Success => terminatingStates.Contains(State); public int TapeLength => tape.Length; public string TapeString => tape.ToString(); public IEnumerable<string> Run() { yield return State; while (Step()) yield return State; } public async Task<TimeSpan> TimeAsync(CancellationToken cancel = default) { var chrono = Stopwatch.StartNew(); await RunAsync(cancel); chrono.Stop(); return chrono.Elapsed; } public Task RunAsync(CancellationToken cancel = default) => Task.Run(() => { while (Step()) cancel.ThrowIfCancellationRequested(); }); private bool Step() { if (!transitions.TryGetValue((State, tape.Current), out var action)) return false; tape.Current = action.write; tape.Move(action.move); State = action.toState; Steps++; return true; } private class Tape { private List<char> forwardTape = new List<char>(), backwardTape = new List<char>(); private int head = 0; private char blank; public Tape(char blankSymbol) => forwardTape.Add(blank = blankSymbol); public void Reset() { backwardTape.Clear(); forwardTape.Clear(); head = 0; forwardTape.Add(blank); } public void Input(string input) { Reset(); forwardTape.Clear(); forwardTape.AddRange(input); } public void Move(int direction) { head += direction; if (head >= 0 && forwardTape.Count <= head) forwardTape.Add(blank); if (head < 0 && backwardTape.Count <= ~head) backwardTape.Add(blank); } public char Current { get => head < 0 ? backwardTape[~head] : forwardTape[head]; set { if (head < 0) backwardTape[~head] = value; else forwardTape[head] = value; } } public int Length => backwardTape.Count + forwardTape.Count; public override string ToString() { int h = (head < 0 ? ~head : backwardTape.Count + head) * 2 + 1; var builder = new StringBuilder(" ", Length * 2 + 1); if (backwardTape.Count > 0) { builder.Append(string.Join(" ", backwardTape)).Append(" "); if (head < 0) (builder[h + 1], builder[h - 1]) = ('(', ')'); for (int l = 0, r = builder.Length - 1; l < r; l++, r--) (builder[l], builder[r]) = (builder[r], builder[l]); } builder.Append(string.Join(" ", forwardTape)).Append(" "); if (head >= 0) (builder[h - 1], builder[h + 1]) = ('(', ')'); return builder.ToString(); } } }
from __future__ import print_function def run_utm( state = None, blank = None, rules = [], tape = [], halt = None, pos = 0): st = state if not tape: tape = [blank] if pos < 0: pos += len(tape) if pos >= len(tape) or pos < 0: raise Error( "bad init position") rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules) while True: print(st, '\t', end=" ") for i, v in enumerate(tape): if i == pos: print("[%s]" % (v,), end=" ") else: print(v, end=" ") print() if st == halt: break if (st, tape[pos]) not in rules: break (v1, dr, s1) = rules[(st, tape[pos])] tape[pos] = v1 if dr == 'left': if pos > 0: pos -= 1 else: tape.insert(0, blank) if dr == 'right': pos += 1 if pos >= len(tape): tape.append(blank) st = s1 print("incr machine\n") run_utm( halt = 'qf', state = 'q0', tape = list("111"), blank = 'B', rules = map(tuple, ["q0 1 1 right q0".split(), "q0 B 1 stay qf".split()] ) ) print("\nbusy beaver\n") run_utm( halt = 'halt', state = 'a', blank = '0', rules = map(tuple, ["a 0 1 right b".split(), "a 1 1 left c".split(), "b 0 1 left a".split(), "b 1 1 right b".split(), "c 0 1 left b".split(), "c 1 1 stay halt".split()] ) ) print("\nsorting test\n") run_utm(halt = 'STOP', state = 'A', blank = '0', tape = "2 2 2 1 2 2 1 2 1 2 1 2 1 2".split(), rules = map(tuple, ["A 1 1 right A".split(), "A 2 3 right B".split(), "A 0 0 left E".split(), "B 1 1 right B".split(), "B 2 2 right B".split(), "B 0 0 left C".split(), "C 1 2 left D".split(), "C 2 2 left C".split(), "C 3 2 left E".split(), "D 1 1 left D".split(), "D 2 2 left D".split(), "D 3 1 right A".split(), "E 1 1 left E".split(), "E 0 0 right STOP".split()] ) )
Write the same code in Python as shown below in C#.
using System; using System.IO; class Program { static void Main(string[] args) { File.Create("output.txt"); File.Create(@"\output.txt"); Directory.CreateDirectory("docs"); Directory.CreateDirectory(@"\docs"); } }
import os for directory in ['/', './']: open(directory + 'output.txt', 'w').close() os.mkdir(directory + 'docs')
Translate the given C# code snippet into Python without altering its behavior.
using System; interface IOperable { string Operate(); } class Inoperable { } class Operable : IOperable { public string Operate() { return "Delegate implementation."; } } class Delegator : IOperable { object Delegate; public string Operate() { var operable = Delegate as IOperable; return operable != null ? operable.Operate() : "Default implementation."; } static void Main() { var delegator = new Delegator(); foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() }) { delegator.Delegate = @delegate; Console.WriteLine(delegator.Operate()); } } }
class Delegator: def __init__(self): self.delegate = None def operation(self): if hasattr(self.delegate, 'thing') and callable(self.delegate.thing): return self.delegate.thing() return 'default implementation' class Delegate: def thing(self): return 'delegate implementation' if __name__ == '__main__': a = Delegator() assert a.operation() == 'default implementation' a.delegate = 'A delegate may be any object' assert a.operation() == 'default implementation' a.delegate = Delegate() assert a.operation() == 'delegate implementation'
Generate a Python translation of this C# snippet without changing its computational steps.
readonly DateTime now = DateTime.Now;
>>> s = "Hello" >>> s[0] = "h" Traceback (most recent call last): File "<pyshell s[0] = "h" TypeError: 'str' object does not support item assignment
Change the following C# code into Python without altering its purpose.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BaconCipher { class Program { private static Dictionary<char, string> codes = new Dictionary<char, string> { {'a', "AAAAA" }, {'b', "AAAAB" }, {'c', "AAABA" }, {'d', "AAABB" }, {'e', "AABAA" }, {'f', "AABAB" }, {'g', "AABBA" }, {'h', "AABBB" }, {'i', "ABAAA" }, {'j', "ABAAB" }, {'k', "ABABA" }, {'l', "ABABB" }, {'m', "ABBAA" }, {'n', "ABBAB" }, {'o', "ABBBA" }, {'p', "ABBBB" }, {'q', "BAAAA" }, {'r', "BAAAB" }, {'s', "BAABA" }, {'t', "BAABB" }, {'u', "BABAA" }, {'v', "BABAB" }, {'w', "BABBA" }, {'x', "BABBB" }, {'y', "BBAAA" }, {'z', "BBAAB" }, {' ', "BBBAA" }, }; private static string Encode(string plainText, string message) { string pt = plainText.ToLower(); StringBuilder sb = new StringBuilder(); foreach (char c in pt) { if ('a' <= c && c <= 'z') sb.Append(codes[c]); else sb.Append(codes[' ']); } string et = sb.ToString(); string mg = message.ToLower(); sb.Length = 0; int count = 0; foreach (char c in mg) { if ('a' <= c && c <= 'z') { if (et[count] == 'A') sb.Append(c); else sb.Append((char)(c - 32)); count++; if (count == et.Length) break; } else sb.Append(c); } return sb.ToString(); } private static string Decode(string message) { StringBuilder sb = new StringBuilder(); foreach (char c in message) { if ('a' <= c && c <= 'z') sb.Append('A'); else if ('A' <= c && c <= 'Z') sb.Append('B'); } string et = sb.ToString(); sb.Length = 0; for (int i = 0; i < et.Length; i += 5) { string quintet = et.Substring(i, 5); char key = codes.Where(a => a.Value == quintet).First().Key; sb.Append(key); } return sb.ToString(); } static void Main(string[] args) { string plainText = "the quick brown fox jumps over the lazy dog"; string message = "bacon's cipher is a method of steganography created by francis bacon. " + "this task is to implement a program for encryption and decryption of " + "plaintext using the simple alphabet of the baconian cipher or some " + "other kind of representation of this alphabet (make anything signify anything). " + "the baconian alphabet may optionally be extended to encode all lower " + "case characters individually and/or adding a few punctuation characters " + "such as the space."; string cipherText = Encode(plainText, message); Console.WriteLine("Cipher text ->\n{0}", cipherText); string decodedText = Decode(cipherText); Console.WriteLine("\nHidden text ->\n{0}", decodedText); } } }
import string sometext = .lower() lc2bin = {ch: '{:05b}'.format(i) for i, ch in enumerate(string.ascii_lowercase + ' .')} bin2lc = {val: key for key, val in lc2bin.items()} phrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower() def to_5binary(msg): return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower())) def encrypt(message, text): bin5 = to_5binary(message) textlist = list(text.lower()) out = [] for capitalise in bin5: while textlist: ch = textlist.pop(0) if ch.isalpha(): if capitalise: ch = ch.upper() out.append(ch) break else: out.append(ch) else: raise Exception('ERROR: Ran out of characters in sometext') return ''.join(out) + '...' def decrypt(bacontext): binary = [] bin5 = [] out = [] for ch in bacontext: if ch.isalpha(): binary.append('1' if ch.isupper() else '0') if len(binary) == 5: bin5 = ''.join(binary) out.append(bin2lc[bin5]) binary = [] return ''.join(out) print('PLAINTEXT = \n%s\n' % phrase) encrypted = encrypt(phrase, sometext) print('ENCRYPTED = \n%s\n' % encrypted) decrypted = decrypt(encrypted) print('DECRYPTED = \n%s\n' % decrypted) assert phrase == decrypted, 'Round-tripping error'
Change the following C# code into Python without altering its purpose.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BaconCipher { class Program { private static Dictionary<char, string> codes = new Dictionary<char, string> { {'a', "AAAAA" }, {'b', "AAAAB" }, {'c', "AAABA" }, {'d', "AAABB" }, {'e', "AABAA" }, {'f', "AABAB" }, {'g', "AABBA" }, {'h', "AABBB" }, {'i', "ABAAA" }, {'j', "ABAAB" }, {'k', "ABABA" }, {'l', "ABABB" }, {'m', "ABBAA" }, {'n', "ABBAB" }, {'o', "ABBBA" }, {'p', "ABBBB" }, {'q', "BAAAA" }, {'r', "BAAAB" }, {'s', "BAABA" }, {'t', "BAABB" }, {'u', "BABAA" }, {'v', "BABAB" }, {'w', "BABBA" }, {'x', "BABBB" }, {'y', "BBAAA" }, {'z', "BBAAB" }, {' ', "BBBAA" }, }; private static string Encode(string plainText, string message) { string pt = plainText.ToLower(); StringBuilder sb = new StringBuilder(); foreach (char c in pt) { if ('a' <= c && c <= 'z') sb.Append(codes[c]); else sb.Append(codes[' ']); } string et = sb.ToString(); string mg = message.ToLower(); sb.Length = 0; int count = 0; foreach (char c in mg) { if ('a' <= c && c <= 'z') { if (et[count] == 'A') sb.Append(c); else sb.Append((char)(c - 32)); count++; if (count == et.Length) break; } else sb.Append(c); } return sb.ToString(); } private static string Decode(string message) { StringBuilder sb = new StringBuilder(); foreach (char c in message) { if ('a' <= c && c <= 'z') sb.Append('A'); else if ('A' <= c && c <= 'Z') sb.Append('B'); } string et = sb.ToString(); sb.Length = 0; for (int i = 0; i < et.Length; i += 5) { string quintet = et.Substring(i, 5); char key = codes.Where(a => a.Value == quintet).First().Key; sb.Append(key); } return sb.ToString(); } static void Main(string[] args) { string plainText = "the quick brown fox jumps over the lazy dog"; string message = "bacon's cipher is a method of steganography created by francis bacon. " + "this task is to implement a program for encryption and decryption of " + "plaintext using the simple alphabet of the baconian cipher or some " + "other kind of representation of this alphabet (make anything signify anything). " + "the baconian alphabet may optionally be extended to encode all lower " + "case characters individually and/or adding a few punctuation characters " + "such as the space."; string cipherText = Encode(plainText, message); Console.WriteLine("Cipher text ->\n{0}", cipherText); string decodedText = Decode(cipherText); Console.WriteLine("\nHidden text ->\n{0}", decodedText); } } }
import string sometext = .lower() lc2bin = {ch: '{:05b}'.format(i) for i, ch in enumerate(string.ascii_lowercase + ' .')} bin2lc = {val: key for key, val in lc2bin.items()} phrase = 'Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan'.lower() def to_5binary(msg): return ( ch == '1' for ch in ''.join(lc2bin.get(ch, '') for ch in msg.lower())) def encrypt(message, text): bin5 = to_5binary(message) textlist = list(text.lower()) out = [] for capitalise in bin5: while textlist: ch = textlist.pop(0) if ch.isalpha(): if capitalise: ch = ch.upper() out.append(ch) break else: out.append(ch) else: raise Exception('ERROR: Ran out of characters in sometext') return ''.join(out) + '...' def decrypt(bacontext): binary = [] bin5 = [] out = [] for ch in bacontext: if ch.isalpha(): binary.append('1' if ch.isupper() else '0') if len(binary) == 5: bin5 = ''.join(binary) out.append(bin2lc[bin5]) binary = [] return ''.join(out) print('PLAINTEXT = \n%s\n' % phrase) encrypted = encrypt(phrase, sometext) print('ENCRYPTED = \n%s\n' % encrypted) decrypted = decrypt(encrypted) print('DECRYPTED = \n%s\n' % decrypted) assert phrase == decrypted, 'Round-tripping error'
Convert this C# snippet to Python and keep its semantics consistent.
public int[,] Spiral(int n) { int[,] result = new int[n, n]; int pos = 0; int count = n; int value = -n; int sum = -1; do { value = -1 * value / n; for (int i = 0; i < count; i++) { sum += value; result[sum / n, sum % n] = pos++; } value *= n; count--; for (int i = 0; i < count; i++) { sum += value; result[sum / n, sum % n] = pos++; } } while (count > 0); return result; } public void PrintArray(int[,] array) { int n = (array.GetLength(0) * array.GetLength(1) - 1).ToString().Length + 1; for (int i = 0; i < array.GetLength(0); i++) { for (int j = 0; j < array.GetLength(1); j++) { Console.Write(array[i, j].ToString().PadLeft(n, ' ')); } Console.WriteLine(); } }
def spiral(n): dx,dy = 1,0 x,y = 0,0 myarray = [[None]* n for j in range(n)] for i in xrange(n**2): myarray[x][y] = i nx,ny = x+dx, y+dy if 0<=nx<n and 0<=ny<n and myarray[nx][ny] == None: x,y = nx,ny else: dx,dy = -dy,dx x,y = x+dx, y+dy return myarray def printspiral(myarray): n = range(len(myarray)) for y in n: for x in n: print "%2i" % myarray[x][y], print printspiral(spiral(5))
Rewrite the snippet below in Python so it works the same as the original C# code.
using System; namespace FaulhabersTriangle { internal class Frac { private long num; private long denom; public static readonly Frac ZERO = new Frac(0, 1); public static readonly Frac ONE = new Frac(1, 1); public Frac(long n, long d) { if (d == 0) { throw new ArgumentException("d must not be zero"); } long nn = n; long dd = d; if (nn == 0) { dd = 1; } else if (dd < 0) { nn = -nn; dd = -dd; } long g = Math.Abs(Gcd(nn, dd)); if (g > 1) { nn /= g; dd /= g; } num = nn; denom = dd; } private static long Gcd(long a, long b) { if (b == 0) { return a; } return Gcd(b, a % b); } public static Frac operator -(Frac self) { return new Frac(-self.num, self.denom); } public static Frac operator +(Frac lhs, Frac rhs) { return new Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom); } public static Frac operator -(Frac lhs, Frac rhs) { return lhs + -rhs; } public static Frac operator *(Frac lhs, Frac rhs) { return new Frac(lhs.num * rhs.num, lhs.denom * rhs.denom); } public static bool operator <(Frac lhs, Frac rhs) { double x = (double)lhs.num / lhs.denom; double y = (double)rhs.num / rhs.denom; return x < y; } public static bool operator >(Frac lhs, Frac rhs) { double x = (double)lhs.num / lhs.denom; double y = (double)rhs.num / rhs.denom; return x > y; } public static bool operator ==(Frac lhs, Frac rhs) { return lhs.num == rhs.num && lhs.denom == rhs.denom; } public static bool operator !=(Frac lhs, Frac rhs) { return lhs.num != rhs.num || lhs.denom != rhs.denom; } public override string ToString() { if (denom == 1) { return num.ToString(); } return string.Format("{0}/{1}", num, denom); } public override bool Equals(object obj) { var frac = obj as Frac; return frac != null && num == frac.num && denom == frac.denom; } public override int GetHashCode() { var hashCode = 1317992671; hashCode = hashCode * -1521134295 + num.GetHashCode(); hashCode = hashCode * -1521134295 + denom.GetHashCode(); return hashCode; } } class Program { static Frac Bernoulli(int n) { if (n < 0) { throw new ArgumentException("n may not be negative or zero"); } Frac[] a = new Frac[n + 1]; for (int m = 0; m <= n; m++) { a[m] = new Frac(1, m + 1); for (int j = m; j >= 1; j--) { a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1); } } if (n != 1) return a[0]; return -a[0]; } static int Binomial(int n, int k) { if (n < 0 || k < 0 || n < k) { throw new ArgumentException(); } if (n == 0 || k == 0) return 1; int num = 1; for (int i = k + 1; i <= n; i++) { num = num * i; } int denom = 1; for (int i = 2; i <= n - k; i++) { denom = denom * i; } return num / denom; } static Frac[] FaulhaberTriangle(int p) { Frac[] coeffs = new Frac[p + 1]; for (int i = 0; i < p + 1; i++) { coeffs[i] = Frac.ZERO; } Frac q = new Frac(1, p + 1); int sign = -1; for (int j = 0; j <= p; j++) { sign *= -1; coeffs[p - j] = q * new Frac(sign, 1) * new Frac(Binomial(p + 1, j), 1) * Bernoulli(j); } return coeffs; } static void Main(string[] args) { for (int i = 0; i < 10; i++) { Frac[] coeffs = FaulhaberTriangle(i); foreach (Frac coeff in coeffs) { Console.Write("{0,5} ", coeff); } Console.WriteLine(); } } } }
from itertools import accumulate, chain, count, islice from fractions import Fraction def faulhaberTriangle(m): def go(rs, n): def f(x, y): return Fraction(n, x) * y xs = list(map(f, islice(count(2), m), rs)) return [Fraction(1 - sum(xs), 1)] + xs return list(accumulate( [[]] + list(islice(count(0), 1 + m)), go ))[1:] def faulhaberSum(p, n): def go(x, y): return y * (n ** x) return sum( map(go, count(1), faulhaberTriangle(p)[-1]) ) def main(): fs = faulhaberTriangle(9) print( fTable(__doc__ + ':\n')(str)( compose(concat)( fmap(showRatio(3)(3)) ) )( index(fs) )(range(0, len(fs))) ) print('') print( faulhaberSum(17, 1000) ) def fTable(s): def gox(xShow): def gofx(fxShow): def gof(f): def goxs(xs): ys = [xShow(x) for x in xs] w = max(map(len, ys)) def arrowed(x, y): return y.rjust(w, ' ') + ' -> ' + ( fxShow(f(x)) ) return s + '\n' + '\n'.join( map(arrowed, xs, ys) ) return goxs return gof return gofx return gox def compose(g): return lambda f: lambda x: g(f(x)) def concat(xs): def f(ys): zs = list(chain(*ys)) return ''.join(zs) if isinstance(ys[0], str) else zs return ( f(xs) if isinstance(xs, list) else ( chain.from_iterable(xs) ) ) if xs else [] def fmap(f): def go(xs): return list(map(f, xs)) return go def index(xs): return lambda n: None if 0 > n else ( xs[n] if ( hasattr(xs, "__getitem__") ) else next(islice(xs, n, None)) ) def showRatio(m): def go(n): def f(r): d = r.denominator return str(r.numerator).rjust(m, ' ') + ( ('/' + str(d).ljust(n, ' ')) if 1 != d else ( ' ' * (1 + n) ) ) return f return go if __name__ == '__main__': main()
Generate an equivalent Python version of this C# code.
using System; namespace FaulhabersTriangle { internal class Frac { private long num; private long denom; public static readonly Frac ZERO = new Frac(0, 1); public static readonly Frac ONE = new Frac(1, 1); public Frac(long n, long d) { if (d == 0) { throw new ArgumentException("d must not be zero"); } long nn = n; long dd = d; if (nn == 0) { dd = 1; } else if (dd < 0) { nn = -nn; dd = -dd; } long g = Math.Abs(Gcd(nn, dd)); if (g > 1) { nn /= g; dd /= g; } num = nn; denom = dd; } private static long Gcd(long a, long b) { if (b == 0) { return a; } return Gcd(b, a % b); } public static Frac operator -(Frac self) { return new Frac(-self.num, self.denom); } public static Frac operator +(Frac lhs, Frac rhs) { return new Frac(lhs.num * rhs.denom + lhs.denom * rhs.num, rhs.denom * lhs.denom); } public static Frac operator -(Frac lhs, Frac rhs) { return lhs + -rhs; } public static Frac operator *(Frac lhs, Frac rhs) { return new Frac(lhs.num * rhs.num, lhs.denom * rhs.denom); } public static bool operator <(Frac lhs, Frac rhs) { double x = (double)lhs.num / lhs.denom; double y = (double)rhs.num / rhs.denom; return x < y; } public static bool operator >(Frac lhs, Frac rhs) { double x = (double)lhs.num / lhs.denom; double y = (double)rhs.num / rhs.denom; return x > y; } public static bool operator ==(Frac lhs, Frac rhs) { return lhs.num == rhs.num && lhs.denom == rhs.denom; } public static bool operator !=(Frac lhs, Frac rhs) { return lhs.num != rhs.num || lhs.denom != rhs.denom; } public override string ToString() { if (denom == 1) { return num.ToString(); } return string.Format("{0}/{1}", num, denom); } public override bool Equals(object obj) { var frac = obj as Frac; return frac != null && num == frac.num && denom == frac.denom; } public override int GetHashCode() { var hashCode = 1317992671; hashCode = hashCode * -1521134295 + num.GetHashCode(); hashCode = hashCode * -1521134295 + denom.GetHashCode(); return hashCode; } } class Program { static Frac Bernoulli(int n) { if (n < 0) { throw new ArgumentException("n may not be negative or zero"); } Frac[] a = new Frac[n + 1]; for (int m = 0; m <= n; m++) { a[m] = new Frac(1, m + 1); for (int j = m; j >= 1; j--) { a[j - 1] = (a[j - 1] - a[j]) * new Frac(j, 1); } } if (n != 1) return a[0]; return -a[0]; } static int Binomial(int n, int k) { if (n < 0 || k < 0 || n < k) { throw new ArgumentException(); } if (n == 0 || k == 0) return 1; int num = 1; for (int i = k + 1; i <= n; i++) { num = num * i; } int denom = 1; for (int i = 2; i <= n - k; i++) { denom = denom * i; } return num / denom; } static Frac[] FaulhaberTriangle(int p) { Frac[] coeffs = new Frac[p + 1]; for (int i = 0; i < p + 1; i++) { coeffs[i] = Frac.ZERO; } Frac q = new Frac(1, p + 1); int sign = -1; for (int j = 0; j <= p; j++) { sign *= -1; coeffs[p - j] = q * new Frac(sign, 1) * new Frac(Binomial(p + 1, j), 1) * Bernoulli(j); } return coeffs; } static void Main(string[] args) { for (int i = 0; i < 10; i++) { Frac[] coeffs = FaulhaberTriangle(i); foreach (Frac coeff in coeffs) { Console.Write("{0,5} ", coeff); } Console.WriteLine(); } } } }
from itertools import accumulate, chain, count, islice from fractions import Fraction def faulhaberTriangle(m): def go(rs, n): def f(x, y): return Fraction(n, x) * y xs = list(map(f, islice(count(2), m), rs)) return [Fraction(1 - sum(xs), 1)] + xs return list(accumulate( [[]] + list(islice(count(0), 1 + m)), go ))[1:] def faulhaberSum(p, n): def go(x, y): return y * (n ** x) return sum( map(go, count(1), faulhaberTriangle(p)[-1]) ) def main(): fs = faulhaberTriangle(9) print( fTable(__doc__ + ':\n')(str)( compose(concat)( fmap(showRatio(3)(3)) ) )( index(fs) )(range(0, len(fs))) ) print('') print( faulhaberSum(17, 1000) ) def fTable(s): def gox(xShow): def gofx(fxShow): def gof(f): def goxs(xs): ys = [xShow(x) for x in xs] w = max(map(len, ys)) def arrowed(x, y): return y.rjust(w, ' ') + ' -> ' + ( fxShow(f(x)) ) return s + '\n' + '\n'.join( map(arrowed, xs, ys) ) return goxs return gof return gofx return gox def compose(g): return lambda f: lambda x: g(f(x)) def concat(xs): def f(ys): zs = list(chain(*ys)) return ''.join(zs) if isinstance(ys[0], str) else zs return ( f(xs) if isinstance(xs, list) else ( chain.from_iterable(xs) ) ) if xs else [] def fmap(f): def go(xs): return list(map(f, xs)) return go def index(xs): return lambda n: None if 0 > n else ( xs[n] if ( hasattr(xs, "__getitem__") ) else next(islice(xs, n, None)) ) def showRatio(m): def go(n): def f(r): d = r.denominator return str(r.numerator).rjust(m, ' ') + ( ('/' + str(d).ljust(n, ' ')) if 1 != d else ( ' ' * (1 + n) ) ) return f return go if __name__ == '__main__': main()
Rewrite the snippet below in Python so it works the same as the original C# code.
using System; namespace RosettaCode { class Program { static void Main(string[] args) { for (int i = 0; i < args.Length; i++) Console.WriteLine(String.Format("Argument {0} is '{1}'", i, args[i])); } } }
import sys program_name = sys.argv[0] arguments = sys.argv[1:] count = len(arguments)
Translate this program into Python but keep the logic exactly as in C#.
using System; namespace RosettaCode { class Program { static void Main(string[] args) { for (int i = 0; i < args.Length; i++) Console.WriteLine(String.Format("Argument {0} is '{1}'", i, args[i])); } } }
import sys program_name = sys.argv[0] arguments = sys.argv[1:] count = len(arguments)
Keep all operations the same but rewrite the snippet in Python.
using System; namespace RosettaCode { class Program { static void Main(string[] args) { int[] a = { 1, 2, 3 }; int[] b = { 4, 5, 6 }; int[] c = new int[a.Length + b.Length]; a.CopyTo(c, 0); b.CopyTo(c, a.Length); foreach(int n in c) { Console.WriteLine(n.ToString()); } } } }
arr1 = [1, 2, 3] arr2 = [4, 5, 6] arr3 = [7, 8, 9] arr4 = arr1 + arr2 assert arr4 == [1, 2, 3, 4, 5, 6] arr4.extend(arr3) assert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]
Rewrite this program in Python while keeping its functionality equivalent to the C# version.
using System; namespace RosettaCode { class Program { static void Main(string[] args) { int[] a = { 1, 2, 3 }; int[] b = { 4, 5, 6 }; int[] c = new int[a.Length + b.Length]; a.CopyTo(c, 0); b.CopyTo(c, a.Length); foreach(int n in c) { Console.WriteLine(n.ToString()); } } } }
arr1 = [1, 2, 3] arr2 = [4, 5, 6] arr3 = [7, 8, 9] arr4 = arr1 + arr2 assert arr4 == [1, 2, 3, 4, 5, 6] arr4.extend(arr3) assert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]
Preserve the algorithm and functionality while converting the code from C# to Python.
using System; namespace C_Sharp_Console { class example { static void Main() { string word; int num; Console.Write("Enter an integer: "); num = Console.Read(); Console.Write("Enter a String: "); word = Console.ReadLine(); } } }
string = raw_input("Input a string: ")
Rewrite the snippet below in Python so it works the same as the original C# code.
using System; using System.Collections.Generic; namespace Tests_With_Framework_4 { class Bag : IEnumerable<Bag.Item> { List<Item> items; const int MaxWeightAllowed = 400; public Bag() { items = new List<Item>(); } void AddItem(Item i) { if ((TotalWeight + i.Weight) <= MaxWeightAllowed) items.Add(i); } public void Calculate(List<Item> items) { foreach (Item i in Sorte(items)) { AddItem(i); } } List<Item> Sorte(List<Item> inputItems) { List<Item> choosenItems = new List<Item>(); for (int i = 0; i < inputItems.Count; i++) { int j = -1; if (i == 0) { choosenItems.Add(inputItems[i]); } if (i > 0) { if (!RecursiveF(inputItems, choosenItems, i, choosenItems.Count - 1, false, ref j)) { choosenItems.Add(inputItems[i]); } } } return choosenItems; } bool RecursiveF(List<Item> knapsackItems, List<Item> choosenItems, int i, int lastBound, bool dec, ref int indxToAdd) { if (!(lastBound < 0)) { if ( knapsackItems[i].ResultWV < choosenItems[lastBound].ResultWV ) { indxToAdd = lastBound; } return RecursiveF(knapsackItems, choosenItems, i, lastBound - 1, true, ref indxToAdd); } if (indxToAdd > -1) { choosenItems.Insert(indxToAdd, knapsackItems[i]); return true; } return false; } #region IEnumerable<Item> Members IEnumerator<Item> IEnumerable<Item>.GetEnumerator() { foreach (Item i in items) yield return i; } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return items.GetEnumerator(); } #endregion public int TotalWeight { get { var sum = 0; foreach (Item i in this) { sum += i.Weight; } return sum; } } public class Item { public string Name { get; set; } public int Weight { get; set; } public int Value { get; set; } public int ResultWV { get { return Weight-Value; } } public override string ToString() { return "Name : " + Name + " Wieght : " + Weight + " Value : " + Value + " ResultWV : " + ResultWV; } } } class Program { static void Main(string[] args) {List<Bag.Item> knapsackItems = new List<Bag.Item>(); knapsackItems.Add(new Bag.Item() { Name = "Map", Weight = 9, Value = 150 }); knapsackItems.Add(new Bag.Item() { Name = "Water", Weight = 153, Value = 200 }); knapsackItems.Add(new Bag.Item() { Name = "Compass", Weight = 13, Value = 35 }); knapsackItems.Add(new Bag.Item() { Name = "Sandwitch", Weight = 50, Value = 160 }); knapsackItems.Add(new Bag.Item() { Name = "Glucose", Weight = 15, Value = 60 }); knapsackItems.Add(new Bag.Item() { Name = "Tin", Weight = 68, Value = 45 }); knapsackItems.Add(new Bag.Item() { Name = "Banana", Weight = 27, Value = 60 }); knapsackItems.Add(new Bag.Item() { Name = "Apple", Weight = 39, Value = 40 }); knapsackItems.Add(new Bag.Item() { Name = "Cheese", Weight = 23, Value = 30 }); knapsackItems.Add(new Bag.Item() { Name = "Beer", Weight = 52, Value = 10 }); knapsackItems.Add(new Bag.Item() { Name = "Suntan Cream", Weight = 11, Value = 70 }); knapsackItems.Add(new Bag.Item() { Name = "Camera", Weight = 32, Value = 30 }); knapsackItems.Add(new Bag.Item() { Name = "T-shirt", Weight = 24, Value = 15 }); knapsackItems.Add(new Bag.Item() { Name = "Trousers", Weight = 48, Value = 10 }); knapsackItems.Add(new Bag.Item() { Name = "Umbrella", Weight = 73, Value = 40 }); knapsackItems.Add(new Bag.Item() { Name = "WaterProof Trousers", Weight = 42, Value = 70 }); knapsackItems.Add(new Bag.Item() { Name = "Note-Case", Weight = 22, Value = 80 }); knapsackItems.Add(new Bag.Item() { Name = "Sunglasses", Weight = 7, Value = 20 }); knapsackItems.Add(new Bag.Item() { Name = "Towel", Weight = 18, Value = 12 }); knapsackItems.Add(new Bag.Item() { Name = "Socks", Weight = 4, Value = 50 }); knapsackItems.Add(new Bag.Item() { Name = "Book", Weight = 30, Value = 10 }); knapsackItems.Add(new Bag.Item() { Name = "waterproof overclothes ", Weight = 43, Value = 75 }); Bag b = new Bag(); b.Calculate(knapsackItems); b.All(x => { Console.WriteLine(x); return true; }); Console.WriteLine(b.Sum(x => x.Weight)); Console.ReadKey(); } } }
from itertools import combinations def anycomb(items): ' return combinations of any length from the items ' return ( comb for r in range(1, len(items)+1) for comb in combinations(items, r) ) def totalvalue(comb): ' Totalise a particular combination of items' totwt = totval = 0 for item, wt, val in comb: totwt += wt totval += val return (totval, -totwt) if totwt <= 400 else (0, 0) items = ( ("map", 9, 150), ("compass", 13, 35), ("water", 153, 200), ("sandwich", 50, 160), ("glucose", 15, 60), ("tin", 68, 45), ("banana", 27, 60), ("apple", 39, 40), ("cheese", 23, 30), ("beer", 52, 10), ("suntan cream", 11, 70), ("camera", 32, 30), ("t-shirt", 24, 15), ("trousers", 48, 10), ("umbrella", 73, 40), ("waterproof trousers", 42, 70), ("waterproof overclothes", 43, 75), ("note-case", 22, 80), ("sunglasses", 7, 20), ("towel", 18, 12), ("socks", 4, 50), ("book", 30, 10), ) bagged = max( anycomb(items), key=totalvalue) print("Bagged the following items\n " + '\n '.join(sorted(item for item,_,_ in bagged))) val, wt = totalvalue(bagged) print("for a total value of %i and a total weight of %i" % (val, -wt))
Change the programming language of this snippet from C# to Python without modifying what it does.
using System; public class Program { public static void Main() { int[] empty = new int[0]; int[] list1 = { 1, 2 }; int[] list2 = { 3, 4 }; int[] list3 = { 1776, 1789 }; int[] list4 = { 7, 12 }; int[] list5 = { 4, 14, 23 }; int[] list6 = { 0, 1 }; int[] list7 = { 1, 2, 3 }; int[] list8 = { 30 }; int[] list9 = { 500, 100 }; foreach (var sequenceList in new [] { new [] { list1, list2 }, new [] { list2, list1 }, new [] { list1, empty }, new [] { empty, list1 }, new [] { list3, list4, list5, list6 }, new [] { list7, list8, list9 }, new [] { list7, empty, list9 } }) { var cart = sequenceList.CartesianProduct() .Select(tuple => $"({string.Join(", ", tuple)})"); Console.WriteLine($"{{{string.Join(", ", cart)}}}"); } } } public static class Extensions { public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) { IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; return sequences.Aggregate( emptyProduct, (accumulator, sequence) => from acc in accumulator from item in sequence select acc.Concat(new [] { item })); } }
import itertools def cp(lsts): return list(itertools.product(*lsts)) if __name__ == '__main__': from pprint import pprint as pp for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []], ((1776, 1789), (7, 12), (4, 14, 23), (0, 1)), ((1, 2, 3), (30,), (500, 100)), ((1, 2, 3), (), (500, 100))]: print(lists, '=>') pp(cp(lists), indent=2)
Port the provided C# code into Python while preserving the original functionality.
using System; public class Program { public static void Main() { int[] empty = new int[0]; int[] list1 = { 1, 2 }; int[] list2 = { 3, 4 }; int[] list3 = { 1776, 1789 }; int[] list4 = { 7, 12 }; int[] list5 = { 4, 14, 23 }; int[] list6 = { 0, 1 }; int[] list7 = { 1, 2, 3 }; int[] list8 = { 30 }; int[] list9 = { 500, 100 }; foreach (var sequenceList in new [] { new [] { list1, list2 }, new [] { list2, list1 }, new [] { list1, empty }, new [] { empty, list1 }, new [] { list3, list4, list5, list6 }, new [] { list7, list8, list9 }, new [] { list7, empty, list9 } }) { var cart = sequenceList.CartesianProduct() .Select(tuple => $"({string.Join(", ", tuple)})"); Console.WriteLine($"{{{string.Join(", ", cart)}}}"); } } } public static class Extensions { public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) { IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; return sequences.Aggregate( emptyProduct, (accumulator, sequence) => from acc in accumulator from item in sequence select acc.Concat(new [] { item })); } }
import itertools def cp(lsts): return list(itertools.product(*lsts)) if __name__ == '__main__': from pprint import pprint as pp for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []], ((1776, 1789), (7, 12), (4, 14, 23), (0, 1)), ((1, 2, 3), (30,), (500, 100)), ((1, 2, 3), (), (500, 100))]: print(lists, '=>') pp(cp(lists), indent=2)
Translate the given C# code snippet into Python without altering its behavior.
using System; public class Program { public static void Main() { int[] empty = new int[0]; int[] list1 = { 1, 2 }; int[] list2 = { 3, 4 }; int[] list3 = { 1776, 1789 }; int[] list4 = { 7, 12 }; int[] list5 = { 4, 14, 23 }; int[] list6 = { 0, 1 }; int[] list7 = { 1, 2, 3 }; int[] list8 = { 30 }; int[] list9 = { 500, 100 }; foreach (var sequenceList in new [] { new [] { list1, list2 }, new [] { list2, list1 }, new [] { list1, empty }, new [] { empty, list1 }, new [] { list3, list4, list5, list6 }, new [] { list7, list8, list9 }, new [] { list7, empty, list9 } }) { var cart = sequenceList.CartesianProduct() .Select(tuple => $"({string.Join(", ", tuple)})"); Console.WriteLine($"{{{string.Join(", ", cart)}}}"); } } } public static class Extensions { public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) { IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; return sequences.Aggregate( emptyProduct, (accumulator, sequence) => from acc in accumulator from item in sequence select acc.Concat(new [] { item })); } }
import itertools def cp(lsts): return list(itertools.product(*lsts)) if __name__ == '__main__': from pprint import pprint as pp for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []], ((1776, 1789), (7, 12), (4, 14, 23), (0, 1)), ((1, 2, 3), (30,), (500, 100)), ((1, 2, 3), (), (500, 100))]: print(lists, '=>') pp(cp(lists), indent=2)
Generate a Python translation of this C# snippet without changing its computational steps.
using System; class Program { static void Main(string[] args) { var cube = new Func<double, double>(x => Math.Pow(x, 3.0)); var croot = new Func<double, double>(x => Math.Pow(x, 1 / 3.0)); var functionTuples = new[] { (forward: Math.Sin, backward: Math.Asin), (forward: Math.Cos, backward: Math.Acos), (forward: cube, backward: croot) }; foreach (var ft in functionTuples) { Console.WriteLine(ft.backward(ft.forward(0.5))); } } }
>>> >>> from math import sin, cos, acos, asin >>> >>> cube = lambda x: x * x * x >>> croot = lambda x: x ** (1/3.0) >>> >>> >>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) ) >>> >>> funclist = [sin, cos, cube] >>> funclisti = [asin, acos, croot] >>> >>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)] [0.5, 0.4999999999999999, 0.5] >>>
Port the following code from C# to Python with equivalent syntax and logic.
namespace RosettaCode.ProperDivisors { using System; using System.Collections.Generic; using System.Linq; internal static class Program { private static IEnumerable<int> ProperDivisors(int number) { return Enumerable.Range(1, number / 2) .Where(divisor => number % divisor == 0); } private static void Main() { foreach (var number in Enumerable.Range(1, 10)) { Console.WriteLine("{0}: {{{1}}}", number, string.Join(", ", ProperDivisors(number))); } var record = Enumerable.Range(1, 20000).Select(number => new { Number = number, Count = ProperDivisors(number).Count() }).OrderByDescending(currentRecord => currentRecord.Count).First(); Console.WriteLine("{0}: {1}", record.Number, record.Count); } } }
>>> def proper_divs2(n): ... return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x} ... >>> [proper_divs2(n) for n in range(1, 11)] [set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}] >>> >>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1]) >>> n 15120 >>> length 79 >>>
Change the programming language of this snippet from C# to Python without modifying what it does.
namespace RosettaCode.ProperDivisors { using System; using System.Collections.Generic; using System.Linq; internal static class Program { private static IEnumerable<int> ProperDivisors(int number) { return Enumerable.Range(1, number / 2) .Where(divisor => number % divisor == 0); } private static void Main() { foreach (var number in Enumerable.Range(1, 10)) { Console.WriteLine("{0}: {{{1}}}", number, string.Join(", ", ProperDivisors(number))); } var record = Enumerable.Range(1, 20000).Select(number => new { Number = number, Count = ProperDivisors(number).Count() }).OrderByDescending(currentRecord => currentRecord.Count).First(); Console.WriteLine("{0}: {1}", record.Number, record.Count); } } }
>>> def proper_divs2(n): ... return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x} ... >>> [proper_divs2(n) for n in range(1, 11)] [set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}] >>> >>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1]) >>> n 15120 >>> length 79 >>>
Convert this C# block to Python, preserving its control flow and logic.
using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; class Program { static string CreateXML(Dictionary<string, string> characterRemarks) { var remarks = characterRemarks.Select(r => new XElement("Character", r.Value, new XAttribute("Name", r.Key))); var xml = new XElement("CharacterRemarks", remarks); return xml.ToString(); } static void Main(string[] args) { var characterRemarks = new Dictionary<string, string> { { "April", "Bubbly: I'm > Tam and <= Emily" }, { "Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\"" }, { "Emily", "Short & shrift" } }; string xml = CreateXML(characterRemarks); Console.WriteLine(xml); } }
>>> from xml.etree import ElementTree as ET >>> from itertools import izip >>> def characterstoxml(names, remarks): root = ET.Element("CharacterRemarks") for name, remark in izip(names, remarks): c = ET.SubElement(root, "Character", {'name': name}) c.text = remark return ET.tostring(root) >>> print characterstoxml( names = ["April", "Tam O'Shanter", "Emily"], remarks = [ "Bubbly: I'm > Tam and <= Emily", 'Burns: "When chapman billies leave the street ..."', 'Short & shrift' ] ).replace('><','>\n<')
Produce a functionally identical Python code for the snippet given in C#.
using System; using System.Text.RegularExpressions; class Program { static void Main(string[] args) { string str = "I am a string"; if (new Regex("string$").IsMatch(str)) { Console.WriteLine("Ends with string."); } str = new Regex(" a ").Replace(str, " another "); Console.WriteLine(str); } }
import re string = "This is a string" if re.search('string$', string): print("Ends with string.") string = re.sub(" a ", " another ", string) print(string)
Generate an equivalent Python version of this C# code.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ConsoleApplication1 { class RealisticGuess { private int max; private int min; private int guess; public void Start() { Console.Clear(); string input; try { Console.WriteLine("Please enter the lower boundary"); input = Console.ReadLine(); min = Convert.ToInt32(input); Console.WriteLine("Please enter the upper boundary"); input = Console.ReadLine(); max = Convert.ToInt32(input); } catch (FormatException) { Console.WriteLine("The entry you have made is invalid. Please make sure your entry is an integer and try again."); Console.ReadKey(true); Start(); } Console.WriteLine("Think of a number between {0} and {1}.", min, max); Thread.Sleep(2500); Console.WriteLine("Ready?"); Console.WriteLine("Press any key to begin."); Console.ReadKey(true); Guess(min, max); } public void Guess(int min, int max) { int counter = 1; string userAnswer; bool correct = false; Random rand = new Random(); while (correct == false) { guess = rand.Next(min, max); Console.Clear(); Console.WriteLine("{0}", guess); Console.WriteLine("Is this number correct? {Y/N}"); userAnswer = Console.ReadLine(); if (userAnswer != "y" && userAnswer != "Y" && userAnswer != "n" && userAnswer != "N") { Console.WriteLine("Your entry is invalid. Please enter either 'Y' or 'N'"); Console.WriteLine("Is the number correct? {Y/N}"); userAnswer = Console.ReadLine(); } if (userAnswer == "y" || userAnswer == "Y") { correct = true; } if (userAnswer == "n" || userAnswer == "N") { counter++; if (max == min) { Console.WriteLine("Error: Range Intersect. Press enter to restart the game."); Console.ReadKey(true); Guess(1, 101); } Console.WriteLine("Is the number you're thinking of lower or higher? {L/H}"); userAnswer = Console.ReadLine(); if (userAnswer != "l" && userAnswer != "L" && userAnswer != "h" && userAnswer != "H") { Console.WriteLine("Your entry is invalid. Please enter either 'L' or 'H'"); Console.WriteLine("Is the number you're thinking of lower or higher? {L/H}"); userAnswer = Console.ReadLine(); } if (userAnswer == "l" || userAnswer == "L") { max = guess; } if (userAnswer == "h" || userAnswer == "H") { min = guess; } } } if (correct == true) { EndAndLoop(counter); } } public void EndAndLoop(int iterations) { string userChoice; bool loop = false; Console.WriteLine("Game over. It took {0} guesses to find the number.", iterations); while (loop == false) { Console.WriteLine("Would you like to play again? {Y/N}"); userChoice = Console.ReadLine(); if (userChoice != "Y" && userChoice != "y" && userChoice != "N" && userChoice != "n") { Console.WriteLine("Sorry, your input is invalid. Please answer 'Y' to play again, or 'N' to quit."); } if (userChoice == "Y" || userChoice == "y") { Start(); } if (userChoice == "N" || userChoice == "n") { Environment.Exit(1); } } } } class Program { static void Main(string[] args) { Console.Title = "Random Number"; RealisticGuess game = new RealisticGuess(); game.Start(); } } }
inclusive_range = mn, mx = (1, 10) print( % inclusive_range) i = 0 while True: i += 1 guess = (mn+mx)//2 txt = input("Guess %2i is: %2i. The score for which is (h,l,=): " % (i, guess)).strip().lower()[0] if txt not in 'hl=': print(" I don't understand your input of '%s' ?" % txt) continue if txt == 'h': mx = guess-1 if txt == 'l': mn = guess+1 if txt == '=': print(" Ye-Haw!!") break if (mn > mx) or (mn < inclusive_range[0]) or (mx > inclusive_range[1]): print("Please check your scoring as I cannot find the value") break print("\nThanks for keeping score.")
Convert the following code from C# to Python, ensuring the logic remains intact.
static class Program { static void Main() { System.Collections.Hashtable h = new System.Collections.Hashtable(); string[] keys = { "foo", "bar", "val" }; string[] values = { "little", "miss", "muffet" }; System.Diagnostics.Trace.Assert(keys.Length == values.Length, "Arrays are not same length."); for (int i = 0; i < keys.Length; i++) { h.Add(keys[i], values[i]); } } }
keys = ['a', 'b', 'c'] values = [1, 2, 3] hash = {key: value for key, value in zip(keys, values)}
Port the following code from C# to Python with equivalent syntax and logic.
using System; public class Program { static void Main() { PrintBins(new [] { 23, 37, 43, 53, 67, 83 }, 95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55 ); Console.WriteLine(); PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 }, 445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202, 253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534, 622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458, 945,733,507,916,123,345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,787,942,456,242,759, 898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527, 736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621, 892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749); } static void PrintBins(int[] limits, params int[] data) { int[] bins = Bins(limits, data); Console.WriteLine($"-∞ .. {limits[0]} => {bins[0]}"); for (int i = 0; i < limits.Length-1; i++) { Console.WriteLine($"{limits[i]} .. {limits[i+1]} => {bins[i+1]}"); } Console.WriteLine($"{limits[^1]} .. ∞ => {bins[^1]}"); } static int[] Bins(int[] limits, params int[] data) { Array.Sort(limits); int[] bins = new int[limits.Length + 1]; foreach (int n in data) { int i = Array.BinarySearch(limits, n); i = i < 0 ? ~i : i+1; bins[i]++; } return bins; } }
from bisect import bisect_right def bin_it(limits: list, data: list) -> list: "Bin data according to (ascending) limits." bins = [0] * (len(limits) + 1) for d in data: bins[bisect_right(limits, d)] += 1 return bins def bin_print(limits: list, bins: list) -> list: print(f" < {limits[0]:3} := {bins[0]:3}") for lo, hi, count in zip(limits, limits[1:], bins[1:]): print(f">= {lo:3} .. < {hi:3} := {count:3}") print(f">= {limits[-1]:3}  := {bins[-1]:3}") if __name__ == "__main__": print("RC FIRST EXAMPLE\n") limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] bins = bin_it(limits, data) bin_print(limits, bins) print("\nRC SECOND EXAMPLE\n") limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] bins = bin_it(limits, data) bin_print(limits, bins)
Port the following code from C# to Python with equivalent syntax and logic.
using System; public class Program { static void Main() { PrintBins(new [] { 23, 37, 43, 53, 67, 83 }, 95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55 ); Console.WriteLine(); PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 }, 445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202, 253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534, 622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458, 945,733,507,916,123,345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,787,942,456,242,759, 898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527, 736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621, 892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749); } static void PrintBins(int[] limits, params int[] data) { int[] bins = Bins(limits, data); Console.WriteLine($"-∞ .. {limits[0]} => {bins[0]}"); for (int i = 0; i < limits.Length-1; i++) { Console.WriteLine($"{limits[i]} .. {limits[i+1]} => {bins[i+1]}"); } Console.WriteLine($"{limits[^1]} .. ∞ => {bins[^1]}"); } static int[] Bins(int[] limits, params int[] data) { Array.Sort(limits); int[] bins = new int[limits.Length + 1]; foreach (int n in data) { int i = Array.BinarySearch(limits, n); i = i < 0 ? ~i : i+1; bins[i]++; } return bins; } }
from bisect import bisect_right def bin_it(limits: list, data: list) -> list: "Bin data according to (ascending) limits." bins = [0] * (len(limits) + 1) for d in data: bins[bisect_right(limits, d)] += 1 return bins def bin_print(limits: list, bins: list) -> list: print(f" < {limits[0]:3} := {bins[0]:3}") for lo, hi, count in zip(limits, limits[1:], bins[1:]): print(f">= {lo:3} .. < {hi:3} := {count:3}") print(f">= {limits[-1]:3}  := {bins[-1]:3}") if __name__ == "__main__": print("RC FIRST EXAMPLE\n") limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] bins = bin_it(limits, data) bin_print(limits, bins) print("\nRC SECOND EXAMPLE\n") limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] bins = bin_it(limits, data) bin_print(limits, bins)
Write the same algorithm in Python as shown in this C# implementation.
using System; using System.Drawing; using System.Windows.Forms; class CSharpPendulum { Form _form; Timer _timer; double _angle = Math.PI / 2, _angleAccel, _angleVelocity = 0, _dt = 0.1; int _length = 50; [STAThread] static void Main() { var p = new CSharpPendulum(); } public CSharpPendulum() { _form = new Form() { Text = "Pendulum", Width = 200, Height = 200 }; _timer = new Timer() { Interval = 30 }; _timer.Tick += delegate(object sender, EventArgs e) { int anchorX = (_form.Width / 2) - 12, anchorY = _form.Height / 4, ballX = anchorX + (int)(Math.Sin(_angle) * _length), ballY = anchorY + (int)(Math.Cos(_angle) * _length); _angleAccel = -9.81 / _length * Math.Sin(_angle); _angleVelocity += _angleAccel * _dt; _angle += _angleVelocity * _dt; Bitmap dblBuffer = new Bitmap(_form.Width, _form.Height); Graphics g = Graphics.FromImage(dblBuffer); Graphics f = Graphics.FromHwnd(_form.Handle); g.DrawLine(Pens.Black, new Point(anchorX, anchorY), new Point(ballX, ballY)); g.FillEllipse(Brushes.Black, anchorX - 3, anchorY - 4, 7, 7); g.FillEllipse(Brushes.DarkGoldenrod, ballX - 7, ballY - 7, 14, 14); f.Clear(Color.White); f.DrawImage(dblBuffer, new Point(0, 0)); }; _timer.Start(); Application.Run(_form); } }
import pygame, sys from pygame.locals import * from math import sin, cos, radians pygame.init() WINDOWSIZE = 250 TIMETICK = 100 BOBSIZE = 15 window = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE)) pygame.display.set_caption("Pendulum") screen = pygame.display.get_surface() screen.fill((255,255,255)) PIVOT = (WINDOWSIZE/2, WINDOWSIZE/10) SWINGLENGTH = PIVOT[1]*4 class BobMass(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.theta = 45 self.dtheta = 0 self.rect = pygame.Rect(PIVOT[0]-SWINGLENGTH*cos(radians(self.theta)), PIVOT[1]+SWINGLENGTH*sin(radians(self.theta)), 1,1) self.draw() def recomputeAngle(self): scaling = 3000.0/(SWINGLENGTH**2) firstDDtheta = -sin(radians(self.theta))*scaling midDtheta = self.dtheta + firstDDtheta midtheta = self.theta + (self.dtheta + midDtheta)/2.0 midDDtheta = -sin(radians(midtheta))*scaling midDtheta = self.dtheta + (firstDDtheta + midDDtheta)/2 midtheta = self.theta + (self.dtheta + midDtheta)/2 midDDtheta = -sin(radians(midtheta)) * scaling lastDtheta = midDtheta + midDDtheta lasttheta = midtheta + (midDtheta + lastDtheta)/2.0 lastDDtheta = -sin(radians(lasttheta)) * scaling lastDtheta = midDtheta + (midDDtheta + lastDDtheta)/2.0 lasttheta = midtheta + (midDtheta + lastDtheta)/2.0 self.dtheta = lastDtheta self.theta = lasttheta self.rect = pygame.Rect(PIVOT[0]- SWINGLENGTH*sin(radians(self.theta)), PIVOT[1]+ SWINGLENGTH*cos(radians(self.theta)),1,1) def draw(self): pygame.draw.circle(screen, (0,0,0), PIVOT, 5, 0) pygame.draw.circle(screen, (0,0,0), self.rect.center, BOBSIZE, 0) pygame.draw.aaline(screen, (0,0,0), PIVOT, self.rect.center) pygame.draw.line(screen, (0,0,0), (0, PIVOT[1]), (WINDOWSIZE, PIVOT[1])) def update(self): self.recomputeAngle() screen.fill((255,255,255)) self.draw() bob = BobMass() TICK = USEREVENT + 2 pygame.time.set_timer(TICK, TIMETICK) def input(events): for event in events: if event.type == QUIT: sys.exit(0) elif event.type == TICK: bob.update() while True: input(pygame.event.get()) pygame.display.flip()
Write the same code in Python as shown below in C#.
using System; using System.Collections.Generic; using System.Text; public class HeapSortClass { public static void HeapSort<T>(T[] array) { HeapSort<T>(array, 0, array.Length, Comparer<T>.Default); } public static void HeapSort<T>(T[] array, int offset, int length, IComparer<T> comparer) { HeapSort<T>(array, offset, length, comparer.Compare); } public static void HeapSort<T>(T[] array, int offset, int length, Comparison<T> comparison) { for (int i = 0; i < length; i++) { int index = i; T item = array[offset + i]; while (index > 0 && comparison(array[offset + (index - 1) / 2], item) < 0) { int top = (index - 1) / 2; array[offset + index] = array[offset + top]; index = top; } array[offset + index] = item; } for (int i = length - 1; i > 0; i--) { T last = array[offset + i]; array[offset + i] = array[offset]; int index = 0; while (index * 2 + 1 < i) { int left = index * 2 + 1, right = left + 1; if (right < i && comparison(array[offset + left], array[offset + right]) < 0) { if (comparison(last, array[offset + right]) > 0) break; array[offset + index] = array[offset + right]; index = right; } else { if (comparison(last, array[offset + left]) > 0) break; array[offset + index] = array[offset + left]; index = left; } } array[offset + index] = last; } } static void Main() { byte[] r = {5, 4, 1, 2}; HeapSort(r); string[] s = { "-", "D", "a", "33" }; HeapSort(s, 0, s.Length, StringComparer.CurrentCultureIgnoreCase); } }
def heapsort(lst): for start in range((len(lst)-2)/2, -1, -1): siftdown(lst, start, len(lst)-1) for end in range(len(lst)-1, 0, -1): lst[end], lst[0] = lst[0], lst[end] siftdown(lst, 0, end - 1) return lst def siftdown(lst, start, end): root = start while True: child = root * 2 + 1 if child > end: break if child + 1 <= end and lst[child] < lst[child + 1]: child += 1 if lst[root] < lst[child]: lst[root], lst[child] = lst[child], lst[root] root = child else: break
Can you help me rewrite this code in Python instead of C#, keeping it the same logically?
using System; using System.Linq; using System.Collections.Generic; public struct Card { public Card(string rank, string suit) : this() { Rank = rank; Suit = suit; } public string Rank { get; } public string Suit { get; } public override string ToString() => $"{Rank} of {Suit}"; } public class Deck : IEnumerable<Card> { static readonly string[] ranks = { "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace" }; static readonly string[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" }; readonly List<Card> cards; public Deck() { cards = (from suit in suits from rank in ranks select new Card(rank, suit)).ToList(); } public int Count => cards.Count; public void Shuffle() { var random = new Random(); for (int i = 0; i < cards.Count; i++) { int r = random.Next(i, cards.Count); var temp = cards[i]; cards[i] = cards[r]; cards[r] = temp; } } public Card Deal() { int last = cards.Count - 1; Card card = cards[last]; cards.RemoveAt(last); return card; } public IEnumerator<Card> GetEnumerator() { for (int i = cards.Count - 1; i >= 0; i--) yield return cards[i]; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); }
import random class Card(object): suits = ("Clubs","Hearts","Spades","Diamonds") pips = ("2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace") def __init__(self, pip,suit): self.pip=pip self.suit=suit def __str__(self): return "%s %s"%(self.pip,self.suit) class Deck(object): def __init__(self): self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips] def __str__(self): return "[%s]"%", ".join( (str(card) for card in self.deck)) def shuffle(self): random.shuffle(self.deck) def deal(self): self.shuffle() return self.deck.pop(0)
Change the programming language of this snippet from C# to Python without modifying what it does.
using System; using System.Linq; using System.Collections.Generic; public struct Card { public Card(string rank, string suit) : this() { Rank = rank; Suit = suit; } public string Rank { get; } public string Suit { get; } public override string ToString() => $"{Rank} of {Suit}"; } public class Deck : IEnumerable<Card> { static readonly string[] ranks = { "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace" }; static readonly string[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" }; readonly List<Card> cards; public Deck() { cards = (from suit in suits from rank in ranks select new Card(rank, suit)).ToList(); } public int Count => cards.Count; public void Shuffle() { var random = new Random(); for (int i = 0; i < cards.Count; i++) { int r = random.Next(i, cards.Count); var temp = cards[i]; cards[i] = cards[r]; cards[r] = temp; } } public Card Deal() { int last = cards.Count - 1; Card card = cards[last]; cards.RemoveAt(last); return card; } public IEnumerator<Card> GetEnumerator() { for (int i = cards.Count - 1; i >= 0; i--) yield return cards[i]; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); }
import random class Card(object): suits = ("Clubs","Hearts","Spades","Diamonds") pips = ("2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace") def __init__(self, pip,suit): self.pip=pip self.suit=suit def __str__(self): return "%s %s"%(self.pip,self.suit) class Deck(object): def __init__(self): self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips] def __str__(self): return "[%s]"%", ".join( (str(card) for card in self.deck)) def shuffle(self): random.shuffle(self.deck) def deal(self): self.shuffle() return self.deck.pop(0)
Convert the following code from C# to Python, ensuring the logic remains intact.
int[] numbers = new int[10];
array = [] array.append(1) array.append(3) array[0] = 2 print array[0]
Change the following C# code into Python without altering its purpose.
int[] numbers = new int[10];
array = [] array.append(1) array.append(3) array[0] = 2 print array[0]
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; class Program { static List<string> NextCarpet(List<string> carpet) { return carpet.Select(x => x + x + x) .Concat(carpet.Select(x => x + x.Replace('#', ' ') + x)) .Concat(carpet.Select(x => x + x + x)).ToList(); } static List<string> SierpinskiCarpet(int n) { return Enumerable.Range(1, n).Aggregate(new List<string> { "#" }, (carpet, _) => NextCarpet(carpet)); } static void Main(string[] args) { foreach (string s in SierpinskiCarpet(3)) Console.WriteLine(s); } }
def setup(): size(729, 729) fill(0) background(255) noStroke() rect(width / 3, height / 3, width / 3, width / 3) rectangles(width / 3, height / 3, width / 3) def rectangles(x, y, s): if s < 1: return xc, yc = x - s, y - s for row in range(3): for col in range(3): if not (row == 1 and col == 1): xx, yy = xc + row * s, yc + col * s delta = s / 3 rect(xx + delta, yy + delta, delta, delta) rectangles(xx + s / 3, yy + s / 3, s / 3)
Produce a functionally identical Python code for the snippet given in C#.
using System; using System.Collections.Generic; namespace RosettaCode.BogoSort { public static class BogoSorter { public static void Sort<T>(List<T> list) where T:IComparable { while (!list.isSorted()) { list.Shuffle(); } } private static bool isSorted<T>(this IList<T> list) where T:IComparable { if(list.Count<=1) return true; for (int i = 1 ; i < list.Count; i++) if(list[i].CompareTo(list[i-1])<0) return false; return true; } private static void Shuffle<T>(this IList<T> list) { Random rand = new Random(); for (int i = 0; i < list.Count; i++) { int swapIndex = rand.Next(list.Count); T temp = list[swapIndex]; list[swapIndex] = list[i]; list[i] = temp; } } } class TestProgram { static void Main() { List<int> testList = new List<int> { 3, 4, 1, 8, 7, 4, -2 }; BogoSorter.Sort(testList); foreach (int i in testList) Console.Write(i + " "); } } }
import random def bogosort(l): while not in_order(l): random.shuffle(l) return l def in_order(l): if not l: return True last = l[0] for x in l[1:]: if x < last: return False last = x return True
Translate this program into Python but keep the logic exactly as in C#.
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Runtime.Serialization; public static class MergeAndAggregateDatasets { public static void Main() { string patientsCsv = @" PATIENT_ID,LASTNAME 1001,Hopper 4004,Wirth 3003,Kemeny 2002,Gosling 5005,Kurtz"; string visitsCsv = @" PATIENT_ID,VISIT_DATE,SCORE 2002,2020-09-10,6.8 1001,2020-09-17,5.5 4004,2020-09-24,8.4 2002,2020-10-08, 1001,,6.6 3003,2020-11-12, 4004,2020-11-05,7.0 1001,2020-11-19,5.3"; string format = "yyyy-MM-dd"; var formatProvider = new DateTimeFormat(format).FormatProvider; var patients = ParseCsv( patientsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries), line => (PatientId: int.Parse(line[0]), LastName: line[1])); var visits = ParseCsv( visitsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries), line => ( PatientId: int.Parse(line[0]), VisitDate: DateTime.TryParse(line[1], formatProvider, DateTimeStyles.None, out var date) ? date : default(DateTime?), Score: double.TryParse(line[2], out double score) ? score : default(double?) ) ); var results = patients.GroupJoin(visits, p => p.PatientId, v => v.PatientId, (p, vs) => ( p.PatientId, p.LastName, LastVisit: vs.Max(v => v.VisitDate), ScoreSum: vs.Sum(v => v.Score), ScoreAvg: vs.Average(v => v.Score) ) ).OrderBy(r => r.PatientId); Console.WriteLine("| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |"); foreach (var r in results) { Console.WriteLine($"| {r.PatientId,-10} | {r.LastName,-8} | {r.LastVisit?.ToString(format) ?? "",-10} | {r.ScoreSum,9} | {r.ScoreAvg,9} |"); } } private static IEnumerable<T> ParseCsv<T>(string[] contents, Func<string[], T> constructor) { for (int i = 1; i < contents.Length; i++) { var line = contents[i].Split(','); yield return constructor(line); } } }
import pandas as pd df_patients = pd.read_csv (r'patients.csv', sep = ",", decimal=".") df_visits = pd.read_csv (r'visits.csv', sep = ",", decimal=".") df_visits['VISIT_DATE'] = pd.to_datetime(df_visits['VISIT_DATE']) df_merge = df_patients.merge(df_visits, on='PATIENT_ID', how='left') df_group = df_merge.groupby(['PATIENT_ID','LASTNAME'], as_index=False) df_result = df_group.agg({'VISIT_DATE': 'max', 'SCORE': [lambda x: x.sum(min_count=1),'mean']}) print(df_result)
Produce a functionally identical Python code for the snippet given in C#.
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Runtime.Serialization; public static class MergeAndAggregateDatasets { public static void Main() { string patientsCsv = @" PATIENT_ID,LASTNAME 1001,Hopper 4004,Wirth 3003,Kemeny 2002,Gosling 5005,Kurtz"; string visitsCsv = @" PATIENT_ID,VISIT_DATE,SCORE 2002,2020-09-10,6.8 1001,2020-09-17,5.5 4004,2020-09-24,8.4 2002,2020-10-08, 1001,,6.6 3003,2020-11-12, 4004,2020-11-05,7.0 1001,2020-11-19,5.3"; string format = "yyyy-MM-dd"; var formatProvider = new DateTimeFormat(format).FormatProvider; var patients = ParseCsv( patientsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries), line => (PatientId: int.Parse(line[0]), LastName: line[1])); var visits = ParseCsv( visitsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries), line => ( PatientId: int.Parse(line[0]), VisitDate: DateTime.TryParse(line[1], formatProvider, DateTimeStyles.None, out var date) ? date : default(DateTime?), Score: double.TryParse(line[2], out double score) ? score : default(double?) ) ); var results = patients.GroupJoin(visits, p => p.PatientId, v => v.PatientId, (p, vs) => ( p.PatientId, p.LastName, LastVisit: vs.Max(v => v.VisitDate), ScoreSum: vs.Sum(v => v.Score), ScoreAvg: vs.Average(v => v.Score) ) ).OrderBy(r => r.PatientId); Console.WriteLine("| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |"); foreach (var r in results) { Console.WriteLine($"| {r.PatientId,-10} | {r.LastName,-8} | {r.LastVisit?.ToString(format) ?? "",-10} | {r.ScoreSum,9} | {r.ScoreAvg,9} |"); } } private static IEnumerable<T> ParseCsv<T>(string[] contents, Func<string[], T> constructor) { for (int i = 1; i < contents.Length; i++) { var line = contents[i].Split(','); yield return constructor(line); } } }
import pandas as pd df_patients = pd.read_csv (r'patients.csv', sep = ",", decimal=".") df_visits = pd.read_csv (r'visits.csv', sep = ",", decimal=".") df_visits['VISIT_DATE'] = pd.to_datetime(df_visits['VISIT_DATE']) df_merge = df_patients.merge(df_visits, on='PATIENT_ID', how='left') df_group = df_merge.groupby(['PATIENT_ID','LASTNAME'], as_index=False) df_result = df_group.agg({'VISIT_DATE': 'max', 'SCORE': [lambda x: x.sum(min_count=1),'mean']}) print(df_result)
Produce a language-to-language conversion: from C# to Python, same semantics.
using System; namespace prog { class MainClass { const float T0 = 100f; const float TR = 20f; const float k = 0.07f; readonly static float[] delta_t = {2.0f,5.0f,10.0f}; const int n = 100; public delegate float func(float t); static float NewtonCooling(float t) { return -k * (t-TR); } public static void Main (string[] args) { func f = new func(NewtonCooling); for(int i=0; i<delta_t.Length; i++) { Console.WriteLine("delta_t = " + delta_t[i]); Euler(f,T0,n,delta_t[i]); } } public static void Euler(func f, float y, int n, float h) { for(float x=0; x<=n; x+=h) { Console.WriteLine("\t" + x + "\t" + y); y += h * f(y); } } } }
def euler(f,y0,a,b,h): t,y = a,y0 while t <= b: print "%6.3f %6.3f" % (t,y) t += h y += h * f(t,y) def newtoncooling(time, temp): return -0.07 * (temp - 20) euler(newtoncooling,100,0,100,10)
Transform the following C# implementation into Python, maintaining the same output and logic.
using System; using System.Diagnostics; namespace sons { class Program { static void Main(string[] args) { for (int i = 1; i < 23; i++) Console.WriteLine(nonsqr(i)); for (int i = 1; i < 1000000; i++) { double j = Math.Sqrt(nonsqr(i)); Debug.Assert(j != Math.Floor(j),"Square"); } } static int nonsqr(int i) { return (int)(i + Math.Floor(0.5 + Math.Sqrt(i))); } } }
>>> from math import floor, sqrt >>> def non_square(n): return n + floor(1/2 + sqrt(n)) >>> >>> print(*map(non_square, range(1, 23))) 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27 >>> >>> def is_square(n): return sqrt(n).is_integer() >>> non_squares = map(non_square, range(1, 10 ** 6)) >>> next(filter(is_square, non_squares)) StopIteration Traceback (most recent call last) <ipython-input-45-f32645fc1c0a> in <module>() 1 non_squares = map(non_square, range(1, 10 ** 6)) ----> 2 next(filter(is_square, non_squares)) StopIteration:
Transform the following C# implementation into Python, maintaining the same output and logic.
using System; namespace SubString { class Program { static void Main(string[] args) { string s = "0123456789"; const int n = 3; const int m = 2; const char c = '3'; const string z = "345"; Console.WriteLine(s.Substring(n, m)); Console.WriteLine(s.Substring(n, s.Length - n)); Console.WriteLine(s.Substring(0, s.Length - 1)); Console.WriteLine(s.Substring(s.IndexOf(c), m)); Console.WriteLine(s.Substring(s.IndexOf(z), m)); } } }
>>> s = 'abcdefgh' >>> n, m, char, chars = 2, 3, 'd', 'cd' >>> >>> s[n-1:n+m-1] 'bcd' >>> >>> s[n-1:] 'bcdefgh' >>> >>> s[:-1] 'abcdefg' >>> >>> indx = s.index(char) >>> s[indx:indx+m] 'def' >>> >>> indx = s.index(chars) >>> s[indx:indx+m] 'cde' >>>
Rewrite the snippet below in Python so it works the same as the original C# code.
using System; class Program { public static bool JortSort<T>(T[] array) where T : IComparable, IEquatable<T> { T[] originalArray = (T[]) array.Clone(); Array.Sort(array); for (var i = 0; i < originalArray.Length; i++) { if (!Equals(originalArray[i], array[i])) { return false; } } return true; } }
>>> def jortsort(sequence): return list(sequence) == sorted(sequence) >>> for data in [(1,2,4,3), (14,6,8), ['a', 'c'], ['s', 'u', 'x'], 'CVGH', 'PQRST']: print(f'jortsort({repr(data)}) is {jortsort(data)}') jortsort((1, 2, 4, 3)) is False jortsort((14, 6, 8)) is False jortsort(['a', 'c']) is True jortsort(['s', 'u', 'x']) is True jortsort('CVGH') is False jortsort('PQRST') is True >>>
Keep all operations the same but rewrite the snippet in Python.
using System; class Program { static void Main() { foreach (var year in new[] { 1900, 1994, 1996, DateTime.Now.Year }) { Console.WriteLine("{0} is {1}a leap year.", year, DateTime.IsLeapYear(year) ? string.Empty : "not "); } } }
import calendar calendar.isleap(year)
Preserve the algorithm and functionality while converting the code from C# to Python.
using static System.Console; using static System.Linq.Enumerable; public class Program { public static void Main() { foreach (int n in new [] { 0, 5, 13, 21, -22 }) WriteLine($"{n}: {string.Join(", ", LexOrder(n))}"); } public static IEnumerable<int> LexOrder(int n) => (n < 1 ? Range(n, 2 - n) : Range(1, n)).OrderBy(i => i.ToString()); }
n=13 print(sorted(range(1,n+1), key=str))
Transform the following C# implementation into Python, maintaining the same output and logic.
using System; class NumberNamer { static readonly string[] incrementsOfOne = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; static readonly string[] incrementsOfTen = { "", "", "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety" }; const string millionName = "million", thousandName = "thousand", hundredName = "hundred", andName = "and"; public static string GetName( int i ) { string output = ""; if( i >= 1000000 ) { output += ParseTriplet( i / 1000000 ) + " " + millionName; i %= 1000000; if( i == 0 ) return output; } if( i >= 1000 ) { if( output.Length > 0 ) { output += ", "; } output += ParseTriplet( i / 1000 ) + " " + thousandName; i %= 1000; if( i == 0 ) return output; } if( output.Length > 0 ) { output += ", "; } output += ParseTriplet( i ); return output; } static string ParseTriplet( int i ) { string output = ""; if( i >= 100 ) { output += incrementsOfOne[i / 100] + " " + hundredName; i %= 100; if( i == 0 ) return output; } if( output.Length > 0 ) { output += " " + andName + " "; } if( i >= 20 ) { output += incrementsOfTen[i / 10]; i %= 10; if( i == 0 ) return output; } if( output.Length > 0 ) { output += " "; } output += incrementsOfOne[i]; return output; } } class Program { static void Main( string[] args ) { Console.WriteLine( NumberNamer.GetName( 1 ) ); Console.WriteLine( NumberNamer.GetName( 234 ) ); Console.WriteLine( NumberNamer.GetName( 31337 ) ); Console.WriteLine( NumberNamer.GetName( 987654321 ) ); } }
TENS = [None, None, "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] SMALL = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] HUGE = [None, None] + [h + "illion" for h in ("m", "b", "tr", "quadr", "quint", "sext", "sept", "oct", "non", "dec")] def nonzero(c, n, connect=''): return "" if n == 0 else connect + c + spell_integer(n) def last_and(num): if ',' in num: pre, last = num.rsplit(',', 1) if ' and ' not in last: last = ' and' + last num = ''.join([pre, ',', last]) return num def big(e, n): if e == 0: return spell_integer(n) elif e == 1: return spell_integer(n) + " thousand" else: return spell_integer(n) + " " + HUGE[e] def base1000_rev(n): while n != 0: n, r = divmod(n, 1000) yield r def spell_integer(n): if n < 0: return "minus " + spell_integer(-n) elif n < 20: return SMALL[n] elif n < 100: a, b = divmod(n, 10) return TENS[a] + nonzero("-", b) elif n < 1000: a, b = divmod(n, 100) return SMALL[a] + " hundred" + nonzero(" ", b, ' and') else: num = ", ".join([big(e, x) for e, x in enumerate(base1000_rev(n)) if x][::-1]) return last_and(num) if __name__ == '__main__': for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29): print('%+4i -> %s' % (n, spell_integer(n))) print('') n = 201021002001 while n: print('%-12i -> %s' % (n, spell_integer(n))) n //= -10 print('%-12i -> %s' % (n, spell_integer(n))) print('')
Can you help me rewrite this code in Python instead of C#, keeping it the same logically?
using System; using System.Collections.Generic; namespace example { class Program { static void Main(string[] args) { var strings = new string[] { "abcd", "123456789", "abcdef", "1234567" }; compareAndReportStringsLength(strings); } private static void compareAndReportStringsLength(string[] strings) { if (strings.Length > 0) { char Q = '"'; string hasLength = " has length "; string predicateMax = " and is the longest string"; string predicateMin = " and is the shortest string"; string predicateAve = " and is neither the longest nor the shortest string"; string predicate; (int, int)[] li = new (int, int)[strings.Length]; for (int i = 0; i < strings.Length; i++) li[i] = (strings[i].Length, i); Array.Sort(li, ((int, int) a, (int, int) b) => b.Item1 - a.Item1); int maxLength = li[0].Item1; int minLength = li[strings.Length - 1].Item1; for (int i = 0; i < strings.Length; i++) { int length = li[i].Item1; string str = strings[li[i].Item2]; if (length == maxLength) predicate = predicateMax; else if (length == minLength) predicate = predicateMin; else predicate = predicateAve; Console.WriteLine(Q + str + Q + hasLength + length + predicate); } } } } }
A = 'I am string' B = 'I am string too' if len(A) > len(B): print('"' + A + '"', 'has length', len(A), 'and is the longest of the two strings') print('"' + B + '"', 'has length', len(B), 'and is the shortest of the two strings') elif len(A) < len(B): print('"' + B + '"', 'has length', len(B), 'and is the longest of the two strings') print('"' + A + '"', 'has length', len(A), 'and is the shortest of the two strings') else: print('"' + A + '"', 'has length', len(A), 'and it is as long as the second string') print('"' + B + '"', 'has length', len(B), 'and it is as long as the second string')
Convert this C# snippet to Python and keep its semantics consistent.
using System; using System.Collections.Generic; using System.IO; using System.Linq; class Program { static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items) { var dictionary = new SortedDictionary<TItem, int>(); foreach (var item in items) { if (dictionary.ContainsKey(item)) { dictionary[item]++; } else { dictionary[item] = 1; } } return dictionary; } static void Main(string[] arguments) { var file = arguments.FirstOrDefault(); if (File.Exists(file)) { var text = File.ReadAllText(file); foreach (var entry in GetFrequencies(text)) { Console.WriteLine("{0}: {1}", entry.Key, entry.Value); } } } }
import collections, sys def filecharcount(openfile): return sorted(collections.Counter(c for l in openfile for c in l).items()) f = open(sys.argv[1]) print(filecharcount(f))
Ensure the translated Python code behaves exactly like the original C# snippet.
string s = "12345"; s = (int.Parse(s) + 1).ToString(); using System.Numerics; string bis = "123456789012345678999999999"; bis = (BigInteger.Parse(bis) + 1).ToString();
next = str(int('123') + 1)
Preserve the algorithm and functionality while converting the code from C# to Python.
using System; public static string RemoveCharactersFromString(string testString, string removeChars) { char[] charAry = removeChars.ToCharArray(); string returnString = testString; foreach (char c in charAry) { while (returnString.IndexOf(c) > -1) { returnString = returnString.Remove(returnString.IndexOf(c), 1); } } return returnString; }
>>> def stripchars(s, chars): ... return s.translate(None, chars) ... >>> stripchars("She was a soul stripper. She took my heart!", "aei") 'Sh ws soul strppr. Sh took my hrt!'
Translate this program into Python but keep the logic exactly as in C#.
using System; using System.Linq; class Program { static void Main() { Console.WriteLine(new[] { 1, 2, 3 }.Average()); } }
from math import fsum def average(x): return fsum(x)/float(len(x)) if x else 0 print (average([0,0,3,1,4,1,5,9,0,0])) print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))
Port the following code from C# to Python with equivalent syntax and logic.
using System; using System.Collections.Generic; namespace Entropy { class Program { public static double logtwo(double num) { return Math.Log(num)/Math.Log(2); } public static void Main(string[] args) { label1: string input = Console.ReadLine(); double infoC=0; Dictionary<char,double> table = new Dictionary<char, double>(); foreach (char c in input) { if (table.ContainsKey(c)) table[c]++; else table.Add(c,1); } double freq; foreach (KeyValuePair<char,double> letter in table) { freq=letter.Value/input.Length; infoC+=freq*logtwo(freq); } infoC*=-1; Console.WriteLine("The Entropy of {0} is {1}",input,infoC); goto label1; } } }
from __future__ import division import math def hist(source): hist = {}; l = 0; for e in source: l += 1 if e not in hist: hist[e] = 0 hist[e] += 1 return (l,hist) def entropy(hist,l): elist = [] for v in hist.values(): c = v / l elist.append(-c * math.log(c ,2)) return sum(elist) def printHist(h): flip = lambda (k,v) : (v,k) h = sorted(h.iteritems(), key = flip) print 'Sym\thi\tfi\tInf' for (k,v) in h: print '%s\t%f\t%f\t%f'%(k,v,v/l,-math.log(v/l, 2)) source = "1223334444" (l,h) = hist(source); print '.[Results].' print 'Length',l print 'Entropy:', entropy(h, l) printHist(h)
Ensure the translated Python code behaves exactly like the original C# snippet.
using System; using System.Text; using System.Collections.Generic; public class TokenizeAStringWithEscaping { public static void Main() { string testcase = "one^|uno||three^^^^|four^^^|^cuatro|"; foreach (var token in testcase.Tokenize(separator: '|', escape: '^')) { Console.WriteLine(": " + token); } } } public static class Extensions { public static IEnumerable<string> Tokenize(this string input, char separator, char escape) { if (input == null) yield break; var buffer = new StringBuilder(); bool escaping = false; foreach (char c in input) { if (escaping) { buffer.Append(c); escaping = false; } else if (c == escape) { escaping = true; } else if (c == separator) { yield return buffer.Flush(); } else { buffer.Append(c); } } if (buffer.Length > 0 || input[input.Length-1] == separator) yield return buffer.Flush(); } public static string Flush(this StringBuilder stringBuilder) { string result = stringBuilder.ToString(); stringBuilder.Clear(); return result; } }
def token_with_escape(a, escape = '^', separator = '|'): result = [] token = '' state = 0 for c in a: if state == 0: if c == escape: state = 1 elif c == separator: result.append(token) token = '' else: token += c elif state == 1: token += c state = 0 result.append(token) return result
Produce a language-to-language conversion: from C# to Python, same semantics.
Using System; namespace HelloWorld { class Program { static void Main() { Console.Writeln("Hello World!"); } } }
print "Hello world!"
Change the programming language of this snippet from C# to Python without modifying what it does.
Using System; namespace HelloWorld { class Program { static void Main() { Console.Writeln("Hello World!"); } } }
print "Hello world!"
Write the same code in Python as shown below in C#.
using System; using System.Collections.Generic; using System.Linq; class Program { static IEnumerable<int> ForwardDifference(IEnumerable<int> sequence, uint order = 1u) { switch (order) { case 0u: return sequence; case 1u: return sequence.Skip(1).Zip(sequence, (next, current) => next - current); default: return ForwardDifference(ForwardDifference(sequence), order - 1u); } } static void Main() { IEnumerable<int> sequence = new[] { 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 }; do { Console.WriteLine(string.Join(", ", sequence)); } while ((sequence = ForwardDifference(sequence)).Any()); } }
>>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])] >>> >>> difn = lambda s, n: difn(dif(s), n-1) if n else s >>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] >>> difn(s, 0) [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] >>> difn(s, 1) [-43, 11, -29, -7, 10, 23, -50, 50, 18] >>> difn(s, 2) [54, -40, 22, 17, 13, -73, 100, -32] >>> from pprint import pprint >>> pprint( [difn(s, i) for i in xrange(10)] ) [[90, 47, 58, 29, 22, 32, 55, 5, 55, 73], [-43, 11, -29, -7, 10, 23, -50, 50, 18], [54, -40, 22, 17, 13, -73, 100, -32], [-94, 62, -5, -4, -86, 173, -132], [156, -67, 1, -82, 259, -305], [-223, 68, -83, 341, -564], [291, -151, 424, -905], [-442, 575, -1329], [1017, -1904], [-2921]]
Transform the following C# implementation into Python, maintaining the same output and logic.
static bool isPrime(int n) { if (n <= 1) return false; for (int i = 2; i * i <= n; i++) if (n % i == 0) return false; return true; }
def prime(a): return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))
Change the following C# code into Python without altering its purpose.
static bool isPrime(int n) { if (n <= 1) return false; for (int i = 2; i * i <= n; i++) if (n % i == 0) return false; return true; }
def prime(a): return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))
Ensure the translated Python code behaves exactly like the original C# snippet.
using System; namespace BinomialCoefficients { class Program { static void Main(string[] args) { ulong n = 1000000, k = 3; ulong result = biCoefficient(n, k); Console.WriteLine("The Binomial Coefficient of {0}, and {1}, is equal to: {2}", n, k, result); Console.ReadLine(); } static int fact(int n) { if (n == 0) return 1; else return n * fact(n - 1); } static ulong biCoefficient(ulong n, ulong k) { if (k > n - k) { k = n - k; } ulong c = 1; for (uint i = 0; i < k; i++) { c = c * (n - i); c = c / (i + 1); } return c; } } }
def binomialCoeff(n, k): result = 1 for i in range(1, k+1): result = result * (n-i+1) / i return result if __name__ == "__main__": print(binomialCoeff(5, 3))
Rewrite this program in Python while keeping its functionality equivalent to the C# version.
int[] intArray = new int[5] { 1, 2, 3, 4, 5 }; int[] intArray = new int[]{ 1, 2, 3, 4, 5 }; int[] intArray = { 1, 2, 3, 4, 5 }; string[] stringArr = new string[5]; stringArr[0] = "string";
collection = [0, '1'] x = collection[0] collection.append(2) collection.insert(0, '-1') y = collection[0] collection.extend([2,'3']) collection += [2,'3'] collection[2:6] len(collection) collection = (0, 1) collection[:] collection[-4:-1] collection[::2] collection="some string" x = collection[::-1] collection[::2] == "some string"[::2] collection.__getitem__(slice(0,len(collection),2)) collection = {0: "zero", 1: "one"} collection['zero'] = 2 collection = set([0, '1'])
Keep all operations the same but rewrite the snippet in Python.
var current = [head of list to traverse] while(current != null) { current = current.Next; }
for node in lst: print node.value
Maintain the same structure and functionality when rewriting this code in Python.
using System; using System.IO; class PPMWriter { public static void WriteBitmapToPPM(string file, Bitmap bitmap) { var writer = new StreamWriter(file); writer.WriteLine("P6"); writer.WriteLine($"{bitmap.Width} {bitmap.Height}"); writer.WriteLine("255"); writer.Close(); var writerB = new BinaryWriter(new FileStream(file, FileMode.Append)); for (int x = 0; x < bitmap.Height; x++) for (int y = 0; y < bitmap.Width; y++) { Color color = bitmap.GetPixel(y, x); writerB.Write(color.R); writerB.Write(color.G); writerB.Write(color.B); } writerB.Close(); } }
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
Transform the following C# implementation into Python, maintaining the same output and logic.
using System; using System.IO; namespace DeleteFile { class Program { static void Main() { File.Delete("input.txt"); Directory.Delete("docs"); File.Delete("/input.txt"); Directory.Delete("/docs"); } } }
import os os.remove("output.txt") os.rmdir("docs") os.remove("/output.txt") os.rmdir("/docs")
Rewrite this program in Python while keeping its functionality equivalent to the C# version.
using System; public static class DiscordianDate { static readonly string[] seasons = { "Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath" }; static readonly string[] weekdays = { "Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange" }; static readonly string[] apostles = { "Mungday", "Mojoday", "Syaday", "Zaraday", "Maladay" }; static readonly string[] holidays = { "Chaoflux", "Discoflux", "Confuflux", "Bureflux", "Afflux" }; public static string Discordian(this DateTime date) { string yold = $" in the YOLD {date.Year + 1166}."; int dayOfYear = date.DayOfYear; if (DateTime.IsLeapYear(date.Year)) { if (dayOfYear == 60) return "St. Tib's day" + yold; else if (dayOfYear > 60) dayOfYear--; } dayOfYear--; int seasonDay = dayOfYear % 73 + 1; int seasonNr = dayOfYear / 73; int weekdayNr = dayOfYear % 5; string holyday = ""; if (seasonDay == 5) holyday = $" Celebrate {apostles[seasonNr]}!"; else if (seasonDay == 50) holyday = $" Celebrate {holidays[seasonNr]}!"; return $"{weekdays[weekdayNr]}, day {seasonDay} of {seasons[seasonNr]}{yold}{holyday}"; } public static void Main() { foreach (var (day, month, year) in new [] { (1, 1, 2010), (5, 1, 2010), (19, 2, 2011), (28, 2, 2012), (29, 2, 2012), (1, 3, 2012), (19, 3, 2013), (3, 5, 2014), (31, 5, 2015), (22, 6, 2016), (15, 7, 2016), (12, 8, 2017), (19, 9, 2018), (26, 9, 2018), (24, 10, 2019), (8, 12, 2020), (31, 12, 2020) }) { Console.WriteLine($"{day:00}-{month:00}-{year:00} = {new DateTime(year, month, day).Discordian()}"); } } }
import datetime, calendar DISCORDIAN_SEASONS = ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"] def ddate(year, month, day): today = datetime.date(year, month, day) is_leap_year = calendar.isleap(year) if is_leap_year and month == 2 and day == 29: return "St. Tib's Day, YOLD " + (year + 1166) day_of_year = today.timetuple().tm_yday - 1 if is_leap_year and day_of_year >= 60: day_of_year -= 1 season, dday = divmod(day_of_year, 73) return "%s %d, YOLD %d" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)
Can you help me rewrite this code in Python instead of C#, keeping it the same logically?
public class AverageLoopLength { private static int N = 100000; private static double analytical(int n) { double[] factorial = new double[n + 1]; double[] powers = new double[n + 1]; powers[0] = 1.0; factorial[0] = 1.0; for (int i = 1; i <= n; i++) { factorial[i] = factorial[i - 1] * i; powers[i] = powers[i - 1] * n; } double sum = 0; for (int i = 1; i <= n; i++) { sum += factorial[n] / factorial[n - i] / powers[i]; } return sum; } private static double average(int n) { Random rnd = new Random(); double sum = 0.0; for (int a = 0; a < N; a++) { int[] random = new int[n]; for (int i = 0; i < n; i++) { random[i] = rnd.Next(n); } var seen = new HashSet<double>(n); int current = 0; int length = 0; while (seen.Add(current)) { length++; current = random[current]; } sum += length; } return sum / N; } public static void Main(string[] args) { Console.WriteLine(" N average analytical (error)"); Console.WriteLine("=== ========= ============ ========="); for (int i = 1; i <= 20; i++) { var average = AverageLoopLength.average(i); var analytical = AverageLoopLength.analytical(i); Console.WriteLine("{0,3} {1,10:N4} {2,13:N4} {3,8:N2}%", i, average, analytical, (analytical - average) / analytical * 100); } } }
from __future__ import division from math import factorial from random import randrange MAX_N = 20 TIMES = 1000000 def analytical(n): return sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1)) def test(n, times): count = 0 for i in range(times): x, bits = 1, 0 while not (bits & x): count += 1 bits |= x x = 1 << randrange(n) return count / times if __name__ == '__main__': print(" n\tavg\texp.\tdiff\n-------------------------------") for n in range(1, MAX_N+1): avg = test(n, TIMES) theory = analytical(n) diff = (avg / theory - 1) * 100 print("%2d %8.4f %8.4f %6.3f%%" % (n, avg, theory, diff))
Rewrite the snippet below in Python so it works the same as the original C# code.
public class AverageLoopLength { private static int N = 100000; private static double analytical(int n) { double[] factorial = new double[n + 1]; double[] powers = new double[n + 1]; powers[0] = 1.0; factorial[0] = 1.0; for (int i = 1; i <= n; i++) { factorial[i] = factorial[i - 1] * i; powers[i] = powers[i - 1] * n; } double sum = 0; for (int i = 1; i <= n; i++) { sum += factorial[n] / factorial[n - i] / powers[i]; } return sum; } private static double average(int n) { Random rnd = new Random(); double sum = 0.0; for (int a = 0; a < N; a++) { int[] random = new int[n]; for (int i = 0; i < n; i++) { random[i] = rnd.Next(n); } var seen = new HashSet<double>(n); int current = 0; int length = 0; while (seen.Add(current)) { length++; current = random[current]; } sum += length; } return sum / N; } public static void Main(string[] args) { Console.WriteLine(" N average analytical (error)"); Console.WriteLine("=== ========= ============ ========="); for (int i = 1; i <= 20; i++) { var average = AverageLoopLength.average(i); var analytical = AverageLoopLength.analytical(i); Console.WriteLine("{0,3} {1,10:N4} {2,13:N4} {3,8:N2}%", i, average, analytical, (analytical - average) / analytical * 100); } } }
from __future__ import division from math import factorial from random import randrange MAX_N = 20 TIMES = 1000000 def analytical(n): return sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1)) def test(n, times): count = 0 for i in range(times): x, bits = 1, 0 while not (bits & x): count += 1 bits |= x x = 1 << randrange(n) return count / times if __name__ == '__main__': print(" n\tavg\texp.\tdiff\n-------------------------------") for n in range(1, MAX_N+1): avg = test(n, TIMES) theory = analytical(n) diff = (avg / theory - 1) * 100 print("%2d %8.4f %8.4f %6.3f%%" % (n, avg, theory, diff))
Rewrite the snippet below in Python so it works the same as the original C# code.
class Program { static void Main() { string extra = "little"; string formatted = $"Mary had a {extra} lamb."; System.Console.WriteLine(formatted); } }
>>> original = 'Mary had a %s lamb.' >>> extra = 'little' >>> original % extra 'Mary had a little lamb.'
Produce a language-to-language conversion: from C# to Python, same semantics.
using System; class Program { const long Lm = (long)1e18; const string Fm = "D18"; struct LI { public long lo, ml, mh, hi, tp; } static void inc(ref LI d, LI s) { if ((d.lo += s.lo) >= Lm) { d.ml++; d.lo -= Lm; } if ((d.ml += s.ml) >= Lm) { d.mh++; d.ml -= Lm; } if ((d.mh += s.mh) >= Lm) { d.hi++; d.mh -= Lm; } if ((d.hi += s.hi) >= Lm) { d.tp++; d.hi -= Lm; } d.tp += s.tp; } static void dec(ref LI d, LI s) { if ((d.lo -= s.lo) < 0) { d.ml--; d.lo += Lm; } if ((d.ml -= s.ml) < 0) { d.mh--; d.ml += Lm; } if ((d.mh -= s.mh) < 0) { d.hi--; d.mh += Lm; } if ((d.hi -= s.hi) < 0) { d.tp--; d.hi += Lm; } d.tp -= s.tp; } static LI set(long s) { LI d; d.lo = s; d.ml = d.mh = d.hi = d.tp = 0; return d; } static string fmt(LI x) { if (x.tp > 0) return x.tp.ToString() + x.hi.ToString(Fm) + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm); if (x.hi > 0) return x.hi.ToString() + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm); if (x.mh > 0) return x.mh.ToString() + x.ml.ToString(Fm) + x.lo.ToString(Fm); if (x.ml > 0) return x.ml.ToString() + x.lo.ToString(Fm); return x.lo.ToString(); } static LI partcount(int n) { var P = new LI[n + 1]; P[0] = set(1); for (int i = 1; i <= n; i++) { int k = 0, d = -2, j = i; LI x = set(0); while (true) { if ((j -= (d += 3) -k) >= 0) inc(ref x, P[j]); else break; if ((j -= ++k) >= 0) inc(ref x, P[j]); else break; if ((j -= (d += 3) -k) >= 0) dec(ref x, P[j]); else break; if ((j -= ++k) >= 0) dec(ref x, P[j]); else break; } P[i] = x; } return P[n]; } static void Main(string[] args) { var sw = System.Diagnostics.Stopwatch.StartNew (); var res = partcount(6666); sw.Stop(); Console.Write("{0} {1} ms", fmt(res), sw.Elapsed.TotalMilliseconds); } }
from itertools import islice def posd(): "diff between position numbers. 1, 2, 3... interleaved with 3, 5, 7..." count, odd = 1, 3 while True: yield count yield odd count, odd = count + 1, odd + 2 def pos_gen(): "position numbers. 1 3 2 5 7 4 9 ..." val = 1 diff = posd() while True: yield val val += next(diff) def plus_minus(): "yield (list_offset, sign) or zero for Partition calc" n, sign = 0, [1, 1] p_gen = pos_gen() out_on = next(p_gen) while True: n += 1 if n == out_on: next_sign = sign.pop(0) if not sign: sign = [-next_sign] * 2 yield -n, next_sign out_on = next(p_gen) else: yield 0 def part(n): "Partition numbers" p = [1] p_m = plus_minus() mods = [] for _ in range(n): next_plus_minus = next(p_m) if next_plus_minus: mods.append(next_plus_minus) p.append(sum(p[offset] * sign for offset, sign in mods)) return p[-1] print("(Intermediaries):") print(" posd:", list(islice(posd(), 10))) print(" pos_gen:", list(islice(pos_gen(), 10))) print(" plus_minus:", list(islice(plus_minus(), 15))) print("\nPartitions:", [part(x) for x in range(15)])
Change the programming language of this snippet from C# to Python without modifying what it does.
using System; using static System.Console; using LI = System.Collections.Generic.SortedSet<int>; class Program { static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) { if (lft == 0) res.Add(vlu); else if (lft > 0) foreach (int itm in set) res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul); return res; } static void Main(string[] args) { WriteLine(string.Join(" ", unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); } }
from collections import deque def prime_digits_sum(r): q = deque([(r, 0)]) while q: r, n = q.popleft() for d in 2, 3, 5, 7: if d >= r: if d == r: yield n + d break q.append((r - d, (n + d) * 10)) print(*prime_digits_sum(13))
Generate a Python translation of this C# snippet without changing its computational steps.
using System; using static System.Console; using LI = System.Collections.Generic.SortedSet<int>; class Program { static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) { if (lft == 0) res.Add(vlu); else if (lft > 0) foreach (int itm in set) res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul); return res; } static void Main(string[] args) { WriteLine(string.Join(" ", unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); } }
from collections import deque def prime_digits_sum(r): q = deque([(r, 0)]) while q: r, n = q.popleft() for d in 2, 3, 5, 7: if d >= r: if d == r: yield n + d break q.append((r - d, (n + d) * 10)) print(*prime_digits_sum(13))
Generate a Python translation of this C# snippet without changing its computational steps.
using System; using static System.Console; using LI = System.Collections.Generic.SortedSet<int>; class Program { static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) { if (lft == 0) res.Add(vlu); else if (lft > 0) foreach (int itm in set) res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul); return res; } static void Main(string[] args) { WriteLine(string.Join(" ", unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); } }
from collections import deque def prime_digits_sum(r): q = deque([(r, 0)]) while q: r, n = q.popleft() for d in 2, 3, 5, 7: if d >= r: if d == r: yield n + d break q.append((r - d, (n + d) * 10)) print(*prime_digits_sum(13))
Can you help me rewrite this code in Python instead of C#, keeping it the same logically?
using System; using System.IO; using System.Text; namespace RosettaCode { internal class Program { private const string FileName = "NOTES.TXT"; private static void Main(string[] args) { if (args.Length==0) { string txt = File.ReadAllText(FileName); Console.WriteLine(txt); } else { var sb = new StringBuilder(); sb.Append(DateTime.Now).Append("\n\t"); foreach (string s in args) sb.Append(s).Append(" "); sb.Append("\n"); if (File.Exists(FileName)) File.AppendAllText(FileName, sb.ToString()); else File.WriteAllText(FileName, sb.ToString()); } } } }
import sys, datetime, shutil if len(sys.argv) == 1: try: with open('notes.txt', 'r') as f: shutil.copyfileobj(f, sys.stdout) except IOError: pass else: with open('notes.txt', 'a') as f: f.write(datetime.datetime.now().isoformat() + '\n') f.write("\t%s\n" % ' '.join(sys.argv[1:]))
Generate a Python translation of this C# snippet without changing its computational steps.
using System; public static class Angles { public static void Main() => Print(-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 6399, 1_000_000); public static void Print(params double[] angles) { string[] names = { "Degrees", "Gradians", "Mils", "Radians" }; Func<double, double> rnd = a => Math.Round(a, 4); Func<double, double>[] normal = { NormalizeDeg, NormalizeGrad, NormalizeMil, NormalizeRad }; Func<double, double>[,] convert = { { a => a, DegToGrad, DegToMil, DegToRad }, { GradToDeg, a => a, GradToMil, GradToRad }, { MilToDeg, MilToGrad, a => a, MilToRad }, { RadToDeg, RadToGrad, RadToMil, a => a } }; Console.WriteLine($@"{"Angle",-12}{"Normalized",-12}{"Unit",-12}{ "Degrees",-12}{"Gradians",-12}{"Mils",-12}{"Radians",-12}"); foreach (double angle in angles) { for (int i = 0; i < 4; i++) { double nAngle = normal[i](angle); Console.WriteLine($@"{ rnd(angle),-12}{ rnd(nAngle),-12}{ names[i],-12}{ rnd(convert[i, 0](nAngle)),-12}{ rnd(convert[i, 1](nAngle)),-12}{ rnd(convert[i, 2](nAngle)),-12}{ rnd(convert[i, 3](nAngle)),-12}"); } } } public static double NormalizeDeg(double angle) => Normalize(angle, 360); public static double NormalizeGrad(double angle) => Normalize(angle, 400); public static double NormalizeMil(double angle) => Normalize(angle, 6400); public static double NormalizeRad(double angle) => Normalize(angle, 2 * Math.PI); private static double Normalize(double angle, double N) { while (angle <= -N) angle += N; while (angle >= N) angle -= N; return angle; } public static double DegToGrad(double angle) => angle * 10 / 9; public static double DegToMil(double angle) => angle * 160 / 9; public static double DegToRad(double angle) => angle * Math.PI / 180; public static double GradToDeg(double angle) => angle * 9 / 10; public static double GradToMil(double angle) => angle * 16; public static double GradToRad(double angle) => angle * Math.PI / 200; public static double MilToDeg(double angle) => angle * 9 / 160; public static double MilToGrad(double angle) => angle / 16; public static double MilToRad(double angle) => angle * Math.PI / 3200; public static double RadToDeg(double angle) => angle * 180 / Math.PI; public static double RadToGrad(double angle) => angle * 200 / Math.PI; public static double RadToMil(double angle) => angle * 3200 / Math.PI; }
PI = 3.141592653589793 TWO_PI = 6.283185307179586 def normalize2deg(a): while a < 0: a += 360 while a >= 360: a -= 360 return a def normalize2grad(a): while a < 0: a += 400 while a >= 400: a -= 400 return a def normalize2mil(a): while a < 0: a += 6400 while a >= 6400: a -= 6400 return a def normalize2rad(a): while a < 0: a += TWO_PI while a >= TWO_PI: a -= TWO_PI return a def deg2grad(a): return a * 10.0 / 9.0 def deg2mil(a): return a * 160.0 / 9.0 def deg2rad(a): return a * PI / 180.0 def grad2deg(a): return a * 9.0 / 10.0 def grad2mil(a): return a * 16.0 def grad2rad(a): return a * PI / 200.0 def mil2deg(a): return a * 9.0 / 160.0 def mil2grad(a): return a / 16.0 def mil2rad(a): return a * PI / 3200.0 def rad2deg(a): return a * 180.0 / PI def rad2grad(a): return a * 200.0 / PI def rad2mil(a): return a * 3200.0 / PI
Keep all operations the same but rewrite the snippet in Python.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RosettaCodeTasks { class Program { static void Main ( string[ ] args ) { FindCommonDirectoryPath.Test ( ); } } class FindCommonDirectoryPath { public static void Test ( ) { Console.WriteLine ( "Find Common Directory Path" ); Console.WriteLine ( ); List<string> PathSet1 = new List<string> ( ); PathSet1.Add ( "/home/user1/tmp/coverage/test" ); PathSet1.Add ( "/home/user1/tmp/covert/operator" ); PathSet1.Add ( "/home/user1/tmp/coven/members" ); Console.WriteLine("Path Set 1 (All Absolute Paths):"); foreach ( string path in PathSet1 ) { Console.WriteLine ( path ); } Console.WriteLine ( "Path Set 1 Common Path: {0}", FindCommonPath ( "/", PathSet1 ) ); } public static string FindCommonPath ( string Separator, List<string> Paths ) { string CommonPath = String.Empty; List<string> SeparatedPath = Paths .First ( str => str.Length == Paths.Max ( st2 => st2.Length ) ) .Split ( new string[ ] { Separator }, StringSplitOptions.RemoveEmptyEntries ) .ToList ( ); foreach ( string PathSegment in SeparatedPath.AsEnumerable ( ) ) { if ( CommonPath.Length == 0 && Paths.All ( str => str.StartsWith ( PathSegment ) ) ) { CommonPath = PathSegment; } else if ( Paths.All ( str => str.StartsWith ( CommonPath + Separator + PathSegment ) ) ) { CommonPath += Separator + PathSegment; } else { break; } } return CommonPath; } } }
>>> import os >>> os.path.commonpath(['/home/user1/tmp/coverage/test', '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members']) '/home/user1/tmp'
Please provide an equivalent version of this C# code in Python.
using System; using System.Collections.Generic; namespace RecamanSequence { class Program { static void Main(string[] args) { List<int> a = new List<int>() { 0 }; HashSet<int> used = new HashSet<int>() { 0 }; HashSet<int> used1000 = new HashSet<int>() { 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.Count < 1001) { int next = a[n - 1] - n; if (next < 1 || used.Contains(next)) { next += 2 * n; } bool alreadyUsed = used.Contains(next); a.Add(next); if (!alreadyUsed) { used.Add(next); if (0 <= next && next <= 1000) { used1000.Add(next); } } if (n == 14) { Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a)); } if (!foundDup && alreadyUsed) { Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next); foundDup = true; } if (used1000.Count == 1001) { Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n); } n++; } } } }
from itertools import islice class Recamans(): "Recamán's sequence generator callable class" def __init__(self): self.a = None self.n = None def __call__(self): "Recamán's sequence generator" nxt = 0 a, n = {nxt}, 0 self.a = a self.n = n yield nxt while True: an1, n = nxt, n + 1 nxt = an1 - n if nxt < 0 or nxt in a: nxt = an1 + n a.add(nxt) self.n = n yield nxt if __name__ == '__main__': recamans = Recamans() print("First fifteen members of Recamans sequence:", list(islice(recamans(), 15))) so_far = set() for term in recamans(): if term in so_far: print(f"First duplicate number in series is: a({recamans.n}) = {term}") break so_far.add(term) n = 1_000 setn = set(range(n + 1)) for _ in recamans(): if setn.issubset(recamans.a): print(f"Range 0 ..{n} is covered by terms up to a({recamans.n})") break
Convert the following code from C# to Python, ensuring the logic remains intact.
using System; using System.Collections.Generic; namespace RecamanSequence { class Program { static void Main(string[] args) { List<int> a = new List<int>() { 0 }; HashSet<int> used = new HashSet<int>() { 0 }; HashSet<int> used1000 = new HashSet<int>() { 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.Count < 1001) { int next = a[n - 1] - n; if (next < 1 || used.Contains(next)) { next += 2 * n; } bool alreadyUsed = used.Contains(next); a.Add(next); if (!alreadyUsed) { used.Add(next); if (0 <= next && next <= 1000) { used1000.Add(next); } } if (n == 14) { Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a)); } if (!foundDup && alreadyUsed) { Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next); foundDup = true; } if (used1000.Count == 1001) { Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n); } n++; } } } }
from itertools import islice class Recamans(): "Recamán's sequence generator callable class" def __init__(self): self.a = None self.n = None def __call__(self): "Recamán's sequence generator" nxt = 0 a, n = {nxt}, 0 self.a = a self.n = n yield nxt while True: an1, n = nxt, n + 1 nxt = an1 - n if nxt < 0 or nxt in a: nxt = an1 + n a.add(nxt) self.n = n yield nxt if __name__ == '__main__': recamans = Recamans() print("First fifteen members of Recamans sequence:", list(islice(recamans(), 15))) so_far = set() for term in recamans(): if term in so_far: print(f"First duplicate number in series is: a({recamans.n}) = {term}") break so_far.add(term) n = 1_000 setn = set(range(n + 1)) for _ in recamans(): if setn.issubset(recamans.a): print(f"Range 0 ..{n} is covered by terms up to a({recamans.n})") break
Convert this C# snippet to Python and keep its semantics consistent.
using System; using System.Runtime.InteropServices; public unsafe class Program { public static unsafe void HeapMemory() { const int HEAP_ZERO_MEMORY = 0x00000008; const int size = 1000; int ph = GetProcessHeap(); void* pointer = HeapAlloc(ph, HEAP_ZERO_MEMORY, size); if (pointer == null) throw new OutOfMemoryException(); Console.WriteLine(HeapSize(ph, 0, pointer)); HeapFree(ph, 0, pointer); } public static unsafe void StackMemory() { byte* buffer = stackalloc byte[1000]; } public static void Main(string[] args) { HeapMemory(); StackMemory(); } [DllImport("kernel32")] static extern void* HeapAlloc(int hHeap, int flags, int size); [DllImport("kernel32")] static extern bool HeapFree(int hHeap, int flags, void* block); [DllImport("kernel32")] static extern int GetProcessHeap(); [DllImport("kernel32")] static extern int HeapSize(int hHeap, int flags, void* block); }
>>> from array import array >>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \u2641'), ('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])] >>> for typecode, initializer in argslist: a = array(typecode, initializer) print a del a array('l') array('c', 'hello world') array('u', u'hello \u2641') array('l', [1, 2, 3, 4, 5]) array('d', [1.0, 2.0, 3.1400000000000001]) >>>
Translate the given C# code snippet into Python without altering its behavior.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RosettaTicTacToe { class Program { static string[][] Players = new string[][] { new string[] { "COMPUTER", "X" }, new string[] { "HUMAN", "O" } }; const int Unplayed = -1; const int Computer = 0; const int Human = 1; static int[] GameBoard = new int[9]; static int[] corners = new int[] { 0, 2, 6, 8 }; static int[][] wins = new int[][] { new int[] { 0, 1, 2 }, new int[] { 3, 4, 5 }, new int[] { 6, 7, 8 }, new int[] { 0, 3, 6 }, new int[] { 1, 4, 7 }, new int[] { 2, 5, 8 }, new int[] { 0, 4, 8 }, new int[] { 2, 4, 6 } }; static void Main(string[] args) { while (true) { Console.Clear(); Console.WriteLine("Welcome to Rosetta Code Tic-Tac-Toe for C#."); initializeGameBoard(); displayGameBoard(); int currentPlayer = rnd.Next(0, 2); Console.WriteLine("The first move goes to {0} who is playing {1}s.\n", playerName(currentPlayer), playerToken(currentPlayer)); while (true) { int thisMove = getMoveFor(currentPlayer); if (thisMove == Unplayed) { Console.WriteLine("{0}, you've quit the game ... am I that good?", playerName(currentPlayer)); break; } playMove(thisMove, currentPlayer); displayGameBoard(); if (isGameWon()) { Console.WriteLine("{0} has won the game!", playerName(currentPlayer)); break; } else if (isGameTied()) { Console.WriteLine("Cat game ... we have a tie."); break; } currentPlayer = getNextPlayer(currentPlayer); } if (!playAgain()) return; } } static int getMoveFor(int player) { if (player == Human) return getManualMove(player); else { int selectedMove = getSemiRandomMove(player); Console.WriteLine("{0} selects position {1}.", playerName(player), selectedMove + 1); return selectedMove; } } static int getManualMove(int player) { while (true) { Console.Write("{0}, enter you move (number): ", playerName(player)); ConsoleKeyInfo keyInfo = Console.ReadKey(); Console.WriteLine(); if (keyInfo.Key == ConsoleKey.Escape) return Unplayed; if (keyInfo.Key >= ConsoleKey.D1 && keyInfo.Key <= ConsoleKey.D9) { int move = keyInfo.KeyChar - '1'; if (GameBoard[move] == Unplayed) return move; else Console.WriteLine("Spot {0} is already taken, please select again.", move + 1); } else Console.WriteLine("Illegal move, please select again.\n"); } } static int getRandomMove(int player) { int movesLeft = GameBoard.Count(position => position == Unplayed); int x = rnd.Next(0, movesLeft); for (int i = 0; i < GameBoard.Length; i++) { if (GameBoard[i] == Unplayed && x < 0) return i; x--; } return Unplayed; } static int getSemiRandomMove(int player) { int posToPlay; if (checkForWinningMove(player, out posToPlay)) return posToPlay; if (checkForBlockingMove(player, out posToPlay)) return posToPlay; return getRandomMove(player); } static int getBestMove(int player) { return -1; } static bool checkForWinningMove(int player, out int posToPlay) { posToPlay = Unplayed; foreach (var line in wins) if (twoOfThreeMatchPlayer(player, line, out posToPlay)) return true; return false; } static bool checkForBlockingMove(int player, out int posToPlay) { posToPlay = Unplayed; foreach (var line in wins) if (twoOfThreeMatchPlayer(getNextPlayer(player), line, out posToPlay)) return true; return false; } static bool twoOfThreeMatchPlayer(int player, int[] line, out int posToPlay) { int cnt = 0; posToPlay = int.MinValue; foreach (int pos in line) { if (GameBoard[pos] == player) cnt++; else if (GameBoard[pos] == Unplayed) posToPlay = pos; } return cnt == 2 && posToPlay >= 0; } static void playMove(int boardPosition, int player) { GameBoard[boardPosition] = player; } static bool isGameWon() { return wins.Any(line => takenBySamePlayer(line[0], line[1], line[2])); } static bool takenBySamePlayer(int a, int b, int c) { return GameBoard[a] != Unplayed && GameBoard[a] == GameBoard[b] && GameBoard[a] == GameBoard[c]; } static bool isGameTied() { return !GameBoard.Any(spot => spot == Unplayed); } static Random rnd = new Random(); static void initializeGameBoard() { for (int i = 0; i < GameBoard.Length; i++) GameBoard[i] = Unplayed; } static string playerName(int player) { return Players[player][0]; } static string playerToken(int player) { return Players[player][1]; } static int getNextPlayer(int player) { return (player + 1) % 2; } static void displayGameBoard() { Console.WriteLine(" {0} | {1} | {2}", pieceAt(0), pieceAt(1), pieceAt(2)); Console.WriteLine("---|---|---"); Console.WriteLine(" {0} | {1} | {2}", pieceAt(3), pieceAt(4), pieceAt(5)); Console.WriteLine("---|---|---"); Console.WriteLine(" {0} | {1} | {2}", pieceAt(6), pieceAt(7), pieceAt(8)); Console.WriteLine(); } static string pieceAt(int boardPosition) { if (GameBoard[boardPosition] == Unplayed) return (boardPosition + 1).ToString(); return playerToken(GameBoard[boardPosition]); } private static bool playAgain() { Console.WriteLine("\nDo you want to play again?"); return Console.ReadKey(false).Key == ConsoleKey.Y; } } }
import random board = list('123456789') wins = ((0,1,2), (3,4,5), (6,7,8), (0,3,6), (1,4,7), (2,5,8), (0,4,8), (2,4,6)) def printboard(): print('\n'.join(' '.join(board[x:x+3]) for x in(0,3,6))) def score(): for w in wins: b = board[w[0]] if b in 'XO' and all (board[i] == b for i in w): return b, [i+1 for i in w] return None, None def finished(): return all (b in 'XO' for b in board) def space(): return [ b for b in board if b not in 'XO'] def my_turn(xo): options = space() choice = random.choice(options) board[int(choice)-1] = xo return choice def your_turn(xo): options = space() while True: choice = input(" Put your %s in any of these positions: %s " % (xo, ''.join(options))).strip() if choice in options: break print( "Whoops I don't understand the input" ) board[int(choice)-1] = xo return choice def me(xo='X'): printboard() print('I go at', my_turn(xo)) return score() assert not s[0], "\n%s wins across %s" % s def you(xo='O'): printboard() print('You went at', your_turn(xo)) return score() assert not s[0], "\n%s wins across %s" % s print(__doc__) while not finished(): s = me('X') if s[0]: printboard() print("\n%s wins across %s" % s) break if not finished(): s = you('O') if s[0]: printboard() print("\n%s wins across %s" % s) break else: print('\nA draw')
Change the programming language of this snippet from C# to Python without modifying what it does.
using System; using System.Numerics; class Program { static void Main() { BigInteger i = 1; while (true) { Console.WriteLine(i++); } } }
i=1 while i: print(i) i += 1
Port the provided C# code into Python while preserving the original functionality.
using System; using System.Numerics; class Program { static void Main() { BigInteger i = 1; while (true) { Console.WriteLine(i++); } } }
i=1 while i: print(i) i += 1
Keep all operations the same but rewrite the snippet in Python.
private string LookupDns(string s) { try { System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s); string result = ip.AddressList[0].ToString(); for (int i = 1; i < ip.AddressList.Length; ++i) result += ", " + ip.AddressList[i].ToString(); return result; } catch (System.Net.Sockets.SocketException se) { return se.Message; } }
>>> import socket >>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80)) >>> for ip in ips: print ip ... 2001:200:dff:fff1:216:3eff:feb1:44d7 203.178.141.194
Change the following C# code into Python without altering its purpose.
private string LookupDns(string s) { try { System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s); string result = ip.AddressList[0].ToString(); for (int i = 1; i < ip.AddressList.Length; ++i) result += ", " + ip.AddressList[i].ToString(); return result; } catch (System.Net.Sockets.SocketException se) { return se.Message; } }
>>> import socket >>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80)) >>> for ip in ips: print ip ... 2001:200:dff:fff1:216:3eff:feb1:44d7 203.178.141.194
Can you help me rewrite this code in Python instead of C#, keeping it the same logically?
using System; public class SevenSidedDice { Random random = new Random(); static void Main(string[] args) { SevenSidedDice sevenDice = new SevenSidedDice(); Console.WriteLine("Random number from 1 to 7: "+ sevenDice.seven()); Console.Read(); } int seven() { int v=21; while(v>20) v=five()+five()*5-6; return 1+v%7; } int five() { return 1 + random.Next(5); } }
from random import randint def dice5(): return randint(1, 5) def dice7(): r = dice5() + dice5() * 5 - 6 return (r % 7) + 1 if r < 21 else dice7()
Write the same code in Python as shown below in C#.
class Program { static void Main(string[] args) { Console.WriteLine("Enter two integers. Space delimited please: "); string s = Console.ReadLine(); int[,] myArray=new int[(int)s[0],(int)s[2]]; myArray[0, 0] = 2; Console.WriteLine(myArray[0, 0]); Console.ReadLine(); } }
width = int(raw_input("Width of myarray: ")) height = int(raw_input("Height of Array: ")) myarray = [[0] * width for i in range(height)] myarray[0][0] = 3.5 print (myarray[0][0])
Convert this C# snippet to Python and keep its semantics consistent.
using System; using System.Linq; namespace ChineseRemainderTheorem { class Program { static void Main(string[] args) { int[] n = { 3, 5, 7 }; int[] a = { 2, 3, 2 }; int result = ChineseRemainderTheorem.Solve(n, a); int counter = 0; int maxCount = n.Length - 1; while (counter <= maxCount) { Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})"); counter++; } } } public static class ChineseRemainderTheorem { public static int Solve(int[] n, int[] a) { int prod = n.Aggregate(1, (i, j) => i * j); int p; int sm = 0; for (int i = 0; i < n.Length; i++) { p = prod / n[i]; sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p; } return sm % prod; } private static int ModularMultiplicativeInverse(int a, int mod) { int b = a % mod; for (int x = 1; x < mod; x++) { if ((b * x) % mod == 1) { return x; } } return 1; } } }
def chinese_remainder(n, a): sum = 0 prod = reduce(lambda a, b: a*b, n) for n_i, a_i in zip(n, a): p = prod / n_i sum += a_i * mul_inv(p, n_i) * p return sum % prod def mul_inv(a, b): b0 = b x0, x1 = 0, 1 if b == 1: return 1 while a > 1: q = a / b a, b = b, a%b x0, x1 = x1 - q * x0, x0 if x1 < 0: x1 += b0 return x1 if __name__ == '__main__': n = [3, 5, 7] a = [2, 3, 2] print chinese_remainder(n, a)
Can you help me rewrite this code in VB instead of Java, keeping it the same logically?
module BitwiseOps { @Inject Console console; void run() { for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF]) { static String hex(Int64 n) { return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString(); } console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}): | {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)} | {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)} | {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)} | NOT {hex(n1)} = {hex(~n1)} | left shift {hex(n1)} by {n2} = {hex(n1 << n2)} | right shift {hex(n1)} by {n2} = {hex(n1 >> n2)} | right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)} | left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))} | right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))} | leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)} | rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)} | leading zero count of {hex(n1)} = {n1.leadingZeroCount} | trailing zero count of {hex(n1)} = {n1.trailingZeroCount} | bit count (aka "population") of {hex(n1)} = {n1.bitCount} | reversed bits of {hex(n1)} = {hex(n1.reverseBits())} | reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())} | ); } } }
Debug.Print Hex(&HF0F0 And &HFF00) Debug.Print Hex(&HF0F0 Or &HFF00) Debug.Print Hex(&HF0F0 Xor &HFF00) Debug.Print Hex(Not &HF0F0) Debug.Print Hex(&HF0F0 Eqv &HFF00) Debug.Print Hex(&HF0F0 Imp &HFF00)
Translate this program into VB but keep the logic exactly as in Java.
import java.awt.Color; import java.awt.Graphics; import java.util.*; import javax.swing.JFrame; public class DragonCurve extends JFrame { private List<Integer> turns; private double startingAngle, side; public DragonCurve(int iter) { super("Dragon Curve"); setBounds(100, 100, 800, 600); setDefaultCloseOperation(EXIT_ON_CLOSE); turns = getSequence(iter); startingAngle = -iter * (Math.PI / 4); side = 400 / Math.pow(2, iter / 2.); } public List<Integer> getSequence(int iterations) { List<Integer> turnSequence = new ArrayList<Integer>(); for (int i = 0; i < iterations; i++) { List<Integer> copy = new ArrayList<Integer>(turnSequence); Collections.reverse(copy); turnSequence.add(1); for (Integer turn : copy) { turnSequence.add(-turn); } } return turnSequence; } @Override public void paint(Graphics g) { g.setColor(Color.BLACK); double angle = startingAngle; int x1 = 230, y1 = 350; int x2 = x1 + (int) (Math.cos(angle) * side); int y2 = y1 + (int) (Math.sin(angle) * side); g.drawLine(x1, y1, x2, y2); x1 = x2; y1 = y2; for (Integer turn : turns) { angle += turn * (Math.PI / 2); x2 = x1 + (int) (Math.cos(angle) * side); y2 = y1 + (int) (Math.sin(angle) * side); g.drawLine(x1, y1, x2, y2); x1 = x2; y1 = y2; } } public static void main(String[] args) { new DragonCurve(14).setVisible(true); } }
option explicit const pi180= 0.01745329251994329576923690768489 const pi=3.1415926535897932384626433832795 class turtle dim fso dim fn dim svg dim iang dim ori dim incr dim pdown dim clr dim x dim y public property let orient(n):ori = n*pi180 :end property public property let iangle(n):iang= n*pi180 :end property public sub pd() : pdown=true: end sub public sub pu() :pdown=FALSE :end sub public sub rt(i) ori=ori - i*iang: end sub public sub lt(i): ori=(ori + i*iang) end sub public sub bw(l) x= x+ cos(ori+pi)*l*incr y= y+ sin(ori+pi)*l*incr end sub public sub fw(l) dim x1,y1 x1=x + cos(ori)*l*incr y1=y + sin(ori)*l*incr if pdown then line x,y,x1,y1 x=x1:y=y1 end sub Private Sub Class_Initialize() setlocale "us" initsvg x=400:y=400:incr=100 ori=90*pi180 iang=90*pi180 clr=0 pdown=true end sub Private Sub Class_Terminate() disply end sub private sub line (x,y,x1,y1) svg.WriteLine "<line x1=""" & x & """ y1= """& y & """ x2=""" & x1& """ y2=""" & y1 & """/>" end sub private sub disply() dim shell svg.WriteLine "</svg></body></html>" svg.close Set shell = CreateObject("Shell.Application") shell.ShellExecute fn,1,False end sub private sub initsvg() dim scriptpath Set fso = CreateObject ("Scripting.Filesystemobject") ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\")) fn=Scriptpath & "SIERP.HTML" Set svg = fso.CreateTextFile(fn,True) if SVG IS nothing then wscript.echo "Can svg.WriteLine "<!DOCTYPE html>" &vbcrlf & "<html>" &vbcrlf & "<head>" svg.writeline "<style>" & vbcrlf & "line {stroke:rgb(255,0,0);stroke-width:.5}" &vbcrlf &"</style>" svg.writeline "</head>"&vbcrlf & "<body>" svg.WriteLine "<svg xmlns=""http://www.w3.org/2000/svg"" width=""800"" height=""800"" viewBox=""0 0 800 800"">" end sub end class sub dragon(st,le,dir) if st=0 then x.fw le: exit sub x.rt dir dragon st-1, le/1.41421 ,1 x.rt dir*2 dragon st-1, le/1.41421 ,-1 x.rt dir end sub dim x set x=new turtle x.iangle=45 x.orient=45 x.incr=1 x.x=200:x.y=200 dragon 12,300,1 set x=nothing
Generate a VB translation of this Java snippet without changing its computational steps.
import java.io.BufferedReader; import java.io.FileReader; public class ReadFileByLines { private static void processLine(int lineNo, String line) { } public static void main(String[] args) { for (String filename : args) { BufferedReader br = null; FileReader fr = null; try { fr = new FileReader(filename); br = new BufferedReader(fr); String line; int lineNo = 0; while ((line = br.readLine()) != null) { processLine(++lineNo, line); } } catch (Exception x) { x.printStackTrace(); } finally { if (fr != null) { try {br.close();} catch (Exception ignoreMe) {} try {fr.close();} catch (Exception ignoreMe) {} } } } } }
$Include "Rapidq.inc" dim file as qfilestream if file.open("c:\A Test.txt", fmOpenRead) then while not File.eof print File.readline wend else print "Cannot read file" end if input "Press enter to exit: ";a$
Convert the following code from Java to VB, ensuring the logic remains intact.
import java.util.LinkedList; @SuppressWarnings("serial") public class DoublyLinkedListInsertion<T> extends LinkedList<T> { public static void main(String[] args) { DoublyLinkedListInsertion<String> list = new DoublyLinkedListInsertion<String>(); list.addFirst("Add First 1"); list.addFirst("Add First 2"); list.addFirst("Add First 3"); list.addFirst("Add First 4"); list.addFirst("Add First 5"); traverseList(list); list.addAfter("Add First 3", "Add New"); traverseList(list); } public void addAfter(T after, T element) { int index = indexOf(after); if ( index >= 0 ) { add(index + 1, element); } else { addLast(element); } } private static void traverseList(LinkedList<String> list) { System.out.println("Traverse List:"); for ( int i = 0 ; i < list.size() ; i++ ) { System.out.printf("Element number %d - Element value = '%s'%n", i, list.get(i)); } System.out.println(); } }
Public Sub Insert(ByVal a As Node(Of T), ByVal b As Node(Of T), ByVal c As T) Dim node As New Node(Of T)(value) a.Next = node node.Previous = a b.Previous = node node.Next = b End Sub
Generate a VB translation of this Java snippet without changing its computational steps.
import java.util.Random; public class QuickSelect { private static <E extends Comparable<? super E>> int partition(E[] arr, int left, int right, int pivot) { E pivotVal = arr[pivot]; swap(arr, pivot, right); int storeIndex = left; for (int i = left; i < right; i++) { if (arr[i].compareTo(pivotVal) < 0) { swap(arr, i, storeIndex); storeIndex++; } } swap(arr, right, storeIndex); return storeIndex; } private static <E extends Comparable<? super E>> E select(E[] arr, int n) { int left = 0; int right = arr.length - 1; Random rand = new Random(); while (right >= left) { int pivotIndex = partition(arr, left, right, rand.nextInt(right - left + 1) + left); if (pivotIndex == n) { return arr[pivotIndex]; } else if (pivotIndex < n) { left = pivotIndex + 1; } else { right = pivotIndex - 1; } } return null; } private static void swap(Object[] arr, int i1, int i2) { if (i1 != i2) { Object temp = arr[i1]; arr[i1] = arr[i2]; arr[i2] = temp; } } public static void main(String[] args) { for (int i = 0; i < 10; i++) { Integer[] input = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}; System.out.print(select(input, i)); if (i < 9) System.out.print(", "); } System.out.println(); } }
Dim s As Variant Private Function quick_select(ByRef s As Variant, k As Integer) As Integer Dim left As Integer, right As Integer, pos As Integer Dim pivotValue As Integer, tmp As Integer left = 1: right = UBound(s) Do While left < right pivotValue = s(k) tmp = s(k) s(k) = s(right) s(right) = tmp pos = left For i = left To right If s(i) < pivotValue Then tmp = s(i) s(i) = s(pos) s(pos) = tmp pos = pos + 1 End If Next i tmp = s(right) s(right) = s(pos) s(pos) = tmp If pos = k Then Exit Do End If If pos < k Then left = pos + 1 Else right = pos - 1 End If Loop quick_select = s(k) End Function Public Sub main() Dim r As Integer, i As Integer s = [{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}] For i = 1 To 10 r = quick_select(s, i) Debug.Print IIf(i < 10, r & ", ", "" & r); Next i End Sub
Please provide an equivalent version of this Java code in VB.
public static long backToTen(String num, int oldBase){ return Long.parseLong(num, oldBase); } public static String tenToBase(long num, int newBase){ return Long.toString(num, newBase); }
Private Function to_base(ByVal number As Long, base As Integer) As String Dim digits As String, result As String Dim i As Integer, digit As Integer digits = "0123456789abcdefghijklmnopqrstuvwxyz" Do While number > 0 digit = number Mod base result = Mid(digits, digit + 1, 1) & result number = number \ base Loop to_base = result End Function Private Function from_base(number As String, base As Integer) As Long Dim digits As String, result As Long Dim i As Integer digits = "0123456789abcdefghijklmnopqrstuvwxyz" result = Val(InStr(1, digits, Mid(number, 1, 1), vbTextCompare) - 1) For i = 2 To Len(number) result = result * base + Val(InStr(1, digits, Mid(number, i, 1), vbTextCompare) - 1) Next i from_base = result End Function Public Sub Non_decimal_radices_Convert() Debug.Print "26 decimal in base 16 is: "; to_base(26, 16); ". Conversely, hexadecimal 1a in decimal is: "; from_base("1a", 16) End Sub