Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Write the same code in Python as shown below in C++.
#include <iostream> #include <vector> template<typename T> T sum_below_diagonal(const std::vector<std::vector<T>>& matrix) { T sum = 0; for (std::size_t y = 0; y < matrix.size(); y++) for (std::size_t x = 0; x < matrix[y].size() && x < y; x++) sum += matrix[y][x]; return sum; } int main() { std::vector<std::vector<int>> matrix = { {1,3,7,8,10}, {2,4,16,14,4}, {3,1,9,18,11}, {12,14,17,18,20}, {7,1,3,9,5} }; std::cout << sum_below_diagonal(matrix) << std::endl; return 0; }
from numpy import array, tril, sum A = [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]] print(sum(tril(A, -1)))
Rewrite the snippet below in Python so it works the same as the original C++ code.
#include <iostream> #include <fstream> int main( int argc, char **argv ){ if( argc <= 1 ){ std::cerr << "Usage: "<<argv[0]<<" [infile]" << std::endl; return -1; } std::ifstream input(argv[1]); if(!input.good()){ std::cerr << "Error opening '"<<argv[1]<<"'. Bailing out." << std::endl; return -1; } std::string line, name, content; while( std::getline( input, line ).good() ){ if( line.empty() || line[0] == '>' ){ if( !name.empty() ){ std::cout << name << " : " << content << std::endl; name.clear(); } if( !line.empty() ){ name = line.substr(1); } content.clear(); } else if( !name.empty() ){ if( line.find(' ') != std::string::npos ){ name.clear(); content.clear(); } else { content += line; } } } if( !name.empty() ){ std::cout << name << " : " << content << std::endl; } return 0; }
import io FASTA= infile = io.StringIO(FASTA) def fasta_parse(infile): key = '' for line in infile: if line.startswith('>'): if key: yield key, val key, val = line[1:].rstrip().split()[0], '' elif key: val += line.rstrip() if key: yield key, val print('\n'.join('%s: %s' % keyval for keyval in fasta_parse(infile)))
Ensure the translated Python code behaves exactly like the original C++ snippet.
#include <bitset> #include <stdio.h> #define SIZE 80 #define RULE 30 #define RULE_TEST(x) (RULE & 1 << (7 & (x))) void evolve(std::bitset<SIZE> &s) { int i; std::bitset<SIZE> t(0); t[SIZE-1] = RULE_TEST( s[0] << 2 | s[SIZE-1] << 1 | s[SIZE-2] ); t[ 0] = RULE_TEST( s[1] << 2 | s[ 0] << 1 | s[SIZE-1] ); for (i = 1; i < SIZE-1; i++) t[i] = RULE_TEST( s[i+1] << 2 | s[i] << 1 | s[i-1] ); for (i = 0; i < SIZE; i++) s[i] = t[i]; } void show(std::bitset<SIZE> s) { int i; for (i = SIZE; i--; ) printf("%c", s[i] ? '#' : ' '); printf("|\n"); } unsigned char byte(std::bitset<SIZE> &s) { unsigned char b = 0; int i; for (i=8; i--; ) { b |= s[0] << i; evolve(s); } return b; } int main() { int i; std::bitset<SIZE> state(1); for (i=10; i--; ) printf("%u%c", byte(state), i ? ' ' : '\n'); return 0; }
from elementary_cellular_automaton import eca, eca_wrap def rule30bytes(lencells=100): cells = '1' + '0' * (lencells - 1) gen = eca(cells, 30) while True: yield int(''.join(next(gen)[0] for i in range(8)), 2) if __name__ == '__main__': print([b for i,b in zip(range(10), rule30bytes())])
Rewrite this program in Python while keeping its functionality equivalent to the C++ version.
#include <array> #include <iostream> class PCG32 { private: const uint64_t N = 6364136223846793005; uint64_t state = 0x853c49e6748fea9b; uint64_t inc = 0xda3e39cb94b95bdb; public: uint32_t nextInt() { uint64_t old = state; state = old * N + inc; uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27); uint32_t rot = old >> 59; return (shifted >> rot) | (shifted << ((~rot + 1) & 31)); } double nextFloat() { return ((double)nextInt()) / (1LL << 32); } void seed(uint64_t seed_state, uint64_t seed_sequence) { state = 0; inc = (seed_sequence << 1) | 1; nextInt(); state = state + seed_state; nextInt(); } }; int main() { auto r = new PCG32(); r->seed(42, 54); std::cout << r->nextInt() << '\n'; std::cout << r->nextInt() << '\n'; std::cout << r->nextInt() << '\n'; std::cout << r->nextInt() << '\n'; std::cout << r->nextInt() << '\n'; std::cout << '\n'; std::array<int, 5> counts{ 0, 0, 0, 0, 0 }; r->seed(987654321, 1); for (size_t i = 0; i < 100000; i++) { int j = (int)floor(r->nextFloat() * 5.0); counts[j]++; } std::cout << "The counts for 100,000 repetitions are:\n"; for (size_t i = 0; i < counts.size(); i++) { std::cout << " " << i << " : " << counts[i] << '\n'; } return 0; }
mask64 = (1 << 64) - 1 mask32 = (1 << 32) - 1 CONST = 6364136223846793005 class PCG32(): def __init__(self, seed_state=None, seed_sequence=None): if all(type(x) == int for x in (seed_state, seed_sequence)): self.seed(seed_state, seed_sequence) else: self.state = self.inc = 0 def seed(self, seed_state, seed_sequence): self.state = 0 self.inc = ((seed_sequence << 1) | 1) & mask64 self.next_int() self.state = (self.state + seed_state) self.next_int() def next_int(self): "return random 32 bit unsigned int" old = self.state self.state = ((old * CONST) + self.inc) & mask64 xorshifted = (((old >> 18) ^ old) >> 27) & mask32 rot = (old >> 59) & mask32 answer = (xorshifted >> rot) | (xorshifted << ((-rot) & 31)) answer = answer &mask32 return answer def next_float(self): "return random float between 0 and 1" return self.next_int() / (1 << 32) if __name__ == '__main__': random_gen = PCG32() random_gen.seed(42, 54) for i in range(5): print(random_gen.next_int()) random_gen.seed(987654321, 1) hist = {i:0 for i in range(5)} for i in range(100_000): hist[int(random_gen.next_float() *5)] += 1 print(hist)
Keep all operations the same but rewrite the snippet in Python.
#include <iomanip> #include <iostream> #define _USE_MATH_DEFINES #include <math.h> constexpr double degrees(double deg) { const double tau = 2.0 * M_PI; return deg * tau / 360.0; } const double part_ratio = 2.0 * cos(degrees(72)); const double side_ratio = 1.0 / (part_ratio + 2.0); struct Point { double x, y; friend std::ostream& operator<<(std::ostream& os, const Point& p); }; std::ostream& operator<<(std::ostream& os, const Point& p) { auto f(std::cout.flags()); os << std::setprecision(3) << std::fixed << p.x << ',' << p.y << ' '; std::cout.flags(f); return os; } struct Turtle { private: Point pos; double theta; bool tracing; public: Turtle() : theta(0.0), tracing(false) { pos.x = 0.0; pos.y = 0.0; } Turtle(double x, double y) : theta(0.0), tracing(false) { pos.x = x; pos.y = y; } Point position() { return pos; } void position(const Point& p) { pos = p; } double heading() { return theta; } void heading(double angle) { theta = angle; } void forward(double dist) { auto dx = dist * cos(theta); auto dy = dist * sin(theta); pos.x += dx; pos.y += dy; if (tracing) { std::cout << pos; } } void right(double angle) { theta -= angle; } void begin_fill() { if (!tracing) { std::cout << "<polygon points=\""; tracing = true; } } void end_fill() { if (tracing) { std::cout << "\"/>\n"; tracing = false; } } }; void pentagon(Turtle& turtle, double size) { turtle.right(degrees(36)); turtle.begin_fill(); for (size_t i = 0; i < 5; i++) { turtle.forward(size); turtle.right(degrees(72)); } turtle.end_fill(); } void sierpinski(int order, Turtle& turtle, double size) { turtle.heading(0.0); auto new_size = size * side_ratio; if (order-- > 1) { for (size_t j = 0; j < 4; j++) { turtle.right(degrees(36)); double small = size * side_ratio / part_ratio; auto distList = { small, size, size, small }; auto dist = *(distList.begin() + j); Turtle spawn{ turtle.position().x, turtle.position().y }; spawn.heading(turtle.heading()); spawn.forward(dist); sierpinski(order, spawn, new_size); } sierpinski(order, turtle, new_size); } else { pentagon(turtle, size); } if (order > 0) { std::cout << '\n'; } } int main() { const int order = 5; double size = 500; Turtle turtle{ size / 2.0, size }; std::cout << "<?xml version=\"1.0\" standalone=\"no\"?>\n"; std::cout << "<!DOCTYPE svg PUBLIC \" - std::cout << " \"http: std::cout << "<svg height=\"" << size << "\" width=\"" << size << "\" style=\"fill:blue\" transform=\"translate(" << size / 2 << ", " << size / 2 << ") rotate(-36)\"\n"; std::cout << " version=\"1.1\" xmlns=\"http: size *= part_ratio; sierpinski(order, turtle, size); std::cout << "</svg>"; }
from turtle import * import math speed(0) hideturtle() part_ratio = 2 * math.cos(math.radians(72)) side_ratio = 1 / (part_ratio + 2) hide_turtles = True path_color = "black" fill_color = "black" def pentagon(t, s): t.color(path_color, fill_color) t.pendown() t.right(36) t.begin_fill() for i in range(5): t.forward(s) t.right(72) t.end_fill() def sierpinski(i, t, s): t.setheading(0) new_size = s * side_ratio if i > 1: i -= 1 for j in range(4): t.right(36) short = s * side_ratio / part_ratio dist = [short, s, s, short][j] spawn = Turtle() if hide_turtles:spawn.hideturtle() spawn.penup() spawn.setposition(t.position()) spawn.setheading(t.heading()) spawn.forward(dist) sierpinski(i, spawn, new_size) sierpinski(i, t, new_size) else: pentagon(t, s) del t def main(): t = Turtle() t.hideturtle() t.penup() screen = t.getscreen() y = screen.window_height() t.goto(0, y/2-20) i = 5 size = 300 size *= part_ratio sierpinski(i, t, size) main()
Produce a language-to-language conversion: from C++ to Python, same semantics.
#include <iomanip> #include <iostream> #define _USE_MATH_DEFINES #include <math.h> constexpr double degrees(double deg) { const double tau = 2.0 * M_PI; return deg * tau / 360.0; } const double part_ratio = 2.0 * cos(degrees(72)); const double side_ratio = 1.0 / (part_ratio + 2.0); struct Point { double x, y; friend std::ostream& operator<<(std::ostream& os, const Point& p); }; std::ostream& operator<<(std::ostream& os, const Point& p) { auto f(std::cout.flags()); os << std::setprecision(3) << std::fixed << p.x << ',' << p.y << ' '; std::cout.flags(f); return os; } struct Turtle { private: Point pos; double theta; bool tracing; public: Turtle() : theta(0.0), tracing(false) { pos.x = 0.0; pos.y = 0.0; } Turtle(double x, double y) : theta(0.0), tracing(false) { pos.x = x; pos.y = y; } Point position() { return pos; } void position(const Point& p) { pos = p; } double heading() { return theta; } void heading(double angle) { theta = angle; } void forward(double dist) { auto dx = dist * cos(theta); auto dy = dist * sin(theta); pos.x += dx; pos.y += dy; if (tracing) { std::cout << pos; } } void right(double angle) { theta -= angle; } void begin_fill() { if (!tracing) { std::cout << "<polygon points=\""; tracing = true; } } void end_fill() { if (tracing) { std::cout << "\"/>\n"; tracing = false; } } }; void pentagon(Turtle& turtle, double size) { turtle.right(degrees(36)); turtle.begin_fill(); for (size_t i = 0; i < 5; i++) { turtle.forward(size); turtle.right(degrees(72)); } turtle.end_fill(); } void sierpinski(int order, Turtle& turtle, double size) { turtle.heading(0.0); auto new_size = size * side_ratio; if (order-- > 1) { for (size_t j = 0; j < 4; j++) { turtle.right(degrees(36)); double small = size * side_ratio / part_ratio; auto distList = { small, size, size, small }; auto dist = *(distList.begin() + j); Turtle spawn{ turtle.position().x, turtle.position().y }; spawn.heading(turtle.heading()); spawn.forward(dist); sierpinski(order, spawn, new_size); } sierpinski(order, turtle, new_size); } else { pentagon(turtle, size); } if (order > 0) { std::cout << '\n'; } } int main() { const int order = 5; double size = 500; Turtle turtle{ size / 2.0, size }; std::cout << "<?xml version=\"1.0\" standalone=\"no\"?>\n"; std::cout << "<!DOCTYPE svg PUBLIC \" - std::cout << " \"http: std::cout << "<svg height=\"" << size << "\" width=\"" << size << "\" style=\"fill:blue\" transform=\"translate(" << size / 2 << ", " << size / 2 << ") rotate(-36)\"\n"; std::cout << " version=\"1.1\" xmlns=\"http: size *= part_ratio; sierpinski(order, turtle, size); std::cout << "</svg>"; }
from turtle import * import math speed(0) hideturtle() part_ratio = 2 * math.cos(math.radians(72)) side_ratio = 1 / (part_ratio + 2) hide_turtles = True path_color = "black" fill_color = "black" def pentagon(t, s): t.color(path_color, fill_color) t.pendown() t.right(36) t.begin_fill() for i in range(5): t.forward(s) t.right(72) t.end_fill() def sierpinski(i, t, s): t.setheading(0) new_size = s * side_ratio if i > 1: i -= 1 for j in range(4): t.right(36) short = s * side_ratio / part_ratio dist = [short, s, s, short][j] spawn = Turtle() if hide_turtles:spawn.hideturtle() spawn.penup() spawn.setposition(t.position()) spawn.setheading(t.heading()) spawn.forward(dist) sierpinski(i, spawn, new_size) sierpinski(i, t, new_size) else: pentagon(t, s) del t def main(): t = Turtle() t.hideturtle() t.penup() screen = t.getscreen() y = screen.window_height() t.goto(0, y/2-20) i = 5 size = 300 size *= part_ratio sierpinski(i, t, size) main()
Preserve the algorithm and functionality while converting the code from C++ to Python.
#include <string> #include <vector> #include <boost/regex.hpp> bool is_repstring( const std::string & teststring , std::string & repunit ) { std::string regex( "^(.+)\\1+(.*)$" ) ; boost::regex e ( regex ) ; boost::smatch what ; if ( boost::regex_match( teststring , what , e , boost::match_extra ) ) { std::string firstbracket( what[1 ] ) ; std::string secondbracket( what[ 2 ] ) ; if ( firstbracket.length( ) >= secondbracket.length( ) && firstbracket.find( secondbracket ) != std::string::npos ) { repunit = firstbracket ; } } return !repunit.empty( ) ; } int main( ) { std::vector<std::string> teststrings { "1001110011" , "1110111011" , "0010010010" , "1010101010" , "1111111111" , "0100101101" , "0100100" , "101" , "11" , "00" , "1" } ; std::string theRep ; for ( std::string myString : teststrings ) { if ( is_repstring( myString , theRep ) ) { std::cout << myString << " is a rep string! Here is a repeating string:\n" ; std::cout << theRep << " " ; } else { std::cout << myString << " is no rep string!" ; } theRep.clear( ) ; std::cout << std::endl ; } return 0 ; }
def is_repeated(text): 'check if the first part of the string is repeated throughout the string' for x in range(len(text)//2, 0, -1): if text.startswith(text[x:]): return x return 0 matchstr = for line in matchstr.split(): ln = is_repeated(line) print('%r has a repetition length of %i i.e. %s' % (line, ln, repr(line[:ln]) if ln else '*not* a rep-string'))
Rewrite the snippet below in Python so it works the same as the original C++ code.
auto strA = R"(this is a newline-separated raw string)";
'c' == "c" 'text' == "text" ' " ' " ' " '\x20' == ' ' u'unicode string' u'\u05d0'
Rewrite this program in Python while keeping its functionality equivalent to the C++ version.
#include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <string> #include <vector> int hamming_distance(const std::string& str1, const std::string& str2) { size_t len1 = str1.size(); size_t len2 = str2.size(); if (len1 != len2) return 0; int count = 0; for (size_t i = 0; i < len1; ++i) { if (str1[i] != str2[i]) ++count; if (count == 2) break; } return count; } int main(int argc, char** argv) { const char* filename(argc < 2 ? "unixdict.txt" : argv[1]); std::ifstream in(filename); if (!in) { std::cerr << "Cannot open file '" << filename << "'.\n"; return EXIT_FAILURE; } std::string line; std::vector<std::string> dictionary; while (getline(in, line)) { if (line.size() > 11) dictionary.push_back(line); } std::cout << "Changeable words in " << filename << ":\n"; int n = 1; for (const std::string& word1 : dictionary) { for (const std::string& word2 : dictionary) { if (hamming_distance(word1, word2) == 1) std::cout << std::setw(2) << std::right << n++ << ": " << std::setw(14) << std::left << word1 << " -> " << word2 << '\n'; } } return EXIT_SUCCESS; }
from collections import defaultdict, Counter def getwords(minlength=11, fname='unixdict.txt'): "Return set of lowercased words of > given number of characters" with open(fname) as f: words = f.read().strip().lower().split() return {w for w in words if len(w) > minlength} words11 = getwords() word_minus_1 = defaultdict(list) minus_1_to_word = defaultdict(list) for w in words11: for i in range(len(w)): minus_1 = w[:i] + w[i+1:] word_minus_1[minus_1].append((w, i)) if minus_1 in words11: minus_1_to_word[minus_1].append(w) cwords = set() for _, v in word_minus_1.items(): if len(v) >1: change_indices = Counter(i for wrd, i in v) change_words = set(wrd for wrd, i in v) words_changed = None if len(change_words) > 1 and change_indices.most_common(1)[0][1] > 1: words_changed = [wrd for wrd, i in v if change_indices[i] > 1] if words_changed: cwords.add(tuple(sorted(words_changed))) print(f"{len(minus_1_to_word)} words that are from deleting a char from other words:") for k, v in sorted(minus_1_to_word.items()): print(f" {k:12} From {', '.join(v)}") print(f"\n{len(cwords)} words that are from changing a char from other words:") for v in sorted(cwords): print(f" {v[0]:12} From {', '.join(v[1:])}")
Change the following C++ code into Python without altering its purpose.
#include <iostream> #include <vector> using namespace std; template <typename T> auto operator>>(const vector<T>& monad, auto f) { vector<remove_reference_t<decltype(f(monad.front()).front())>> result; for(auto& item : monad) { const auto r = f(item); result.insert(result.end(), begin(r), end(r)); } return result; } auto Pure(auto t) { return vector{t}; } auto Double(int i) { return Pure(2 * i); } auto Increment(int i) { return Pure(i + 1); } auto NiceNumber(int i) { return Pure(to_string(i) + " is a nice number\n"); } auto UpperSequence = [](auto startingVal) { const int MaxValue = 500; vector<decltype(startingVal)> sequence; while(startingVal <= MaxValue) sequence.push_back(startingVal++); return sequence; }; void PrintVector(const auto& vec) { cout << " "; for(auto value : vec) { cout << value << " "; } cout << "\n"; } void PrintTriples(const auto& vec) { cout << "Pythagorean triples:\n"; for(auto it = vec.begin(); it != vec.end();) { auto x = *it++; auto y = *it++; auto z = *it++; cout << x << ", " << y << ", " << z << "\n"; } cout << "\n"; } int main() { auto listMonad = vector<int> {2, 3, 4} >> Increment >> Double >> NiceNumber; PrintVector(listMonad); auto pythagoreanTriples = UpperSequence(1) >> [](int x){return UpperSequence(x) >> [x](int y){return UpperSequence(y) >> [x, y](int z){return (x*x + y*y == z*z) ? vector{x, y, z} : vector<int>{};};};}; PrintTriples(pythagoreanTriples); }
from __future__ import annotations from itertools import chain from typing import Any from typing import Callable from typing import Iterable from typing import List from typing import TypeVar T = TypeVar("T") class MList(List[T]): @classmethod def unit(cls, value: Iterable[T]) -> MList[T]: return cls(value) def bind(self, func: Callable[[T], MList[Any]]) -> MList[Any]: return MList(chain.from_iterable(map(func, self))) def __rshift__(self, func: Callable[[T], MList[Any]]) -> MList[Any]: return self.bind(func) if __name__ == "__main__": print( MList([1, 99, 4]) .bind(lambda val: MList([val + 1])) .bind(lambda val: MList([f"${val}.00"])) ) print( MList([1, 99, 4]) >> (lambda val: MList([val + 1])) >> (lambda val: MList([f"${val}.00"])) ) print( MList(range(1, 6)).bind( lambda x: MList(range(6, 11)).bind(lambda y: MList([(x, y)])) ) ) print( MList(range(1, 26)).bind( lambda x: MList(range(x + 1, 26)).bind( lambda y: MList(range(y + 1, 26)).bind( lambda z: MList([(x, y, z)]) if x * x + y * y == z * z else MList([]) ) ) ) )
Port the provided C++ code into Python while preserving the original functionality.
#include <cmath> #include <cstdint> #include <iostream> #include <functional> uint64_t factorial(int n) { uint64_t result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; } int inverse_factorial(uint64_t f) { int p = 1; int i = 1; if (f == 1) { return 0; } while (p < f) { p *= i; i++; } if (p == f) { return i - 1; } return -1; } uint64_t super_factorial(int n) { uint64_t result = 1; for (int i = 1; i <= n; i++) { result *= factorial(i); } return result; } uint64_t hyper_factorial(int n) { uint64_t result = 1; for (int i = 1; i <= n; i++) { result *= (uint64_t)powl(i, i); } return result; } uint64_t alternating_factorial(int n) { uint64_t result = 0; for (int i = 1; i <= n; i++) { if ((n - i) % 2 == 0) { result += factorial(i); } else { result -= factorial(i); } } return result; } uint64_t exponential_factorial(int n) { uint64_t result = 0; for (int i = 1; i <= n; i++) { result = (uint64_t)powl(i, (long double)result); } return result; } void test_factorial(int count, std::function<uint64_t(int)> func, const std::string &name) { std::cout << "First " << count << ' ' << name << '\n'; for (int i = 0; i < count; i++) { std::cout << func(i) << ' '; } std::cout << '\n'; } void test_inverse(uint64_t f) { int n = inverse_factorial(f); if (n < 0) { std::cout << "rf(" << f << ") = No Solution\n"; } else { std::cout << "rf(" << f << ") = " << n << '\n'; } } int main() { test_factorial(9, super_factorial, "super factorials"); std::cout << '\n'; test_factorial(8, hyper_factorial, "hyper factorials"); std::cout << '\n'; test_factorial(10, alternating_factorial, "alternating factorials"); std::cout << '\n'; test_factorial(5, exponential_factorial, "exponential factorials"); std::cout << '\n'; test_inverse(1); test_inverse(2); test_inverse(6); test_inverse(24); test_inverse(120); test_inverse(720); test_inverse(5040); test_inverse(40320); test_inverse(362880); test_inverse(3628800); test_inverse(119); return 0; }
from math import prod def superFactorial(n): return prod([prod(range(1,i+1)) for i in range(1,n+1)]) def hyperFactorial(n): return prod([i**i for i in range(1,n+1)]) def alternatingFactorial(n): return sum([(-1)**(n-i)*prod(range(1,i+1)) for i in range(1,n+1)]) def exponentialFactorial(n): if n in [0,1]: return 1 else: return n**exponentialFactorial(n-1) def inverseFactorial(n): i = 1 while True: if n == prod(range(1,i)): return i-1 elif n < prod(range(1,i)): return "undefined" i+=1 print("Superfactorials for [0,9] :") print({"sf(" + str(i) + ") " : superFactorial(i) for i in range(0,10)}) print("\nHyperfactorials for [0,9] :") print({"H(" + str(i) + ") " : hyperFactorial(i) for i in range(0,10)}) print("\nAlternating factorials for [0,9] :") print({"af(" + str(i) + ") " : alternatingFactorial(i) for i in range(0,10)}) print("\nExponential factorials for [0,4] :") print({str(i) + "$ " : exponentialFactorial(i) for i in range(0,5)}) print("\nDigits in 5$ : " , len(str(exponentialFactorial(5)))) factorialSet = [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800] print("\nInverse factorials for " , factorialSet) print({"rf(" + str(i) + ") ":inverseFactorial(i) for i in factorialSet}) print("\nrf(119) : " + inverseFactorial(119))
Write the same algorithm in Python as shown in this C++ implementation.
#include <iostream> #include <string> #include <cctype> #include <cstdint> typedef std::uint64_t integer; const char* small[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; const char* tens[] = { "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; struct named_number { const char* name_; integer number_; }; const named_number named_numbers[] = { { "hundred", 100 }, { "thousand", 1000 }, { "million", 1000000 }, { "billion", 1000000000 }, { "trillion", 1000000000000 }, { "quadrillion", 1000000000000000ULL }, { "quintillion", 1000000000000000000ULL } }; const named_number& get_named_number(integer n) { constexpr size_t names_len = std::size(named_numbers); for (size_t i = 0; i + 1 < names_len; ++i) { if (n < named_numbers[i + 1].number_) return named_numbers[i]; } return named_numbers[names_len - 1]; } std::string cardinal(integer n) { std::string result; if (n < 20) result = small[n]; else if (n < 100) { result = tens[n/10 - 2]; if (n % 10 != 0) { result += "-"; result += small[n % 10]; } } else { const named_number& num = get_named_number(n); integer p = num.number_; result = cardinal(n/p); result += " "; result += num.name_; if (n % p != 0) { result += " "; result += cardinal(n % p); } } return result; } inline char uppercase(char ch) { return static_cast<char>(std::toupper(static_cast<unsigned char>(ch))); } std::string magic(integer n) { std::string result; for (unsigned int i = 0; ; ++i) { std::string text(cardinal(n)); if (i == 0) text[0] = uppercase(text[0]); result += text; if (n == 4) { result += " is magic."; break; } integer len = text.length(); result += " is "; result += cardinal(len); result += ", "; n = len; } return result; } void test_magic(integer n) { std::cout << magic(n) << '\n'; } int main() { test_magic(5); test_magic(13); test_magic(78); test_magic(797); test_magic(2739); test_magic(4000); test_magic(7893); test_magic(93497412); test_magic(2673497412U); test_magic(10344658531277200972ULL); return 0; }
import random from collections import OrderedDict numbers = { 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen', 20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty', 90: 'ninety', 100: 'hundred', 1000: 'thousand', 10 ** 6: 'million', 10 ** 9: 'billion', 10 ** 12: 'trillion', 10 ** 15: 'quadrillion', 10 ** 18: 'quintillion', 10 ** 21: 'sextillion', 10 ** 24: 'septillion', 10 ** 27: 'octillion', 10 ** 30: 'nonillion', 10 ** 33: 'decillion', 10 ** 36: 'undecillion', 10 ** 39: 'duodecillion', 10 ** 42: 'tredecillion', 10 ** 45: 'quattuordecillion', 10 ** 48: 'quinquadecillion', 10 ** 51: 'sedecillion', 10 ** 54: 'septendecillion', 10 ** 57: 'octodecillion', 10 ** 60: 'novendecillion', 10 ** 63: 'vigintillion', 10 ** 66: 'unvigintillion', 10 ** 69: 'duovigintillion', 10 ** 72: 'tresvigintillion', 10 ** 75: 'quattuorvigintillion', 10 ** 78: 'quinquavigintillion', 10 ** 81: 'sesvigintillion', 10 ** 84: 'septemvigintillion', 10 ** 87: 'octovigintillion', 10 ** 90: 'novemvigintillion', 10 ** 93: 'trigintillion', 10 ** 96: 'untrigintillion', 10 ** 99: 'duotrigintillion', 10 ** 102: 'trestrigintillion', 10 ** 105: 'quattuortrigintillion', 10 ** 108: 'quinquatrigintillion', 10 ** 111: 'sestrigintillion', 10 ** 114: 'septentrigintillion', 10 ** 117: 'octotrigintillion', 10 ** 120: 'noventrigintillion', 10 ** 123: 'quadragintillion', 10 ** 153: 'quinquagintillion', 10 ** 183: 'sexagintillion', 10 ** 213: 'septuagintillion', 10 ** 243: 'octogintillion', 10 ** 273: 'nonagintillion', 10 ** 303: 'centillion', 10 ** 306: 'uncentillion', 10 ** 309: 'duocentillion', 10 ** 312: 'trescentillion', 10 ** 333: 'decicentillion', 10 ** 336: 'undecicentillion', 10 ** 363: 'viginticentillion', 10 ** 366: 'unviginticentillion', 10 ** 393: 'trigintacentillion', 10 ** 423: 'quadragintacentillion', 10 ** 453: 'quinquagintacentillion', 10 ** 483: 'sexagintacentillion', 10 ** 513: 'septuagintacentillion', 10 ** 543: 'octogintacentillion', 10 ** 573: 'nonagintacentillion', 10 ** 603: 'ducentillion', 10 ** 903: 'trecentillion', 10 ** 1203: 'quadringentillion', 10 ** 1503: 'quingentillion', 10 ** 1803: 'sescentillion', 10 ** 2103: 'septingentillion', 10 ** 2403: 'octingentillion', 10 ** 2703: 'nongentillion', 10 ** 3003: 'millinillion' } numbers = OrderedDict(sorted(numbers.items(), key=lambda t: t[0], reverse=True)) def string_representation(i: int) -> str: if i == 0: return 'zero' words = ['negative'] if i < 0 else [] working_copy = abs(i) for key, value in numbers.items(): if key <= working_copy: times = int(working_copy / key) if key >= 100: words.append(string_representation(times)) words.append(value) working_copy -= times * key if working_copy == 0: break return ' '.join(words) def next_phrase(i: int): while not i == 4: str_i = string_representation(i) len_i = len(str_i) yield str_i, 'is', string_representation(len_i) i = len_i yield string_representation(i), 'is', 'magic' def magic(i: int) -> str: phrases = [] for phrase in next_phrase(i): phrases.append(' '.join(phrase)) return f'{", ".join(phrases)}.'.capitalize() if __name__ == '__main__': for j in (random.randint(0, 10 ** 3) for i in range(5)): print(j, ':\n', magic(j), '\n') for j in (random.randint(-10 ** 24, 10 ** 24) for i in range(2)): print(j, ':\n', magic(j), '\n')
Convert the following code from C++ to Python, ensuring the logic remains intact.
#include <iomanip> #include <iostream> #include <sstream> int findNumOfDec(double x) { std::stringstream ss; ss << std::fixed << std::setprecision(14) << x; auto s = ss.str(); auto pos = s.find('.'); if (pos == std::string::npos) { return 0; } auto tail = s.find_last_not_of('0'); return tail - pos; } void test(double x) { std::cout << x << " has " << findNumOfDec(x) << " decimals\n"; } int main() { test(12.0); test(12.345); test(12.345555555555); test(12.3450); test(12.34555555555555555555); test(1.2345e+54); return 0; }
In [6]: def dec(n): ...: return len(n.rsplit('.')[-1]) if '.' in n else 0 In [7]: dec('12.345') Out[7]: 3 In [8]: dec('12.3450') Out[8]: 4 In [9]:
Can you help me rewrite this code in Python instead of C++, keeping it the same logically?
enum fruits { apple, banana, cherry }; enum fruits { apple = 0, banana = 1, cherry = 2 };
>>> from enum import Enum >>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE') >>> Contact.__members__ mappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)])) >>> >>> >>> class Contact2(Enum): FIRST_NAME = 1 LAST_NAME = 2 PHONE = 3 >>> Contact2.__members__ mappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)])) >>>
Write a version of this C++ function in Python with identical behavior.
#include <boost/asio/ip/address.hpp> #include <cstdint> #include <iostream> #include <iomanip> #include <limits> #include <string> using boost::asio::ip::address; using boost::asio::ip::address_v4; using boost::asio::ip::address_v6; using boost::asio::ip::make_address; using boost::asio::ip::make_address_v4; using boost::asio::ip::make_address_v6; template<typename uint> bool parse_int(const std::string& str, int base, uint& n) { try { size_t pos = 0; unsigned long u = stoul(str, &pos, base); if (pos != str.length() || u > std::numeric_limits<uint>::max()) return false; n = static_cast<uint>(u); return true; } catch (const std::exception& ex) { return false; } } void parse_ip_address_and_port(const std::string& input, address& addr, uint16_t& port) { size_t pos = input.rfind(':'); if (pos != std::string::npos && pos > 1 && pos + 1 < input.length() && parse_int(input.substr(pos + 1), 10, port) && port > 0) { if (input[0] == '[' && input[pos - 1] == ']') { addr = make_address_v6(input.substr(1, pos - 2)); return; } else { try { addr = make_address_v4(input.substr(0, pos)); return; } catch (const std::exception& ex) { } } } port = 0; addr = make_address(input); } void print_address_and_port(const address& addr, uint16_t port) { std::cout << std::hex << std::uppercase << std::setfill('0'); if (addr.is_v4()) { address_v4 addr4 = addr.to_v4(); std::cout << "address family: IPv4\n"; std::cout << "address number: " << std::setw(8) << addr4.to_uint() << '\n'; } else if (addr.is_v6()) { address_v6 addr6 = addr.to_v6(); address_v6::bytes_type bytes(addr6.to_bytes()); std::cout << "address family: IPv6\n"; std::cout << "address number: "; for (unsigned char byte : bytes) std::cout << std::setw(2) << static_cast<unsigned int>(byte); std::cout << '\n'; } if (port != 0) std::cout << "port: " << std::dec << port << '\n'; else std::cout << "port not specified\n"; } void test(const std::string& input) { std::cout << "input: " << input << '\n'; try { address addr; uint16_t port = 0; parse_ip_address_and_port(input, addr, port); print_address_and_port(addr, port); } catch (const std::exception& ex) { std::cout << "parsing failed\n"; } std::cout << '\n'; } int main(int argc, char** argv) { test("127.0.0.1"); test("127.0.0.1:80"); test("::ffff:127.0.0.1"); test("::1"); test("[::1]:80"); test("1::80"); test("2605:2700:0:3::4713:93e3"); test("[2605:2700:0:3::4713:93e3]:80"); return 0; }
from ipaddress import ip_address from urllib.parse import urlparse tests = [ "127.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", "::192.168.0.1", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80" ] def parse_ip_port(netloc): try: ip = ip_address(netloc) port = None except ValueError: parsed = urlparse('//{}'.format(netloc)) ip = ip_address(parsed.hostname) port = parsed.port return ip, port for address in tests: ip, port = parse_ip_port(address) hex_ip = {4:'{:08X}', 6:'{:032X}'}[ip.version].format(int(ip)) print("{:39s} {:>32s} IPv{} port={}".format( str(ip), hex_ip, ip.version, port ))
Produce a functionally identical Python code for the snippet given in C++.
#include <fstream> #include <iostream> #include <unordered_map> #include <vector> struct Textonym_Checker { private: int total; int elements; int textonyms; int max_found; std::vector<std::string> max_strings; std::unordered_map<std::string, std::vector<std::string>> values; int get_mapping(std::string &result, const std::string &input) { static std::unordered_map<char, char> mapping = { {'A', '2'}, {'B', '2'}, {'C', '2'}, {'D', '3'}, {'E', '3'}, {'F', '3'}, {'G', '4'}, {'H', '4'}, {'I', '4'}, {'J', '5'}, {'K', '5'}, {'L', '5'}, {'M', '6'}, {'N', '6'}, {'O', '6'}, {'P', '7'}, {'Q', '7'}, {'R', '7'}, {'S', '7'}, {'T', '8'}, {'U', '8'}, {'V', '8'}, {'W', '9'}, {'X', '9'}, {'Y', '9'}, {'Z', '9'} }; result = input; for (char &c : result) { if (!isalnum(c)) return 0; if (isalpha(c)) c = mapping[toupper(c)]; } return 1; } public: Textonym_Checker() : total(0), elements(0), textonyms(0), max_found(0) { } ~Textonym_Checker() { } void add(const std::string &str) { std::string mapping; total++; if (!get_mapping(mapping, str)) return; const int num_strings = values[mapping].size(); if (num_strings == 1) textonyms++; elements++; if (num_strings > max_found) { max_strings.clear(); max_strings.push_back(mapping); max_found = num_strings; } else if (num_strings == max_found) max_strings.push_back(mapping); values[mapping].push_back(str); } void results(const std::string &filename) { std::cout << "Read " << total << " words from " << filename << "\n\n"; std::cout << "There are " << elements << " words in " << filename; std::cout << " which can be represented by the digit key mapping.\n"; std::cout << "They require " << values.size() << " digit combinations to represent them.\n"; std::cout << textonyms << " digit combinations represent Textonyms.\n\n"; std::cout << "The numbers mapping to the most words map to "; std::cout << max_found + 1 << " words each:\n"; for (auto it1 : max_strings) { std::cout << '\t' << it1 << " maps to: "; for (auto it2 : values[it1]) std::cout << it2 << " "; std::cout << '\n'; } std::cout << '\n'; } void match(const std::string &str) { auto match = values.find(str); if (match == values.end()) { std::cout << "Key '" << str << "' not found\n"; } else { std::cout << "Key '" << str << "' matches: "; for (auto it : values[str]) std::cout << it << " "; std::cout << '\n'; } } }; int main() { auto filename = "unixdict.txt"; std::ifstream input(filename); Textonym_Checker tc; if (input.is_open()) { std::string line; while (getline(input, line)) tc.add(line); } input.close(); tc.results(filename); tc.match("001"); tc.match("228"); tc.match("27484247"); tc.match("7244967473642"); }
from collections import defaultdict import urllib.request CH2NUM = {ch: str(num) for num, chars in enumerate('abc def ghi jkl mno pqrs tuv wxyz'.split(), 2) for ch in chars} URL = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt' def getwords(url): return urllib.request.urlopen(url).read().decode("utf-8").lower().split() def mapnum2words(words): number2words = defaultdict(list) reject = 0 for word in words: try: number2words[''.join(CH2NUM[ch] for ch in word)].append(word) except KeyError: reject += 1 return dict(number2words), reject def interactiveconversions(): global inp, ch, num while True: inp = input("\nType a number or a word to get the translation and textonyms: ").strip().lower() if inp: if all(ch in '23456789' for ch in inp): if inp in num2words: print(" Number {0} has the following textonyms in the dictionary: {1}".format(inp, ', '.join( num2words[inp]))) else: print(" Number {0} has no textonyms in the dictionary.".format(inp)) elif all(ch in CH2NUM for ch in inp): num = ''.join(CH2NUM[ch] for ch in inp) print(" Word {0} is{1} in the dictionary and is number {2} with textonyms: {3}".format( inp, ('' if inp in wordset else "n't"), num, ', '.join(num2words[num]))) else: print(" I don't understand %r" % inp) else: print("Thank you") break if __name__ == '__main__': words = getwords(URL) print("Read %i words from %r" % (len(words), URL)) wordset = set(words) num2words, reject = mapnum2words(words) morethan1word = sum(1 for w in num2words if len(num2words[w]) > 1) maxwordpernum = max(len(values) for values in num2words.values()) print(.format(len(words) - reject, URL, len(num2words), morethan1word)) print("\nThe numbers mapping to the most words map to %i words each:" % maxwordpernum) maxwpn = sorted((key, val) for key, val in num2words.items() if len(val) == maxwordpernum) for num, wrds in maxwpn: print(" %s maps to: %s" % (num, ', '.join(wrds))) interactiveconversions()
Convert the following code from C++ to Python, ensuring the logic remains intact.
#include <list> #include <algorithm> #include <iostream> class point { public: point( int a = 0, int b = 0 ) { x = a; y = b; } bool operator ==( const point& o ) { return o.x == x && o.y == y; } point operator +( const point& o ) { return point( o.x + x, o.y + y ); } int x, y; }; class map { public: map() { char t[8][8] = { {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 1, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0} }; w = h = 8; for( int r = 0; r < h; r++ ) for( int s = 0; s < w; s++ ) m[s][r] = t[r][s]; } int operator() ( int x, int y ) { return m[x][y]; } char m[8][8]; int w, h; }; class node { public: bool operator == (const node& o ) { return pos == o.pos; } bool operator == (const point& o ) { return pos == o; } bool operator < (const node& o ) { return dist + cost < o.dist + o.cost; } point pos, parent; int dist, cost; }; class aStar { public: aStar() { neighbours[0] = point( -1, -1 ); neighbours[1] = point( 1, -1 ); neighbours[2] = point( -1, 1 ); neighbours[3] = point( 1, 1 ); neighbours[4] = point( 0, -1 ); neighbours[5] = point( -1, 0 ); neighbours[6] = point( 0, 1 ); neighbours[7] = point( 1, 0 ); } int calcDist( point& p ){ int x = end.x - p.x, y = end.y - p.y; return( x * x + y * y ); } bool isValid( point& p ) { return ( p.x >-1 && p.y > -1 && p.x < m.w && p.y < m.h ); } bool existPoint( point& p, int cost ) { std::list<node>::iterator i; i = std::find( closed.begin(), closed.end(), p ); if( i != closed.end() ) { if( ( *i ).cost + ( *i ).dist < cost ) return true; else { closed.erase( i ); return false; } } i = std::find( open.begin(), open.end(), p ); if( i != open.end() ) { if( ( *i ).cost + ( *i ).dist < cost ) return true; else { open.erase( i ); return false; } } return false; } bool fillOpen( node& n ) { int stepCost, nc, dist; point neighbour; for( int x = 0; x < 8; x++ ) { stepCost = x < 4 ? 1 : 1; neighbour = n.pos + neighbours[x]; if( neighbour == end ) return true; if( isValid( neighbour ) && m( neighbour.x, neighbour.y ) != 1 ) { nc = stepCost + n.cost; dist = calcDist( neighbour ); if( !existPoint( neighbour, nc + dist ) ) { node m; m.cost = nc; m.dist = dist; m.pos = neighbour; m.parent = n.pos; open.push_back( m ); } } } return false; } bool search( point& s, point& e, map& mp ) { node n; end = e; start = s; m = mp; n.cost = 0; n.pos = s; n.parent = 0; n.dist = calcDist( s ); open.push_back( n ); while( !open.empty() ) { node n = open.front(); open.pop_front(); closed.push_back( n ); if( fillOpen( n ) ) return true; } return false; } int path( std::list<point>& path ) { path.push_front( end ); int cost = 1 + closed.back().cost; path.push_front( closed.back().pos ); point parent = closed.back().parent; for( std::list<node>::reverse_iterator i = closed.rbegin(); i != closed.rend(); i++ ) { if( ( *i ).pos == parent && !( ( *i ).pos == start ) ) { path.push_front( ( *i ).pos ); parent = ( *i ).parent; } } path.push_front( start ); return cost; } map m; point end, start; point neighbours[8]; std::list<node> open; std::list<node> closed; }; int main( int argc, char* argv[] ) { map m; point s, e( 7, 7 ); aStar as; if( as.search( s, e, m ) ) { std::list<point> path; int c = as.path( path ); for( int y = -1; y < 9; y++ ) { for( int x = -1; x < 9; x++ ) { if( x < 0 || y < 0 || x > 7 || y > 7 || m( x, y ) == 1 ) std::cout << char(0xdb); else { if( std::find( path.begin(), path.end(), point( x, y ) )!= path.end() ) std::cout << "x"; else std::cout << "."; } } std::cout << "\n"; } std::cout << "\nPath cost " << c << ": "; for( std::list<point>::iterator i = path.begin(); i != path.end(); i++ ) { std::cout<< "(" << ( *i ).x << ", " << ( *i ).y << ") "; } } std::cout << "\n\n"; return 0; }
from __future__ import print_function import matplotlib.pyplot as plt class AStarGraph(object): def __init__(self): self.barriers = [] self.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)]) def heuristic(self, start, goal): D = 1 D2 = 1 dx = abs(start[0] - goal[0]) dy = abs(start[1] - goal[1]) return D * (dx + dy) + (D2 - 2 * D) * min(dx, dy) def get_vertex_neighbours(self, pos): n = [] for dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]: x2 = pos[0] + dx y2 = pos[1] + dy if x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7: continue n.append((x2, y2)) return n def move_cost(self, a, b): for barrier in self.barriers: if b in barrier: return 100 return 1 def AStarSearch(start, end, graph): G = {} F = {} G[start] = 0 F[start] = graph.heuristic(start, end) closedVertices = set() openVertices = set([start]) cameFrom = {} while len(openVertices) > 0: current = None currentFscore = None for pos in openVertices: if current is None or F[pos] < currentFscore: currentFscore = F[pos] current = pos if current == end: path = [current] while current in cameFrom: current = cameFrom[current] path.append(current) path.reverse() return path, F[end] openVertices.remove(current) closedVertices.add(current) for neighbour in graph.get_vertex_neighbours(current): if neighbour in closedVertices: continue candidateG = G[current] + graph.move_cost(current, neighbour) if neighbour not in openVertices: openVertices.add(neighbour) elif candidateG >= G[neighbour]: continue cameFrom[neighbour] = current G[neighbour] = candidateG H = graph.heuristic(neighbour, end) F[neighbour] = G[neighbour] + H raise RuntimeError("A* failed to find a solution") if __name__=="__main__": graph = AStarGraph() result, cost = AStarSearch((0,0), (7,7), graph) print ("route", result) print ("cost", cost) plt.plot([v[0] for v in result], [v[1] for v in result]) for barrier in graph.barriers: plt.plot([v[0] for v in barrier], [v[1] for v in barrier]) plt.xlim(-1,8) plt.ylim(-1,8) plt.show()
Produce a language-to-language conversion: from C++ to Python, same semantics.
#include <list> #include <algorithm> #include <iostream> class point { public: point( int a = 0, int b = 0 ) { x = a; y = b; } bool operator ==( const point& o ) { return o.x == x && o.y == y; } point operator +( const point& o ) { return point( o.x + x, o.y + y ); } int x, y; }; class map { public: map() { char t[8][8] = { {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 1, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 0}, {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0} }; w = h = 8; for( int r = 0; r < h; r++ ) for( int s = 0; s < w; s++ ) m[s][r] = t[r][s]; } int operator() ( int x, int y ) { return m[x][y]; } char m[8][8]; int w, h; }; class node { public: bool operator == (const node& o ) { return pos == o.pos; } bool operator == (const point& o ) { return pos == o; } bool operator < (const node& o ) { return dist + cost < o.dist + o.cost; } point pos, parent; int dist, cost; }; class aStar { public: aStar() { neighbours[0] = point( -1, -1 ); neighbours[1] = point( 1, -1 ); neighbours[2] = point( -1, 1 ); neighbours[3] = point( 1, 1 ); neighbours[4] = point( 0, -1 ); neighbours[5] = point( -1, 0 ); neighbours[6] = point( 0, 1 ); neighbours[7] = point( 1, 0 ); } int calcDist( point& p ){ int x = end.x - p.x, y = end.y - p.y; return( x * x + y * y ); } bool isValid( point& p ) { return ( p.x >-1 && p.y > -1 && p.x < m.w && p.y < m.h ); } bool existPoint( point& p, int cost ) { std::list<node>::iterator i; i = std::find( closed.begin(), closed.end(), p ); if( i != closed.end() ) { if( ( *i ).cost + ( *i ).dist < cost ) return true; else { closed.erase( i ); return false; } } i = std::find( open.begin(), open.end(), p ); if( i != open.end() ) { if( ( *i ).cost + ( *i ).dist < cost ) return true; else { open.erase( i ); return false; } } return false; } bool fillOpen( node& n ) { int stepCost, nc, dist; point neighbour; for( int x = 0; x < 8; x++ ) { stepCost = x < 4 ? 1 : 1; neighbour = n.pos + neighbours[x]; if( neighbour == end ) return true; if( isValid( neighbour ) && m( neighbour.x, neighbour.y ) != 1 ) { nc = stepCost + n.cost; dist = calcDist( neighbour ); if( !existPoint( neighbour, nc + dist ) ) { node m; m.cost = nc; m.dist = dist; m.pos = neighbour; m.parent = n.pos; open.push_back( m ); } } } return false; } bool search( point& s, point& e, map& mp ) { node n; end = e; start = s; m = mp; n.cost = 0; n.pos = s; n.parent = 0; n.dist = calcDist( s ); open.push_back( n ); while( !open.empty() ) { node n = open.front(); open.pop_front(); closed.push_back( n ); if( fillOpen( n ) ) return true; } return false; } int path( std::list<point>& path ) { path.push_front( end ); int cost = 1 + closed.back().cost; path.push_front( closed.back().pos ); point parent = closed.back().parent; for( std::list<node>::reverse_iterator i = closed.rbegin(); i != closed.rend(); i++ ) { if( ( *i ).pos == parent && !( ( *i ).pos == start ) ) { path.push_front( ( *i ).pos ); parent = ( *i ).parent; } } path.push_front( start ); return cost; } map m; point end, start; point neighbours[8]; std::list<node> open; std::list<node> closed; }; int main( int argc, char* argv[] ) { map m; point s, e( 7, 7 ); aStar as; if( as.search( s, e, m ) ) { std::list<point> path; int c = as.path( path ); for( int y = -1; y < 9; y++ ) { for( int x = -1; x < 9; x++ ) { if( x < 0 || y < 0 || x > 7 || y > 7 || m( x, y ) == 1 ) std::cout << char(0xdb); else { if( std::find( path.begin(), path.end(), point( x, y ) )!= path.end() ) std::cout << "x"; else std::cout << "."; } } std::cout << "\n"; } std::cout << "\nPath cost " << c << ": "; for( std::list<point>::iterator i = path.begin(); i != path.end(); i++ ) { std::cout<< "(" << ( *i ).x << ", " << ( *i ).y << ") "; } } std::cout << "\n\n"; return 0; }
from __future__ import print_function import matplotlib.pyplot as plt class AStarGraph(object): def __init__(self): self.barriers = [] self.barriers.append([(2,4),(2,5),(2,6),(3,6),(4,6),(5,6),(5,5),(5,4),(5,3),(5,2),(4,2),(3,2)]) def heuristic(self, start, goal): D = 1 D2 = 1 dx = abs(start[0] - goal[0]) dy = abs(start[1] - goal[1]) return D * (dx + dy) + (D2 - 2 * D) * min(dx, dy) def get_vertex_neighbours(self, pos): n = [] for dx, dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,1),(1,-1),(-1,-1)]: x2 = pos[0] + dx y2 = pos[1] + dy if x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7: continue n.append((x2, y2)) return n def move_cost(self, a, b): for barrier in self.barriers: if b in barrier: return 100 return 1 def AStarSearch(start, end, graph): G = {} F = {} G[start] = 0 F[start] = graph.heuristic(start, end) closedVertices = set() openVertices = set([start]) cameFrom = {} while len(openVertices) > 0: current = None currentFscore = None for pos in openVertices: if current is None or F[pos] < currentFscore: currentFscore = F[pos] current = pos if current == end: path = [current] while current in cameFrom: current = cameFrom[current] path.append(current) path.reverse() return path, F[end] openVertices.remove(current) closedVertices.add(current) for neighbour in graph.get_vertex_neighbours(current): if neighbour in closedVertices: continue candidateG = G[current] + graph.move_cost(current, neighbour) if neighbour not in openVertices: openVertices.add(neighbour) elif candidateG >= G[neighbour]: continue cameFrom[neighbour] = current G[neighbour] = candidateG H = graph.heuristic(neighbour, end) F[neighbour] = G[neighbour] + H raise RuntimeError("A* failed to find a solution") if __name__=="__main__": graph = AStarGraph() result, cost = AStarSearch((0,0), (7,7), graph) print ("route", result) print ("cost", cost) plt.plot([v[0] for v in result], [v[1] for v in result]) for barrier in graph.barriers: plt.plot([v[0] for v in barrier], [v[1] for v in barrier]) plt.xlim(-1,8) plt.ylim(-1,8) plt.show()
Please provide an equivalent version of this C++ code in Python.
#include <algorithm> #include <fstream> #include <iostream> #include <set> #include <string> #include <vector> std::set<std::string> load_dictionary(const std::string& filename) { std::ifstream in(filename); if (!in) throw std::runtime_error("Cannot open file " + filename); std::set<std::string> words; std::string word; while (getline(in, word)) words.insert(word); return words; } void find_teacup_words(const std::set<std::string>& words) { std::vector<std::string> teacup_words; std::set<std::string> found; for (auto w = words.begin(); w != words.end(); ++w) { std::string word = *w; size_t len = word.size(); if (len < 3 || found.find(word) != found.end()) continue; teacup_words.clear(); teacup_words.push_back(word); for (size_t i = 0; i + 1 < len; ++i) { std::rotate(word.begin(), word.begin() + 1, word.end()); if (word == *w || words.find(word) == words.end()) break; teacup_words.push_back(word); } if (teacup_words.size() == len) { found.insert(teacup_words.begin(), teacup_words.end()); std::cout << teacup_words[0]; for (size_t i = 1; i < len; ++i) std::cout << ' ' << teacup_words[i]; std::cout << '\n'; } } } int main(int argc, char** argv) { if (argc != 2) { std::cerr << "usage: " << argv[0] << " dictionary\n"; return EXIT_FAILURE; } try { find_teacup_words(load_dictionary(argv[1])); } catch (const std::exception& ex) { std::cerr << ex.what() << '\n'; return EXIT_FAILURE; } return EXIT_SUCCESS; }
from itertools import chain, groupby from os.path import expanduser from functools import reduce def main(): print('\n'.join( concatMap(circularGroup)( anagrams(3)( lines(readFile('~/mitWords.txt')) ) ) )) def anagrams(n): def go(ws): def f(xs): return [ [snd(x) for x in xs] ] if n <= len(xs) >= len(xs[0][0]) else [] return concatMap(f)(groupBy(fst)(sorted( [(''.join(sorted(w)), w) for w in ws], key=fst ))) return go def circularGroup(ws): lex = set(ws) iLast = len(ws) - 1 (i, blnCircular) = until( lambda tpl: tpl[1] or (tpl[0] > iLast) )( lambda tpl: (1 + tpl[0], isCircular(lex)(ws[tpl[0]])) )( (0, False) ) return [' -> '.join(allRotations(ws[i]))] if blnCircular else [] def isCircular(lexicon): def go(w): def f(tpl): (i, _, x) = tpl return (1 + i, x in lexicon, rotated(x)) iLast = len(w) - 1 return until( lambda tpl: iLast < tpl[0] or (not tpl[1]) )(f)( (0, True, rotated(w)) )[1] return go def allRotations(w): return takeIterate(len(w) - 1)( rotated )(w) def concatMap(f): def go(xs): return chain.from_iterable(map(f, xs)) return go def fst(tpl): return tpl[0] def groupBy(f): def go(xs): return [ list(x[1]) for x in groupby(xs, key=f) ] return go def lines(s): return s.splitlines() def mapAccumL(f): def go(a, x): tpl = f(a[0], x) return (tpl[0], a[1] + [tpl[1]]) return lambda acc: lambda xs: ( reduce(go, xs, (acc, [])) ) def readFile(fp): with open(expanduser(fp), 'r', encoding='utf-8') as f: return f.read() def rotated(s): return s[1:] + s[0] def snd(tpl): return tpl[1] def takeIterate(n): def go(f): def g(x): def h(a, i): v = f(a) if i else x return (v, v) return mapAccumL(h)(x)( range(0, 1 + n) )[1] return g return go def until(p): def go(f): def g(x): v = x while not p(v): v = f(v) return v return g return go if __name__ == '__main__': main()
Convert the following code from C++ to Python, ensuring the logic remains intact.
#include <cstdint> #include <iomanip> #include <iostream> uint64_t digit_sum(uint64_t n, uint64_t sum) { ++sum; while (n > 0 && n % 10 == 0) { sum -= 9; n /= 10; } return sum; } inline bool divisible(uint64_t n, uint64_t d) { if ((d & 1) == 0 && (n & 1) == 1) return false; return n % d == 0; } int main() { std::cout.imbue(std::locale("")); uint64_t previous = 1, gap = 0, sum = 0; int niven_index = 0, gap_index = 1; std::cout << "Gap index Gap Niven index Niven number\n"; for (uint64_t niven = 1; gap_index <= 32; ++niven) { sum = digit_sum(niven, sum); if (divisible(niven, sum)) { if (niven > previous + gap) { gap = niven - previous; std::cout << std::setw(9) << gap_index++ << std::setw(5) << gap << std::setw(15) << niven_index << std::setw(16) << previous << '\n'; } previous = niven; ++niven_index; } } return 0; }
def digit_sum(n, sum): sum += 1 while n > 0 and n % 10 == 0: sum -= 9 n /= 10 return sum previous = 1 gap = 0 sum = 0 niven_index = 0 gap_index = 1 print("Gap index Gap Niven index Niven number") niven = 1 while gap_index <= 22: sum = digit_sum(niven, sum) if niven % sum == 0: if niven > previous + gap: gap = niven - previous; print('{0:9d} {1:4d} {2:13d} {3:11d}'.format(gap_index, gap, niven_index, previous)) gap_index += 1 previous = niven niven_index += 1 niven += 1
Port the following code from C++ to Python with equivalent syntax and logic.
#include <iostream> #define DEBUG(msg,...) fprintf(stderr, "[DEBUG %s@%d] " msg "\n", __FILE__, __LINE__, __VA_ARGS__) int main() { DEBUG("Hello world"); DEBUG("Some %d Things", 42); return 0; }
import logging, logging.handlers LOG_FILENAME = "logdemo.log" FORMAT_STRING = "%(levelname)s:%(asctime)s:%(name)s:%(funcName)s:line-%(lineno)d: %(message)s" LOGLEVEL = logging.DEBUG def print_squares(number): logger.info("In print_squares") for i in range(number): print("square of {0} is {1}".format(i , i*i)) logger.debug(f'square of {i} is {i*i}') def print_cubes(number): logger.info("In print_cubes") for j in range(number): print("cube of {0} is {1}".format(j, j*j*j)) logger.debug(f'cube of {j} is {j*j*j}') if __name__ == "__main__": logger = logging.getLogger("logdemo") logger.setLevel(LOGLEVEL) handler = logging.FileHandler(LOG_FILENAME) handler.setFormatter(logging.Formatter(FORMAT_STRING)) logger.addHandler(handler) print_squares(10) print_cubes(10) logger.info("All done")
Write the same algorithm in Python as shown in this C++ implementation.
#include <iostream> #define DEBUG(msg,...) fprintf(stderr, "[DEBUG %s@%d] " msg "\n", __FILE__, __LINE__, __VA_ARGS__) int main() { DEBUG("Hello world"); DEBUG("Some %d Things", 42); return 0; }
import logging, logging.handlers LOG_FILENAME = "logdemo.log" FORMAT_STRING = "%(levelname)s:%(asctime)s:%(name)s:%(funcName)s:line-%(lineno)d: %(message)s" LOGLEVEL = logging.DEBUG def print_squares(number): logger.info("In print_squares") for i in range(number): print("square of {0} is {1}".format(i , i*i)) logger.debug(f'square of {i} is {i*i}') def print_cubes(number): logger.info("In print_cubes") for j in range(number): print("cube of {0} is {1}".format(j, j*j*j)) logger.debug(f'cube of {j} is {j*j*j}') if __name__ == "__main__": logger = logging.getLogger("logdemo") logger.setLevel(LOGLEVEL) handler = logging.FileHandler(LOG_FILENAME) handler.setFormatter(logging.Formatter(FORMAT_STRING)) logger.addHandler(handler) print_squares(10) print_cubes(10) logger.info("All done")
Generate an equivalent Python version of this C++ code.
#include <iostream> #include <iterator> #include <cstddef> template<typename InIter> void extract_ranges(InIter begin, InIter end, std::ostream& os) { if (begin == end) return; int current = *begin++; os << current; int count = 1; while (begin != end) { int next = *begin++; if (next == current+1) ++count; else { if (count > 2) os << '-'; else os << ','; if (count > 1) os << current << ','; os << next; count = 1; } current = next; } if (count > 1) os << (count > 2? '-' : ',') << current; } template<typename T, std::size_t n> T* end(T (&array)[n]) { return array+n; } int main() { int data[] = { 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 }; extract_ranges(data, end(data), std::cout); std::cout << std::endl; }
def range_extract(lst): 'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints' lenlst = len(lst) i = 0 while i< lenlst: low = lst[i] while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1 hi = lst[i] if hi - low >= 2: yield (low, hi) elif hi - low == 1: yield (low,) yield (hi,) else: yield (low,) i += 1 def printr(ranges): print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r) for r in ranges ) ) if __name__ == '__main__': for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20], [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]: printr(range_extract(lst))
Write a version of this C++ function in Python with identical behavior.
#include <iostream> int main( int argc, char* argv[] ) { int triangle[] = { 55, 94, 48, 95, 30, 96, 77, 71, 26, 67, 97, 13, 76, 38, 45, 7, 36, 79, 16, 37, 68, 48, 7, 9, 18, 70, 26, 6, 18, 72, 79, 46, 59, 79, 29, 90, 20, 76, 87, 11, 32, 7, 7, 49, 18, 27, 83, 58, 35, 71, 11, 25, 57, 29, 85, 14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55, 2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23, 92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42, 56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72, 44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36, 85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52, 6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15, 27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93 }; const int size = sizeof( triangle ) / sizeof( int ); const int tn = static_cast<int>(sqrt(2.0 * size)); assert(tn * (tn + 1) == 2 * size); for (int n = tn - 1; n > 0; --n) for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k) triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]); std::cout << "Maximum total: " << triangle[0] << "\n\n"; }
fun maxpathsum(t): let a = val t for i in a.length-1..-1..1, c in linearindices a[r]: a[r, c] += max(a[r+1, c], a[r=1, c+1]) return a[1, 1] let test = [ [55], [94, 48], [95, 30, 96], [77, 71, 26, 67], [97, 13, 76, 38, 45], [07, 36, 79, 16, 37, 68], [48, 07, 09, 18, 70, 26, 06], [18, 72, 79, 46, 59, 79, 29, 90], [20, 76, 87, 11, 32, 07, 07, 49, 18], [27, 83, 58, 35, 71, 11, 25, 57, 29, 85], [14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55], [02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23], [92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42], [56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72], [44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36], [85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52], [06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15], [27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93] ] @print maxpathsum test
Generate an equivalent Python version of this C++ code.
#include <iostream> #include <string> #include <sstream> #include <valarray> const std::string input { "................................" ".#########.......########......." ".###...####.....####..####......" ".###....###.....###....###......" ".###...####.....###............." ".#########......###............." ".###.####.......###....###......" ".###..####..###.####..####.###.." ".###...####.###..########..###.." "................................" }; const std::string input2 { ".........................................................." ".#################...................#############........" ".##################...............################........" ".###################............##################........" ".########.....#######..........###################........" "...######.....#######.........#######.......######........" "...######.....#######........#######......................" "...#################.........#######......................" "...################..........#######......................" "...#################.........#######......................" "...######.....#######........#######......................" "...######.....#######........#######......................" "...######.....#######.........#######.......######........" ".########.....#######..........###################........" ".########.....#######.######....##################.######." ".########.....#######.######......################.######." ".########.....#######.######.........#############.######." ".........................................................." }; class ZhangSuen; class Image { public: friend class ZhangSuen; using pixel_t = char; static const pixel_t BLACK_PIX; static const pixel_t WHITE_PIX; Image(unsigned width = 1, unsigned height = 1) : width_{width}, height_{height}, data_( '\0', width_ * height_) {} Image(const Image& i) : width_{ i.width_}, height_{i.height_}, data_{i.data_} {} Image(Image&& i) : width_{ i.width_}, height_{i.height_}, data_{std::move(i.data_)} {} ~Image() = default; Image& operator=(const Image& i) { if (this != &i) { width_ = i.width_; height_ = i.height_; data_ = i.data_; } return *this; } Image& operator=(Image&& i) { if (this != &i) { width_ = i.width_; height_ = i.height_; data_ = std::move(i.data_); } return *this; } size_t idx(unsigned x, unsigned y) const noexcept { return y * width_ + x; } bool operator()(unsigned x, unsigned y) { return data_[idx(x, y)]; } friend std::ostream& operator<<(std::ostream& o, const Image& i) { o << i.width_ << " x " << i.height_ << std::endl; size_t px = 0; for(const auto& e : i.data_) { o << (e?Image::BLACK_PIX:Image::WHITE_PIX); if (++px % i.width_ == 0) o << std::endl; } return o << std::endl; } friend std::istream& operator>>(std::istream& in, Image& img) { auto it = std::begin(img.data_); const auto end = std::end(img.data_); Image::pixel_t tmp; while(in && it != end) { in >> tmp; if (tmp != Image::BLACK_PIX && tmp != Image::WHITE_PIX) throw "Bad character found in image"; *it = (tmp == Image::BLACK_PIX)?1:0; ++it; } return in; } unsigned width() const noexcept { return width_; } unsigned height() const noexcept { return height_; } struct Neighbours { Neighbours(const Image& img, unsigned p1_x, unsigned p1_y) : img_{img} , p1_{img.idx(p1_x, p1_y)} , p2_{p1_ - img.width()} , p3_{p2_ + 1} , p4_{p1_ + 1} , p5_{p4_ + img.width()} , p6_{p5_ - 1} , p7_{p6_ - 1} , p8_{p1_ - 1} , p9_{p2_ - 1} {} const Image& img_; const Image::pixel_t& p1() const noexcept { return img_.data_[p1_]; } const Image::pixel_t& p2() const noexcept { return img_.data_[p2_]; } const Image::pixel_t& p3() const noexcept { return img_.data_[p3_]; } const Image::pixel_t& p4() const noexcept { return img_.data_[p4_]; } const Image::pixel_t& p5() const noexcept { return img_.data_[p5_]; } const Image::pixel_t& p6() const noexcept { return img_.data_[p6_]; } const Image::pixel_t& p7() const noexcept { return img_.data_[p7_]; } const Image::pixel_t& p8() const noexcept { return img_.data_[p8_]; } const Image::pixel_t& p9() const noexcept { return img_.data_[p9_]; } const size_t p1_, p2_, p3_, p4_, p5_, p6_, p7_, p8_, p9_; }; Neighbours neighbours(unsigned x, unsigned y) const { return Neighbours(*this, x, y); } private: unsigned height_ { 0 }; unsigned width_ { 0 }; std::valarray<pixel_t> data_; }; constexpr const Image::pixel_t Image::BLACK_PIX = '#'; constexpr const Image::pixel_t Image::WHITE_PIX = '.'; class ZhangSuen { public: unsigned transitions_white_black(const Image::Neighbours& a) const { unsigned sum = 0; sum += (a.p9() == 0) && a.p2(); sum += (a.p2() == 0) && a.p3(); sum += (a.p3() == 0) && a.p4(); sum += (a.p8() == 0) && a.p9(); sum += (a.p4() == 0) && a.p5(); sum += (a.p7() == 0) && a.p8(); sum += (a.p6() == 0) && a.p7(); sum += (a.p5() == 0) && a.p6(); return sum; } unsigned black_pixels(const Image::Neighbours& a) const { unsigned sum = 0; sum += a.p9(); sum += a.p2(); sum += a.p3(); sum += a.p8(); sum += a.p4(); sum += a.p7(); sum += a.p6(); sum += a.p5(); return sum; } const Image& operator()(const Image& img) { tmp_a_ = img; size_t changed_pixels = 0; do { changed_pixels = 0; tmp_b_ = tmp_a_; for(size_t y = 1; y < tmp_a_.height() - 1; ++y) { for(size_t x = 1; x < tmp_a_.width() - 1; ++x) { if (tmp_a_.data_[tmp_a_.idx(x, y)]) { auto n = tmp_a_.neighbours(x, y); auto bp = black_pixels(n); if (bp >= 2 && bp <= 6) { auto tr = transitions_white_black(n); if ( tr == 1 && (n.p2() * n.p4() * n.p6() == 0) && (n.p4() * n.p6() * n.p8() == 0) ) { tmp_b_.data_[n.p1_] = 0; ++changed_pixels; } } } } } tmp_a_ = tmp_b_; for(size_t y = 1; y < tmp_b_.height() - 1; ++y) { for(size_t x = 1; x < tmp_b_.width() - 1; ++x) { if (tmp_b_.data_[tmp_b_.idx(x, y)]) { auto n = tmp_b_.neighbours(x, y); auto bp = black_pixels(n); if (bp >= 2 && bp <= 6) { auto tr = transitions_white_black(n); if ( tr == 1 && (n.p2() * n.p4() * n.p8() == 0) && (n.p2() * n.p6() * n.p8() == 0) ) { tmp_a_.data_[n.p1_] = 0; ++changed_pixels; } } } } } } while(changed_pixels > 0); return tmp_a_; } private: Image tmp_a_; Image tmp_b_; }; int main(int argc, char const *argv[]) { using namespace std; Image img(32, 10); istringstream iss{input}; iss >> img; cout << img; cout << "ZhangSuen" << endl; ZhangSuen zs; Image res = std::move(zs(img)); cout << res << endl; Image img2(58,18); istringstream iss2{input2}; iss2 >> img2; cout << img2; cout << "ZhangSuen with big image" << endl; Image res2 = std::move(zs(img2)); cout << res2 << endl; return 0; }
beforeTxt = smallrc01 = rc01 = def intarray(binstring): return [[1 if ch == '1' else 0 for ch in line] for line in binstring.strip().split()] def chararray(intmatrix): return '\n'.join(''.join(str(p) for p in row) for row in intmatrix) def toTxt(intmatrix): Return 8-neighbours of point p1 of picture, in order''' i = image x1, y1, x_1, y_1 = x+1, y-1, x-1, y+1 return [i[y1][x], i[y1][x1], i[y][x1], i[y_1][x1], i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1]] def transitions(neighbours): n = neighbours + neighbours[0:1] return sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:])) def zhangSuen(image): changing1 = changing2 = [(-1, -1)] while changing1 or changing2: changing1 = [] for y in range(1, len(image) - 1): for x in range(1, len(image[0]) - 1): P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image) if (image[y][x] == 1 and P4 * P6 * P8 == 0 and P2 * P4 * P6 == 0 and transitions(n) == 1 and 2 <= sum(n) <= 6): changing1.append((x,y)) for x, y in changing1: image[y][x] = 0 changing2 = [] for y in range(1, len(image) - 1): for x in range(1, len(image[0]) - 1): P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image) if (image[y][x] == 1 and P2 * P6 * P8 == 0 and P2 * P4 * P8 == 0 and transitions(n) == 1 and 2 <= sum(n) <= 6): changing2.append((x,y)) for x, y in changing2: image[y][x] = 0 return image if __name__ == '__main__': for picture in (beforeTxt, smallrc01, rc01): image = intarray(picture) print('\nFrom:\n%s' % toTxt(image)) after = zhangSuen(image) print('\nTo thinned:\n%s' % toTxt(after))
Write a version of this C++ function in Python with identical behavior.
#include <array> #include <iostream> int main() { constexpr std::array s {1,2,2,3,4,4,5}; if(!s.empty()) { int previousValue = s[0]; for(size_t i = 1; i < s.size(); ++i) { const int currentValue = s[i]; if(i > 0 && previousValue == currentValue) { std::cout << i << "\n"; } previousValue = currentValue; } } }
s = [1, 2, 2, 3, 4, 4, 5] for i in range(len(s)): curr = s[i] if i > 0 and curr == prev: print(i) prev = curr
Translate the given C++ code snippet into Python without altering its behavior.
#include <iomanip> #include <iostream> bool equal_rises_and_falls(int n) { int total = 0; for (int previous_digit = -1; n > 0; n /= 10) { int digit = n % 10; if (previous_digit > digit) ++total; else if (previous_digit >= 0 && previous_digit < digit) --total; previous_digit = digit; } return total == 0; } int main() { const int limit1 = 200; const int limit2 = 10000000; int n = 0; std::cout << "The first " << limit1 << " numbers in the sequence are:\n"; for (int count = 0; count < limit2; ) { if (equal_rises_and_falls(++n)) { ++count; if (count <= limit1) std::cout << std::setw(3) << n << (count % 20 == 0 ? '\n' : ' '); } } std::cout << "\nThe " << limit2 << "th number in the sequence is " << n << ".\n"; }
import itertools def riseEqFall(num): height = 0 d1 = num % 10 num //= 10 while num: d2 = num % 10 height += (d1<d2) - (d1>d2) d1 = d2 num //= 10 return height == 0 def sequence(start, fn): num=start-1 while True: num += 1 while not fn(num): num += 1 yield num a296712 = sequence(1, riseEqFall) print("The first 200 numbers are:") print(*itertools.islice(a296712, 200)) print("The 10,000,000th number is:") print(*itertools.islice(a296712, 10000000-200-1, 10000000-200))
Port the following code from C++ to Python with equivalent syntax and logic.
#include <fstream> #include <iostream> #include <vector> constexpr double sqrt3_2 = 0.86602540378444; struct point { double x; double y; }; std::vector<point> koch_next(const std::vector<point>& points) { size_t size = points.size(); std::vector<point> output(4*(size - 1) + 1); double x0, y0, x1, y1; size_t j = 0; for (size_t i = 0; i + 1 < size; ++i) { x0 = points[i].x; y0 = points[i].y; x1 = points[i + 1].x; y1 = points[i + 1].y; double dy = y1 - y0; double dx = x1 - x0; output[j++] = {x0, y0}; output[j++] = {x0 + dx/3, y0 + dy/3}; output[j++] = {x0 + dx/2 - dy * sqrt3_2/3, y0 + dy/2 + dx * sqrt3_2/3}; output[j++] = {x0 + 2 * dx/3, y0 + 2 * dy/3}; } output[j] = {x1, y1}; return output; } std::vector<point> koch_points(int size, int iterations) { double length = size * sqrt3_2 * 0.95; double x = (size - length)/2; double y = size/2 - length * sqrt3_2/3; std::vector<point> points{ {x, y}, {x + length/2, y + length * sqrt3_2}, {x + length, y}, {x, y} }; for (int i = 0; i < iterations; ++i) points = koch_next(points); return points; } void koch_curve_svg(std::ostream& out, int size, int iterations) { out << "<svg xmlns='http: << size << "' height='" << size << "'>\n"; out << "<rect width='100%' height='100%' fill='black'/>\n"; out << "<path stroke-width='1' stroke='white' fill='none' d='"; auto points(koch_points(size, iterations)); for (size_t i = 0, n = points.size(); i < n; ++i) out << (i == 0 ? "M" : "L") << points[i].x << ',' << points[i].y << '\n'; out << "z'/>\n</svg>\n"; } int main() { std::ofstream out("koch_curve.svg"); if (!out) { std::cerr << "Cannot open output file\n"; return EXIT_FAILURE; } koch_curve_svg(out, 600, 5); return EXIT_SUCCESS; }
l = 300 def setup(): size(400, 400) background(0, 0, 255) stroke(255) translate(width / 2.0, height / 2.0) translate(-l / 2.0, l * sqrt(3) / 6.0) for i in range(4): kcurve(0, l) rotate(radians(120)) translate(-l, 0) def kcurve(x1, x2): s = (x2 - x1) / 3.0 if s < 5: pushMatrix() translate(x1, 0) line(0, 0, s, 0) line(2 * s, 0, 3 * s, 0) translate(s, 0) rotate(radians(60)) line(0, 0, s, 0) translate(s, 0) rotate(radians(-120)) line(0, 0, s, 0) popMatrix() return pushMatrix() translate(x1, 0) kcurve(0, s) kcurve(2 * s, 3 * s) translate(s, 0) rotate(radians(60)) kcurve(0, s) translate(s, 0) rotate(radians(-120)) kcurve(0, s) popMatrix()
Write the same code in Python as shown below in C++.
#include <fstream> #include <iostream> #include <vector> constexpr double sqrt3_2 = 0.86602540378444; struct point { double x; double y; }; std::vector<point> koch_next(const std::vector<point>& points) { size_t size = points.size(); std::vector<point> output(4*(size - 1) + 1); double x0, y0, x1, y1; size_t j = 0; for (size_t i = 0; i + 1 < size; ++i) { x0 = points[i].x; y0 = points[i].y; x1 = points[i + 1].x; y1 = points[i + 1].y; double dy = y1 - y0; double dx = x1 - x0; output[j++] = {x0, y0}; output[j++] = {x0 + dx/3, y0 + dy/3}; output[j++] = {x0 + dx/2 - dy * sqrt3_2/3, y0 + dy/2 + dx * sqrt3_2/3}; output[j++] = {x0 + 2 * dx/3, y0 + 2 * dy/3}; } output[j] = {x1, y1}; return output; } std::vector<point> koch_points(int size, int iterations) { double length = size * sqrt3_2 * 0.95; double x = (size - length)/2; double y = size/2 - length * sqrt3_2/3; std::vector<point> points{ {x, y}, {x + length/2, y + length * sqrt3_2}, {x + length, y}, {x, y} }; for (int i = 0; i < iterations; ++i) points = koch_next(points); return points; } void koch_curve_svg(std::ostream& out, int size, int iterations) { out << "<svg xmlns='http: << size << "' height='" << size << "'>\n"; out << "<rect width='100%' height='100%' fill='black'/>\n"; out << "<path stroke-width='1' stroke='white' fill='none' d='"; auto points(koch_points(size, iterations)); for (size_t i = 0, n = points.size(); i < n; ++i) out << (i == 0 ? "M" : "L") << points[i].x << ',' << points[i].y << '\n'; out << "z'/>\n</svg>\n"; } int main() { std::ofstream out("koch_curve.svg"); if (!out) { std::cerr << "Cannot open output file\n"; return EXIT_FAILURE; } koch_curve_svg(out, 600, 5); return EXIT_SUCCESS; }
l = 300 def setup(): size(400, 400) background(0, 0, 255) stroke(255) translate(width / 2.0, height / 2.0) translate(-l / 2.0, l * sqrt(3) / 6.0) for i in range(4): kcurve(0, l) rotate(radians(120)) translate(-l, 0) def kcurve(x1, x2): s = (x2 - x1) / 3.0 if s < 5: pushMatrix() translate(x1, 0) line(0, 0, s, 0) line(2 * s, 0, 3 * s, 0) translate(s, 0) rotate(radians(60)) line(0, 0, s, 0) translate(s, 0) rotate(radians(-120)) line(0, 0, s, 0) popMatrix() return pushMatrix() translate(x1, 0) kcurve(0, s) kcurve(2 * s, 3 * s) translate(s, 0) rotate(radians(60)) kcurve(0, s) translate(s, 0) rotate(radians(-120)) kcurve(0, s) popMatrix()
Translate the given C++ code snippet into Python without altering its behavior.
#include <algorithm> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <string> #include <vector> int main(int argc, char** argv) { const int min_length = 9; const char* filename(argc < 2 ? "unixdict.txt" : argv[1]); std::ifstream in(filename); if (!in) { std::cerr << "Cannot open file '" << filename << "'.\n"; return EXIT_FAILURE; } std::string line; std::vector<std::string> words; while (getline(in, line)) { if (line.size() >= min_length) words.push_back(line); } std::sort(words.begin(), words.end()); std::string previous_word; int count = 0; for (size_t i = 0, n = words.size(); i + min_length <= n; ++i) { std::string word; word.reserve(min_length); for (size_t j = 0; j < min_length; ++j) word += words[i + j][j]; if (previous_word == word) continue; auto w = std::lower_bound(words.begin(), words.end(), word); if (w != words.end() && *w == word) std::cout << std::setw(2) << ++count << ". " << word << '\n'; previous_word = word; } return EXIT_SUCCESS; }
import urllib.request from collections import Counter urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt") dictionary = open("unixdict.txt","r") wordList = dictionary.read().split('\n') dictionary.close() filteredWords = [chosenWord for chosenWord in wordList if len(chosenWord)>=9] for word in filteredWords[:-9]: position = filteredWords.index(word) newWord = "".join([filteredWords[position+i][i] for i in range(0,9)]) if newWord in filteredWords: print(newWord)
Ensure the translated Python code behaves exactly like the original C++ snippet.
#include <iostream> #include <sstream> #include <iomanip> using namespace std; class magicSqr { public: magicSqr() { sqr = 0; } ~magicSqr() { if( sqr ) delete [] sqr; } void create( int d ) { if( sqr ) delete [] sqr; if( d & 1 ) d++; while( d % 4 == 0 ) { d += 2; } sz = d; sqr = new int[sz * sz]; memset( sqr, 0, sz * sz * sizeof( int ) ); fillSqr(); } void display() { cout << "Singly Even Magic Square: " << sz << " x " << sz << "\n"; cout << "It's Magic Sum is: " << magicNumber() << "\n\n"; ostringstream cvr; cvr << sz * sz; int l = cvr.str().size(); for( int y = 0; y < sz; y++ ) { int yy = y * sz; for( int x = 0; x < sz; x++ ) { cout << setw( l + 2 ) << sqr[yy + x]; } cout << "\n"; } cout << "\n\n"; } private: void siamese( int from, int to ) { int oneSide = to - from, curCol = oneSide / 2, curRow = 0, count = oneSide * oneSide, s = 1; while( count > 0 ) { bool done = false; while ( false == done ) { if( curCol >= oneSide ) curCol = 0; if( curRow < 0 ) curRow = oneSide - 1; done = true; if( sqr[curCol + sz * curRow] != 0 ) { curCol -= 1; curRow += 2; if( curCol < 0 ) curCol = oneSide - 1; if( curRow >= oneSide ) curRow -= oneSide; done = false; } } sqr[curCol + sz * curRow] = s; s++; count--; curCol++; curRow--; } } void fillSqr() { int n = sz / 2, ns = n * sz, size = sz * sz, add1 = size / 2, add3 = size / 4, add2 = 3 * add3; siamese( 0, n ); for( int r = 0; r < n; r++ ) { int row = r * sz; for( int c = n; c < sz; c++ ) { int m = sqr[c - n + row]; sqr[c + row] = m + add1; sqr[c + row + ns] = m + add3; sqr[c - n + row + ns] = m + add2; } } int lc = ( sz - 2 ) / 4, co = sz - ( lc - 1 ); for( int r = 0; r < n; r++ ) { int row = r * sz; for( int c = co; c < sz; c++ ) { sqr[c + row] -= add3; sqr[c + row + ns] += add3; } } for( int r = 0; r < n; r++ ) { int row = r * sz; for( int c = 0; c < lc; c++ ) { int cc = c; if( r == lc ) cc++; sqr[cc + row] += add2; sqr[cc + row + ns] -= add2; } } } int magicNumber() { return sz * ( ( sz * sz ) + 1 ) / 2; } void inc( int& a ) { if( ++a == sz ) a = 0; } void dec( int& a ) { if( --a < 0 ) a = sz - 1; } bool checkPos( int x, int y ) { return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); } bool isInside( int s ) { return ( s < sz && s > -1 ); } int* sqr; int sz; }; int main( int argc, char* argv[] ) { magicSqr s; s.create( 6 ); s.display(); return 0; }
import math from sys import stdout LOG_10 = 2.302585092994 def build_oms(s): if s % 2 == 0: s += 1 q = [[0 for j in range(s)] for i in range(s)] p = 1 i = s // 2 j = 0 while p <= (s * s): q[i][j] = p ti = i + 1 if ti >= s: ti = 0 tj = j - 1 if tj < 0: tj = s - 1 if q[ti][tj] != 0: ti = i tj = j + 1 i = ti j = tj p = p + 1 return q, s def build_sems(s): if s % 2 == 1: s += 1 while s % 4 == 0: s += 2 q = [[0 for j in range(s)] for i in range(s)] z = s // 2 b = z * z c = 2 * b d = 3 * b o = build_oms(z) for j in range(0, z): for i in range(0, z): a = o[0][i][j] q[i][j] = a q[i + z][j + z] = a + b q[i + z][j] = a + c q[i][j + z] = a + d lc = z // 2 rc = lc for j in range(0, z): for i in range(0, s): if i < lc or i > s - rc or (i == lc and j == lc): if not (i == 0 and j == lc): t = q[i][j] q[i][j] = q[i][j + z] q[i][j + z] = t return q, s def format_sqr(s, l): for i in range(0, l - len(s)): s = "0" + s return s + " " def display(q): s = q[1] print(" - {0} x {1}\n".format(s, s)) k = 1 + math.floor(math.log(s * s) / LOG_10) for j in range(0, s): for i in range(0, s): stdout.write(format_sqr("{0}".format(q[0][i][j]), k)) print() print("Magic sum: {0}\n".format(s * ((s * s) + 1) // 2)) stdout.write("Singly Even Magic Square") display(build_sems(6))
Transform the following C++ implementation into Python, maintaining the same output and logic.
#include <iostream> #include <string> #include <time.h> using namespace std; namespace { void placeRandomly(char* p, char c) { int loc = rand() % 8; if (!p[loc]) p[loc] = c; else placeRandomly(p, c); } int placeFirst(char* p, char c, int loc = 0) { while (p[loc]) ++loc; p[loc] = c; return loc; } string startPos() { char p[8]; memset( p, 0, 8 ); p[2 * (rand() % 4)] = 'B'; p[2 * (rand() % 4) + 1] = 'B'; for (char c : "QNN") placeRandomly(p, c); placeFirst(p, 'R', placeFirst(p, 'K', placeFirst(p, 'R'))); return string(p, 8); } } namespace chess960 { void generate( int c ) { for( int x = 0; x < c; x++ ) cout << startPos() << "\n"; } } int main( int argc, char* argv[] ) { srand( time( NULL ) ); chess960::generate( 10 ); cout << "\n\n"; return system( "pause" ); }
>>> from itertools import permutations >>> pieces = 'KQRrBbNN' >>> starts = {''.join(p).upper() for p in permutations(pieces) if p.index('B') % 2 != p.index('b') % 2 and ( p.index('r') < p.index('K') < p.index('R') or p.index('R') < p.index('K') < p.index('r') ) } >>> len(starts) 960 >>> starts.pop() 'QNBRNKRB' >>>
Change the programming language of this snippet from C++ to Python without modifying what it does.
int meaning_of_life();
def meaning_of_life(): return 42 if __name__ == "__main__": print("Main: The meaning of life is %s" % meaning_of_life())
Keep all operations the same but rewrite the snippet in Python.
int meaning_of_life();
def meaning_of_life(): return 42 if __name__ == "__main__": print("Main: The meaning of life is %s" % meaning_of_life())
Convert the following code from C++ to Python, ensuring the logic remains intact.
#include <algorithm> #include <array> #include <filesystem> #include <iomanip> #include <iostream> void file_size_distribution(const std::filesystem::path& directory) { constexpr size_t n = 9; constexpr std::array<std::uintmax_t, n> sizes = { 0, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000 }; std::array<size_t, n + 1> count = { 0 }; size_t files = 0; std::uintmax_t total_size = 0; std::filesystem::recursive_directory_iterator iter(directory); for (const auto& dir_entry : iter) { if (dir_entry.is_regular_file() && !dir_entry.is_symlink()) { std::uintmax_t file_size = dir_entry.file_size(); total_size += file_size; auto i = std::lower_bound(sizes.begin(), sizes.end(), file_size); size_t index = std::distance(sizes.begin(), i); ++count[index]; ++files; } } std::cout << "File size distribution for " << directory << ":\n"; for (size_t i = 0; i <= n; ++i) { if (i == n) std::cout << "> " << sizes[i - 1]; else std::cout << std::setw(16) << sizes[i]; std::cout << " bytes: " << count[i] << '\n'; } std::cout << "Number of files: " << files << '\n'; std::cout << "Total file size: " << total_size << " bytes\n"; } int main(int argc, char** argv) { std::cout.imbue(std::locale("")); try { const char* directory(argc > 1 ? argv[1] : "."); std::filesystem::path path(directory); if (!is_directory(path)) { std::cerr << directory << " is not a directory.\n"; return EXIT_FAILURE; } file_size_distribution(path); } catch (const std::exception& ex) { std::cerr << ex.what() << '\n'; return EXIT_FAILURE; } return EXIT_SUCCESS; }
import sys, os from collections import Counter def dodir(path): global h for name in os.listdir(path): p = os.path.join(path, name) if os.path.islink(p): pass elif os.path.isfile(p): h[os.stat(p).st_size] += 1 elif os.path.isdir(p): dodir(p) else: pass def main(arg): global h h = Counter() for dir in arg: dodir(dir) s = n = 0 for k, v in sorted(h.items()): print("Size %d -> %d file(s)" % (k, v)) n += v s += k * v print("Total %d bytes for %d files" % (s, n)) main(sys.argv[1:])
Keep all operations the same but rewrite the snippet in Python.
#include <iostream> #include <set> #include <boost/filesystem.hpp> namespace fs = boost::filesystem; int main(void) { fs::path p(fs::current_path()); std::set<std::string> tree; for (auto it = fs::directory_iterator(p); it != fs::directory_iterator(); ++it) tree.insert(it->path().filename().native()); for (auto entry : tree) std::cout << entry << '\n'; }
>>> import os >>> print('\n'.join(sorted(os.listdir('.')))) DLLs Doc LICENSE.txt Lib NEWS.txt README.txt Scripts Tools include libs python.exe pythonw.exe tcl >>>
Ensure the translated Python code behaves exactly like the original C++ snippet.
#include <iostream> #include <sstream> #include <iomanip> using namespace std; class magicSqr { public: magicSqr( int d ) { while( d % 4 > 0 ) { d++; } sz = d; sqr = new int[sz * sz]; fillSqr(); } ~magicSqr() { delete [] sqr; } void display() const { cout << "Doubly Even Magic Square: " << sz << " x " << sz << "\n"; cout << "It's Magic Sum is: " << magicNumber() << "\n\n"; ostringstream cvr; cvr << sz * sz; int l = cvr.str().size(); for( int y = 0; y < sz; y++ ) { int yy = y * sz; for( int x = 0; x < sz; x++ ) { cout << setw( l + 2 ) << sqr[yy + x]; } cout << "\n"; } cout << "\n\n"; } private: void fillSqr() { static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } }; int i = 0; for( int curRow = 0; curRow < sz; curRow++ ) { for( int curCol = 0; curCol < sz; curCol++ ) { sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i; i++; } } } int magicNumber() const { return sz * ( ( sz * sz ) + 1 ) / 2; } int* sqr; int sz; }; int main( int argc, char* argv[] ) { magicSqr s( 8 ); s.display(); return 0; }
def MagicSquareDoublyEven(order): sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ] n1 = order/4 for r in range(n1): r1 = sq[r][n1:-n1] r2 = sq[order -r - 1][n1:-n1] r1.reverse() r2.reverse() sq[r][n1:-n1] = r2 sq[order -r - 1][n1:-n1] = r1 for r in range(n1, order-n1): r1 = sq[r][:n1] r2 = sq[order -r - 1][order-n1:] r1.reverse() r2.reverse() sq[r][:n1] = r2 sq[order -r - 1][order-n1:] = r1 return sq def printsq(s): n = len(s) bl = len(str(n**2))+1 for i in range(n): print ''.join( [ ("%"+str(bl)+"s")%(str(x)) for x in s[i]] ) print "\nMagic constant = %d"%sum(s[0]) printsq(MagicSquareDoublyEven(8))
Ensure the translated Python code behaves exactly like the original C++ snippet.
#include <array> #include <cstdint> #include <iostream> class XorShiftStar { private: const uint64_t MAGIC = 0x2545F4914F6CDD1D; uint64_t state; public: void seed(uint64_t num) { state = num; } uint32_t next_int() { uint64_t x; uint32_t answer; x = state; x = x ^ (x >> 12); x = x ^ (x << 25); x = x ^ (x >> 27); state = x; answer = ((x * MAGIC) >> 32); return answer; } float next_float() { return (float)next_int() / (1LL << 32); } }; int main() { auto rng = new XorShiftStar(); rng->seed(1234567); std::cout << rng->next_int() << '\n'; std::cout << rng->next_int() << '\n'; std::cout << rng->next_int() << '\n'; std::cout << rng->next_int() << '\n'; std::cout << rng->next_int() << '\n'; std::cout << '\n'; std::array<int, 5> counts = { 0, 0, 0, 0, 0 }; rng->seed(987654321); for (int i = 0; i < 100000; i++) { int j = (int)floor(rng->next_float() * 5.0); counts[j]++; } for (size_t i = 0; i < counts.size(); i++) { std::cout << i << ": " << counts[i] << '\n'; } return 0; }
mask64 = (1 << 64) - 1 mask32 = (1 << 32) - 1 const = 0x2545F4914F6CDD1D class Xorshift_star(): def __init__(self, seed=0): self.state = seed & mask64 def seed(self, num): self.state = num & mask64 def next_int(self): "return random int between 0 and 2**32" x = self.state x = (x ^ (x >> 12)) & mask64 x = (x ^ (x << 25)) & mask64 x = (x ^ (x >> 27)) & mask64 self.state = x answer = (((x * const) & mask64) >> 32) & mask32 return answer def next_float(self): "return random float between 0 and 1" return self.next_int() / (1 << 32) if __name__ == '__main__': random_gen = Xorshift_star() random_gen.seed(1234567) for i in range(5): print(random_gen.next_int()) random_gen.seed(987654321) hist = {i:0 for i in range(5)} for i in range(100_000): hist[int(random_gen.next_float() *5)] += 1 print(hist)
Change the programming language of this snippet from C++ to Python without modifying what it does.
#include <cctype> #include <cstdint> #include <iomanip> #include <iostream> #include <string> #include <vector> struct number_names { const char* cardinal; const char* ordinal; }; const number_names small[] = { { "zero", "zeroth" }, { "one", "first" }, { "two", "second" }, { "three", "third" }, { "four", "fourth" }, { "five", "fifth" }, { "six", "sixth" }, { "seven", "seventh" }, { "eight", "eighth" }, { "nine", "ninth" }, { "ten", "tenth" }, { "eleven", "eleventh" }, { "twelve", "twelfth" }, { "thirteen", "thirteenth" }, { "fourteen", "fourteenth" }, { "fifteen", "fifteenth" }, { "sixteen", "sixteenth" }, { "seventeen", "seventeenth" }, { "eighteen", "eighteenth" }, { "nineteen", "nineteenth" } }; const number_names tens[] = { { "twenty", "twentieth" }, { "thirty", "thirtieth" }, { "forty", "fortieth" }, { "fifty", "fiftieth" }, { "sixty", "sixtieth" }, { "seventy", "seventieth" }, { "eighty", "eightieth" }, { "ninety", "ninetieth" } }; struct named_number { const char* cardinal; const char* ordinal; uint64_t number; }; const named_number named_numbers[] = { { "hundred", "hundredth", 100 }, { "thousand", "thousandth", 1000 }, { "million", "millionth", 1000000 }, { "billion", "biliionth", 1000000000 }, { "trillion", "trillionth", 1000000000000 }, { "quadrillion", "quadrillionth", 1000000000000000ULL }, { "quintillion", "quintillionth", 1000000000000000000ULL } }; const char* get_name(const number_names& n, bool ordinal) { return ordinal ? n.ordinal : n.cardinal; } const char* get_name(const named_number& n, bool ordinal) { return ordinal ? n.ordinal : n.cardinal; } const named_number& get_named_number(uint64_t n) { constexpr size_t names_len = std::size(named_numbers); for (size_t i = 0; i + 1 < names_len; ++i) { if (n < named_numbers[i + 1].number) return named_numbers[i]; } return named_numbers[names_len - 1]; } size_t append_number_name(std::vector<std::string>& result, uint64_t n, bool ordinal) { size_t count = 0; if (n < 20) { result.push_back(get_name(small[n], ordinal)); count = 1; } else if (n < 100) { if (n % 10 == 0) { result.push_back(get_name(tens[n/10 - 2], ordinal)); } else { std::string name(get_name(tens[n/10 - 2], false)); name += "-"; name += get_name(small[n % 10], ordinal); result.push_back(name); } count = 1; } else { const named_number& num = get_named_number(n); uint64_t p = num.number; count += append_number_name(result, n/p, false); if (n % p == 0) { result.push_back(get_name(num, ordinal)); ++count; } else { result.push_back(get_name(num, false)); ++count; count += append_number_name(result, n % p, ordinal); } } return count; } size_t count_letters(const std::string& str) { size_t letters = 0; for (size_t i = 0, n = str.size(); i < n; ++i) { if (isalpha(static_cast<unsigned char>(str[i]))) ++letters; } return letters; } std::vector<std::string> sentence(size_t count) { static const char* words[] = { "Four", "is", "the", "number", "of", "letters", "in", "the", "first", "word", "of", "this", "sentence," }; std::vector<std::string> result; result.reserve(count + 10); size_t n = std::size(words); for (size_t i = 0; i < n && i < count; ++i) { result.push_back(words[i]); } for (size_t i = 1; count > n; ++i) { n += append_number_name(result, count_letters(result[i]), false); result.push_back("in"); result.push_back("the"); n += 2; n += append_number_name(result, i + 1, true); result.back() += ','; } return result; } size_t sentence_length(const std::vector<std::string>& words) { size_t n = words.size(); if (n == 0) return 0; size_t length = n - 1; for (size_t i = 0; i < n; ++i) length += words[i].size(); return length; } int main() { std::cout.imbue(std::locale("")); size_t n = 201; auto result = sentence(n); std::cout << "Number of letters in first " << n << " words in the sequence:\n"; for (size_t i = 0; i < n; ++i) { if (i != 0) std::cout << (i % 25 == 0 ? '\n' : ' '); std::cout << std::setw(2) << count_letters(result[i]); } std::cout << '\n'; std::cout << "Sentence length: " << sentence_length(result) << '\n'; for (n = 1000; n <= 10000000; n *= 10) { result = sentence(n); const std::string& word = result[n - 1]; std::cout << "The " << n << "th word is '" << word << "' and has " << count_letters(word) << " letters. "; std::cout << "Sentence length: " << sentence_length(result) << '\n'; } return 0; }
import inflect def count_letters(word): count = 0 for letter in word: if letter != ',' and letter !='-' and letter !=' ': count += 1 return count def split_with_spaces(sentence): sentence_list = [] curr_word = "" for c in sentence: if c == " " and curr_word != "": sentence_list.append(curr_word+" ") curr_word = "" else: curr_word += c if len(curr_word) > 0: sentence_list.append(curr_word) return sentence_list def my_num_to_words(p, my_number): number_string_list = p.number_to_words(my_number, wantlist=True, andword='') number_string = number_string_list[0] for i in range(1,len(number_string_list)): number_string += " " + number_string_list[i] return number_string def build_sentence(p, max_words): sentence_list = split_with_spaces("Four is the number of letters in the first word of this sentence,") num_words = 13 word_number = 2 while num_words < max_words: ordinal_string = my_num_to_words(p, p.ordinal(word_number)) word_number_string = my_num_to_words(p, count_letters(sentence_list[word_number - 1])) new_string = " "+word_number_string+" in the "+ordinal_string+"," new_list = split_with_spaces(new_string) sentence_list += new_list num_words += len(new_list) word_number += 1 return sentence_list, num_words def word_and_counts(word_num): sentence_list, num_words = build_sentence(p, word_num) word_str = sentence_list[word_num - 1].strip(' ,') num_letters = len(word_str) num_characters = 0 for word in sentence_list: num_characters += len(word) print('Word {0:8d} is "{1}", with {2} letters. Length of the sentence so far: {3} '.format(word_num,word_str,num_letters,num_characters)) p = inflect.engine() sentence_list, num_words = build_sentence(p, 201) print(" ") print("The lengths of the first 201 words are:") print(" ") print('{0:3d}: '.format(1),end='') total_characters = 0 for word_index in range(201): word_length = count_letters(sentence_list[word_index]) total_characters += len(sentence_list[word_index]) print('{0:2d}'.format(word_length),end='') if (word_index+1) % 20 == 0: print(" ") print('{0:3d}: '.format(word_index + 2),end='') else: print(" ",end='') print(" ") print(" ") print("Length of the sentence so far: "+str(total_characters)) print(" ") word_and_counts(1000) word_and_counts(10000) word_and_counts(100000) word_and_counts(1000000) word_and_counts(10000000)
Write the same code in Python as shown below in C++.
#include <array> #include <bitset> #include <iostream> using namespace std; struct FieldDetails {string_view Name; int NumBits;}; template <const char *T> consteval auto ParseDiagram() { constexpr string_view rawArt(T); constexpr auto firstBar = rawArt.find("|"); constexpr auto lastBar = rawArt.find_last_of("|"); constexpr auto art = rawArt.substr(firstBar, lastBar - firstBar); static_assert(firstBar < lastBar, "ASCII Table has no fields"); constexpr auto numFields = count(rawArt.begin(), rawArt.end(), '|') - count(rawArt.begin(), rawArt.end(), '\n') / 2; array<FieldDetails, numFields> fields; bool isValidDiagram = true; int startDiagramIndex = 0; int totalBits = 0; for(int i = 0; i < numFields; ) { auto beginningBar = art.find("|", startDiagramIndex); auto endingBar = art.find("|", beginningBar + 1); auto field = art.substr(beginningBar + 1, endingBar - beginningBar - 1); if(field.find("-") == field.npos) { int numBits = (field.size() + 1) / 3; auto nameStart = field.find_first_not_of(" "); auto nameEnd = field.find_last_not_of(" "); if (nameStart > nameEnd || nameStart == string_view::npos) { isValidDiagram = false; field = ""sv; } else { field = field.substr(nameStart, 1 + nameEnd - nameStart); } fields[i++] = FieldDetails {field, numBits}; totalBits += numBits; } startDiagramIndex = endingBar; } int numRawBytes = isValidDiagram ? (totalBits - 1) / 8 + 1 : 0; return make_pair(fields, numRawBytes); } template <const char *T> auto Encode(auto inputValues) { constexpr auto parsedDiagram = ParseDiagram<T>(); static_assert(parsedDiagram.second > 0, "Invalid ASCII talble"); array<unsigned char, parsedDiagram.second> data; int startBit = 0; int i = 0; for(auto value : inputValues) { const auto &field = parsedDiagram.first[i++]; int remainingValueBits = field.NumBits; while(remainingValueBits > 0) { auto [fieldStartByte, fieldStartBit] = div(startBit, 8); int unusedBits = 8 - fieldStartBit; int numBitsToEncode = min({unusedBits, 8, field.NumBits}); int divisor = 1 << (remainingValueBits - numBitsToEncode); unsigned char bitsToEncode = value / divisor; data[fieldStartByte] <<= numBitsToEncode; data[fieldStartByte] |= bitsToEncode; value %= divisor; startBit += numBitsToEncode; remainingValueBits -= numBitsToEncode; } } return data; } template <const char *T> void Decode(auto data) { cout << "Name Bit Pattern\n"; cout << "======= ================\n"; constexpr auto parsedDiagram = ParseDiagram<T>(); static_assert(parsedDiagram.second > 0, "Invalid ASCII talble"); int startBit = 0; for(const auto& field : parsedDiagram.first) { auto [fieldStartByte, fieldStartBit] = div(startBit, 8); unsigned char firstByte = data[fieldStartByte]; firstByte <<= fieldStartBit; firstByte >>= fieldStartBit; int64_t value = firstByte; auto endBit = startBit + field.NumBits; auto [fieldEndByte, fieldEndBit] = div(endBit, 8); fieldEndByte = min(fieldEndByte, (int)(ssize(data) - 1)); for(int index = fieldStartByte + 1; index <= fieldEndByte; index++) { value <<= 8; value += data[index]; } value >>= fieldEndBit; startBit = endBit; cout << field.Name << string_view(" ", (7 - field.Name.size())) << " " << string_view(bitset<64>(value).to_string()).substr(64 - field.NumBits, 64) << "\n"; } } int main(void) { static constexpr char art[] = R"( +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RCODE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QDCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ANCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | NSCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ARCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+)"; auto rawData = Encode<art> (initializer_list<int64_t> { 30791, 0, 15, 0, 1, 1, 1, 3, 15, 21654, 57646, 7153, 27044 }); cout << "Raw encoded data in hex:\n"; for (auto v : rawData) printf("%.2X", v); cout << "\n\n"; cout << "Decoded raw data:\n"; Decode<art>(rawData); }
def validate(diagram): rawlines = diagram.splitlines() lines = [] for line in rawlines: if line != '': lines.append(line) if len(lines) == 0: print('diagram has no non-empty lines!') return None width = len(lines[0]) cols = (width - 1) // 3 if cols not in [8, 16, 32, 64]: print('number of columns should be 8, 16, 32 or 64') return None if len(lines)%2 == 0: print('number of non-empty lines should be odd') return None if lines[0] != (('+--' * cols)+'+'): print('incorrect header line') return None for i in range(len(lines)): line=lines[i] if i == 0: continue elif i%2 == 0: if line != lines[0]: print('incorrect separator line') return None elif len(line) != width: print('inconsistent line widths') return None elif line[0] != '|' or line[width-1] != '|': print("non-separator lines must begin and end with '|'") return None return lines def decode(lines): print("Name Bits Start End") print("======= ==== ===== ===") startbit = 0 results = [] for line in lines: infield=False for c in line: if not infield and c == '|': infield = True spaces = 0 name = '' elif infield: if c == ' ': spaces += 1 elif c != '|': name += c else: bits = (spaces + len(name) + 1) // 3 endbit = startbit + bits - 1 print('{0:7} {1:2d} {2:2d} {3:2d}'.format(name, bits, startbit, endbit)) reslist = [name, bits, startbit, endbit] results.append(reslist) spaces = 0 name = '' startbit += bits return results def unpack(results, hex): print("\nTest string in hex:") print(hex) print("\nTest string in binary:") bin = f'{int(hex, 16):0>{4*len(hex)}b}' print(bin) print("\nUnpacked:\n") print("Name Size Bit pattern") print("======= ==== ================") for r in results: name = r[0] size = r[1] startbit = r[2] endbit = r[3] bitpattern = bin[startbit:endbit+1] print('{0:7} {1:2d} {2:16}'.format(name, size, bitpattern)) diagram = lines = validate(diagram) if lines == None: print("No lines returned") else: print(" ") print("Diagram after trimming whitespace and removal of blank lines:") print(" ") for line in lines: print(line) print(" ") print("Decoded:") print(" ") results = decode(lines) hex = "78477bbf5496e12e1bf169a4" unpack(results, hex)
Port the provided C++ code into Python while preserving the original functionality.
#include <algorithm> #include <coroutine> #include <iostream> #include <memory> #include <tuple> #include <variant> using namespace std; class BinaryTree { using Node = tuple<BinaryTree, int, BinaryTree>; unique_ptr<Node> m_tree; public: BinaryTree() = default; BinaryTree(BinaryTree&& leftChild, int value, BinaryTree&& rightChild) : m_tree {make_unique<Node>(move(leftChild), value, move(rightChild))} {} BinaryTree(int value) : BinaryTree(BinaryTree{}, value, BinaryTree{}){} BinaryTree(BinaryTree&& leftChild, int value) : BinaryTree(move(leftChild), value, BinaryTree{}){} BinaryTree(int value, BinaryTree&& rightChild) : BinaryTree(BinaryTree{}, value, move(rightChild)){} explicit operator bool() const { return (bool)m_tree; } int Value() const { return get<1>(*m_tree); } const BinaryTree& LeftChild() const { return get<0>(*m_tree); } const BinaryTree& RightChild() const { return get<2>(*m_tree); } }; struct TreeWalker { struct promise_type { int val; suspend_never initial_suspend() noexcept {return {};} suspend_never return_void() noexcept {return {};} suspend_always final_suspend() noexcept {return {};} void unhandled_exception() noexcept { } TreeWalker get_return_object() { return TreeWalker{coroutine_handle<promise_type>::from_promise(*this)}; } suspend_always yield_value(int x) noexcept { val=x; return {}; } }; coroutine_handle<promise_type> coro; TreeWalker(coroutine_handle<promise_type> h): coro(h) {} ~TreeWalker() { if(coro) coro.destroy(); } class Iterator { const coroutine_handle<promise_type>* m_h = nullptr; public: Iterator() = default; constexpr Iterator(const coroutine_handle<promise_type>* h) : m_h(h){} Iterator& operator++() { m_h->resume(); return *this; } Iterator operator++(int) { auto old(*this); m_h->resume(); return old; } int operator*() const { return m_h->promise().val; } bool operator!=(monostate) const noexcept { return !m_h->done(); return m_h && !m_h->done(); } bool operator==(monostate) const noexcept { return !operator!=(monostate{}); } }; constexpr Iterator begin() const noexcept { return Iterator(&coro); } constexpr monostate end() const noexcept { return monostate{}; } }; namespace std { template<> class iterator_traits<TreeWalker::Iterator> { public: using difference_type = std::ptrdiff_t; using size_type = std::size_t; using value_type = int; using pointer = int*; using reference = int&; using iterator_category = std::input_iterator_tag; }; } TreeWalker WalkFringe(const BinaryTree& tree) { if(tree) { auto& left = tree.LeftChild(); auto& right = tree.RightChild(); if(!left && !right) { co_yield tree.Value(); } for(auto v : WalkFringe(left)) { co_yield v; } for(auto v : WalkFringe(right)) { co_yield v; } } co_return; } void PrintTree(const BinaryTree& tree) { if(tree) { cout << "("; PrintTree(tree.LeftChild()); cout << tree.Value(); PrintTree(tree.RightChild()); cout <<")"; } } void Compare(const BinaryTree& tree1, const BinaryTree& tree2) { auto walker1 = WalkFringe(tree1); auto walker2 = WalkFringe(tree2); bool sameFringe = ranges::equal(walker1.begin(), walker1.end(), walker2.begin(), walker2.end()); PrintTree(tree1); cout << (sameFringe ? " has same fringe as " : " has different fringe than "); PrintTree(tree2); cout << "\n"; } int main() { BinaryTree tree1(BinaryTree{6}, 77, BinaryTree{BinaryTree{3}, 77, BinaryTree{77, BinaryTree{9}}}); BinaryTree tree2(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{ BinaryTree{3}, 77, BinaryTree{9}}}); BinaryTree tree3(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{77, BinaryTree{9}}}); Compare(tree1, tree2); Compare(tree1, tree3); }
try: from itertools import zip_longest as izip_longest except: from itertools import izip_longest def fringe(tree): for node1 in tree: if isinstance(node1, tuple): for node2 in fringe(node1): yield node2 else: yield node1 def same_fringe(tree1, tree2): return all(node1 == node2 for node1, node2 in izip_longest(fringe(tree1), fringe(tree2))) if __name__ == '__main__': a = 1, 2, 3, 4, 5, 6, 7, 8 b = 1, (( 2, 3 ), (4, (5, ((6, 7), 8)))) c = (((1, 2), 3), 4), 5, 6, 7, 8 x = 1, 2, 3, 4, 5, 6, 7, 8, 9 y = 0, 2, 3, 4, 5, 6, 7, 8 z = 1, 2, (4, 3), 5, 6, 7, 8 assert same_fringe(a, a) assert same_fringe(a, b) assert same_fringe(a, c) assert not same_fringe(a, x) assert not same_fringe(a, y) assert not same_fringe(a, z)
Transform the following C++ implementation into Python, maintaining the same output and logic.
#include <iostream> #include <vector> enum class Piece { empty, black, white }; typedef std::pair<int, int> position; bool isAttacking(const position &queen, const position &pos) { return queen.first == pos.first || queen.second == pos.second || abs(queen.first - pos.first) == abs(queen.second - pos.second); } bool place(const int m, const int n, std::vector<position> &pBlackQueens, std::vector<position> &pWhiteQueens) { if (m == 0) { return true; } bool placingBlack = true; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { auto pos = std::make_pair(i, j); for (auto queen : pBlackQueens) { if (queen == pos || !placingBlack && isAttacking(queen, pos)) { goto inner; } } for (auto queen : pWhiteQueens) { if (queen == pos || placingBlack && isAttacking(queen, pos)) { goto inner; } } if (placingBlack) { pBlackQueens.push_back(pos); placingBlack = false; } else { pWhiteQueens.push_back(pos); if (place(m - 1, n, pBlackQueens, pWhiteQueens)) { return true; } pBlackQueens.pop_back(); pWhiteQueens.pop_back(); placingBlack = true; } inner: {} } } if (!placingBlack) { pBlackQueens.pop_back(); } return false; } void printBoard(int n, const std::vector<position> &blackQueens, const std::vector<position> &whiteQueens) { std::vector<Piece> board(n * n); std::fill(board.begin(), board.end(), Piece::empty); for (auto &queen : blackQueens) { board[queen.first * n + queen.second] = Piece::black; } for (auto &queen : whiteQueens) { board[queen.first * n + queen.second] = Piece::white; } for (size_t i = 0; i < board.size(); ++i) { if (i != 0 && i % n == 0) { std::cout << '\n'; } switch (board[i]) { case Piece::black: std::cout << "B "; break; case Piece::white: std::cout << "W "; break; case Piece::empty: default: int j = i / n; int k = i - j * n; if (j % 2 == k % 2) { std::cout << "x "; } else { std::cout << "* "; } break; } } std::cout << "\n\n"; } int main() { std::vector<position> nms = { {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3}, {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5}, {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6}, {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7}, }; for (auto nm : nms) { std::cout << nm.second << " black and " << nm.second << " white queens on a " << nm.first << " x " << nm.first << " board:\n"; std::vector<position> blackQueens, whiteQueens; if (place(nm.second, nm.first, blackQueens, whiteQueens)) { printBoard(nm.first, blackQueens, whiteQueens); } else { std::cout << "No solution exists.\n\n"; } } return 0; }
from itertools import combinations, product, count from functools import lru_cache, reduce _bbullet, _wbullet = '\u2022\u25E6' _or = set.__or__ def place(m, n): "Place m black and white queens, peacefully, on an n-by-n board" board = set(product(range(n), repeat=2)) placements = {frozenset(c) for c in combinations(board, m)} for blacks in placements: black_attacks = reduce(_or, (queen_attacks_from(pos, n) for pos in blacks), set()) for whites in {frozenset(c) for c in combinations(board - black_attacks, m)}: if not black_attacks & whites: return blacks, whites return set(), set() @lru_cache(maxsize=None) def queen_attacks_from(pos, n): x0, y0 = pos a = set([pos]) a.update((x, y0) for x in range(n)) a.update((x0, y) for y in range(n)) for x1 in range(n): y1 = y0 -x0 +x1 if 0 <= y1 < n: a.add((x1, y1)) y1 = y0 +x0 -x1 if 0 <= y1 < n: a.add((x1, y1)) return a def pboard(black_white, n): "Print board" if black_white is None: blk, wht = set(), set() else: blk, wht = black_white print(f" f"on a {n}-by-{n} board:", end='') for x, y in product(range(n), repeat=2): if y == 0: print() xy = (x, y) ch = ('?' if xy in blk and xy in wht else 'B' if xy in blk else 'W' if xy in wht else _bbullet if (x + y)%2 else _wbullet) print('%s' % ch, end='') print() if __name__ == '__main__': n=2 for n in range(2, 7): print() for m in count(1): ans = place(m, n) if ans[0]: pboard(ans, n) else: print (f" break print('\n') m, n = 5, 7 ans = place(m, n) pboard(ans, n)
Generate an equivalent Python version of this C++ code.
#include <iostream> #include <iomanip> #include <bitset> const int LIMIT = 100000; std::bitset<16> digitset(int num, int base) { std::bitset<16> set; for (; num; num /= base) set.set(num % base); return set; } int main() { int c = 0; for (int i=0; i<LIMIT; i++) { if (digitset(i,10) == digitset(i,16)) { std::cout << std::setw(7) << i; if (++c % 10 == 0) std::cout << std::endl; } } std::cout << std::endl; return 0; }
col = 0 for i in range(100000): if set(str(i)) == set(hex(i)[2:]): col += 1 print("{:7}".format(i), end='\n'[:col % 10 == 0]) print()
Produce a language-to-language conversion: from C++ to Python, same semantics.
#include <cassert> #include <iomanip> #include <iostream> int largest_proper_divisor(int n) { assert(n > 0); if ((n & 1) == 0) return n >> 1; for (int p = 3; p * p <= n; p += 2) { if (n % p == 0) return n / p; } return 1; } int main() { for (int n = 1; n < 101; ++n) { std::cout << std::setw(2) << largest_proper_divisor(n) << (n % 10 == 0 ? '\n' : ' '); } }
def lpd(n): for i in range(n-1,0,-1): if n%i==0: return i return 1 for i in range(1,101): print("{:3}".format(lpd(i)), end=i%10==0 and '\n' or '')
Write the same code in Python as shown below in C++.
#include <iostream> #include <iterator> #include <sstream> #include <vector> using namespace std; class MTF { public: string encode( string str ) { fillSymbolTable(); vector<int> output; for( string::iterator it = str.begin(); it != str.end(); it++ ) { for( int i = 0; i < 26; i++ ) { if( *it == symbolTable[i] ) { output.push_back( i ); moveToFront( i ); break; } } } string r; for( vector<int>::iterator it = output.begin(); it != output.end(); it++ ) { ostringstream ss; ss << *it; r += ss.str() + " "; } return r; } string decode( string str ) { fillSymbolTable(); istringstream iss( str ); vector<int> output; copy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) ); string r; for( vector<int>::iterator it = output.begin(); it != output.end(); it++ ) { r.append( 1, symbolTable[*it] ); moveToFront( *it ); } return r; } private: void moveToFront( int i ) { char t = symbolTable[i]; for( int z = i - 1; z >= 0; z-- ) symbolTable[z + 1] = symbolTable[z]; symbolTable[0] = t; } void fillSymbolTable() { for( int x = 0; x < 26; x++ ) symbolTable[x] = x + 'a'; } char symbolTable[26]; }; int main() { MTF mtf; string a, str[] = { "broood", "bananaaa", "hiphophiphop" }; for( int x = 0; x < 3; x++ ) { a = str[x]; cout << a << " -> encoded = "; a = mtf.encode( a ); cout << a << "; decoded = " << mtf.decode( a ) << endl; } return 0; }
from __future__ import print_function from string import ascii_lowercase SYMBOLTABLE = list(ascii_lowercase) def move2front_encode(strng, symboltable): sequence, pad = [], symboltable[::] for char in strng: indx = pad.index(char) sequence.append(indx) pad = [pad.pop(indx)] + pad return sequence def move2front_decode(sequence, symboltable): chars, pad = [], symboltable[::] for indx in sequence: char = pad[indx] chars.append(char) pad = [pad.pop(indx)] + pad return ''.join(chars) if __name__ == '__main__': for s in ['broood', 'bananaaa', 'hiphophiphop']: encode = move2front_encode(s, SYMBOLTABLE) print('%14r encodes to %r' % (s, encode), end=', ') decode = move2front_decode(encode, SYMBOLTABLE) print('which decodes back to %r' % decode) assert s == decode, 'Whoops!'
Maintain the same structure and functionality when rewriting this code in Python.
#include <array> #include <cstdio> #include <numeric> void PrintContainer(const auto& vec) { int count = 0; for(auto value : vec) { printf("%7d%c", value, ++count % 10 == 0 ? '\n' : ' '); } } int main() { auto cube = [](auto x){return x * x * x;}; std::array<int, 50> a; std::iota(a.begin(), a.end(), 0); std::transform_inclusive_scan(a.begin(), a.end(), a.begin(), std::plus{}, cube); PrintContainer(a); }
def main(): fila = 0 lenCubos = 51 print("Suma de N cubos para n = [0..49]\n") for n in range(1, lenCubos): sumCubos = 0 for m in range(1, n): sumCubos = sumCubos + (m ** 3) fila += 1 print(f'{sumCubos:7} ', end='') if fila % 5 == 0: print(" ") print(f"\nEncontrados {fila} cubos.") if __name__ == '__main__': main()
Ensure the translated Python code behaves exactly like the original C++ snippet.
#include <array> #include <cstdio> #include <numeric> void PrintContainer(const auto& vec) { int count = 0; for(auto value : vec) { printf("%7d%c", value, ++count % 10 == 0 ? '\n' : ' '); } } int main() { auto cube = [](auto x){return x * x * x;}; std::array<int, 50> a; std::iota(a.begin(), a.end(), 0); std::transform_inclusive_scan(a.begin(), a.end(), a.begin(), std::plus{}, cube); PrintContainer(a); }
def main(): fila = 0 lenCubos = 51 print("Suma de N cubos para n = [0..49]\n") for n in range(1, lenCubos): sumCubos = 0 for m in range(1, n): sumCubos = sumCubos + (m ** 3) fila += 1 print(f'{sumCubos:7} ', end='') if fila % 5 == 0: print(" ") print(f"\nEncontrados {fila} cubos.") if __name__ == '__main__': main()
Please provide an equivalent version of this C++ code in Python.
#include <complex> #include <math.h> #include <iostream> template<class Type> struct Precision { public: static Type GetEps() { return eps; } static void SetEps(Type e) { eps = e; } private: static Type eps; }; template<class Type> Type Precision<Type>::eps = static_cast<Type>(1E-7); template<class DigType> bool IsDoubleEqual(DigType d1, DigType d2) { return (fabs(d1 - d2) < Precision<DigType>::GetEps()); } template<class DigType> DigType IntegerPart(DigType value) { return (value > 0) ? floor(value) : ceil(value); } template<class DigType> DigType FractionPart(DigType value) { return fabs(IntegerPart<DigType>(value) - value); } template<class Type> bool IsInteger(const Type& value) { return false; } #define GEN_CHECK_INTEGER(type) \ template<> \ bool IsInteger<type>(const type& value) \ { \ return true; \ } #define GEN_CHECK_CMPL_INTEGER(type) \ template<> \ bool IsInteger<std::complex<type> >(const std::complex<type>& value) \ { \ type zero = type(); \ return value.imag() == zero; \ } #define GEN_CHECK_REAL(type) \ template<> \ bool IsInteger<type>(const type& value) \ { \ type zero = type(); \ return IsDoubleEqual<type>(FractionPart<type>(value), zero); \ } #define GEN_CHECK_CMPL_REAL(type) \ template<> \ bool IsInteger<std::complex<type> >(const std::complex<type>& value) \ { \ type zero = type(); \ return IsDoubleEqual<type>(value.imag(), zero); \ } #define GEN_INTEGER(type) \ GEN_CHECK_INTEGER(type) \ GEN_CHECK_CMPL_INTEGER(type) #define GEN_REAL(type) \ GEN_CHECK_REAL(type) \ GEN_CHECK_CMPL_REAL(type) GEN_INTEGER(char) GEN_INTEGER(unsigned char) GEN_INTEGER(short) GEN_INTEGER(unsigned short) GEN_INTEGER(int) GEN_INTEGER(unsigned int) GEN_INTEGER(long) GEN_INTEGER(unsigned long) GEN_INTEGER(long long) GEN_INTEGER(unsigned long long) GEN_REAL(float) GEN_REAL(double) GEN_REAL(long double) template<class Type> inline void TestValue(const Type& value) { std::cout << "Value: " << value << " of type: " << typeid(Type).name() << " is integer - " << std::boolalpha << IsInteger(value) << std::endl; } int main() { char c = -100; unsigned char uc = 200; short s = c; unsigned short us = uc; int i = s; unsigned int ui = us; long long ll = i; unsigned long long ull = ui; std::complex<unsigned int> ci1(2, 0); std::complex<int> ci2(2, 4); std::complex<int> ci3(-2, 4); std::complex<unsigned short> cs1(2, 0); std::complex<short> cs2(2, 4); std::complex<short> cs3(-2, 4); std::complex<double> cd1(2, 0); std::complex<float> cf1(2, 4); std::complex<double> cd2(-2, 4); float f1 = 1.0; float f2 = -2.0; float f3 = -2.4f; float f4 = 1.23e-5f; float f5 = 1.23e-10f; double d1 = f5; TestValue(c); TestValue(uc); TestValue(s); TestValue(us); TestValue(i); TestValue(ui); TestValue(ll); TestValue(ull); TestValue(ci1); TestValue(ci2); TestValue(ci3); TestValue(cs1); TestValue(cs2); TestValue(cs3); TestValue(cd1); TestValue(cd2); TestValue(cf1); TestValue(f1); TestValue(f2); TestValue(f3); TestValue(f4); TestValue(f5); std::cout << "Set float precision: 1e-15f\n"; Precision<float>::SetEps(1e-15f); TestValue(f5); TestValue(d1); return 0; }
>>> def isint(f): return complex(f).imag == 0 and complex(f).real.is_integer() >>> [isint(f) for f in (1.0, 2, (3.0+0.0j), 4.1, (3+4j), (5.6+0j))] [True, True, True, False, False, False] >>> ... >>> isint(25.000000) True >>> isint(24.999999) False >>> isint(25.000100) False >>> isint(-2.1e120) True >>> isint(-5e-2) False >>> isint(float('nan')) False >>> isint(float('inf')) False >>> isint(5.0+0.0j) True >>> isint(5-5j) False
Translate this program into Python but keep the logic exactly as in C++.
#include <vector> #include <list> #include <algorithm> #include <iostream> template <typename T> struct Node { T value; Node* prev_node; }; template <typename Container> Container lis(const Container& values) { using E = typename Container::value_type; using NodePtr = Node<E>*; using ConstNodePtr = const NodePtr; std::vector<NodePtr> pileTops; std::vector<Node<E>> nodes(values.size()); auto cur_node = std::begin(nodes); for (auto cur_value = std::begin(values); cur_value != std::end(values); ++cur_value, ++cur_node) { auto node = &*cur_node; node->value = *cur_value; auto lb = std::lower_bound(pileTops.begin(), pileTops.end(), node, [](ConstNodePtr& node1, ConstNodePtr& node2) -> bool { return node1->value < node2->value; }); if (lb != pileTops.begin()) node->prev_node = *std::prev(lb); if (lb == pileTops.end()) pileTops.push_back(node); else *lb = node; } Container result(pileTops.size()); auto r = std::rbegin(result); for (NodePtr node = pileTops.back(); node != nullptr; node = node->prev_node, ++r) *r = node->value; return result; } template <typename Container> void show_lis(const Container& values) { auto&& result = lis(values); for (auto& r : result) { std::cout << r << ' '; } std::cout << std::endl; } int main() { show_lis(std::list<int> { 3, 2, 6, 4, 5, 1 }); show_lis(std::vector<int> { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 }); }
def longest_increasing_subsequence(X): N = len(X) P = [0] * N M = [0] * (N+1) L = 0 for i in range(N): lo = 1 hi = L while lo <= hi: mid = (lo+hi)//2 if (X[M[mid]] < X[i]): lo = mid+1 else: hi = mid-1 newL = lo P[i] = M[newL-1] M[newL] = i if (newL > L): L = newL S = [] k = M[L] for i in range(L-1, -1, -1): S.append(X[k]) k = P[k] return S[::-1] if __name__ == '__main__': for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]: print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))
Preserve the algorithm and functionality while converting the code from C++ to Python.
#include <algorithm> #include <iostream> #include <iterator> #include <vector> const int luckySize = 60000; std::vector<int> luckyEven(luckySize); std::vector<int> luckyOdd(luckySize); void init() { for (int i = 0; i < luckySize; ++i) { luckyEven[i] = i * 2 + 2; luckyOdd[i] = i * 2 + 1; } } void filterLuckyEven() { for (size_t n = 2; n < luckyEven.size(); ++n) { int m = luckyEven[n - 1]; int end = (luckyEven.size() / m) * m - 1; for (int j = end; j >= m - 1; j -= m) { std::copy(luckyEven.begin() + j + 1, luckyEven.end(), luckyEven.begin() + j); luckyEven.pop_back(); } } } void filterLuckyOdd() { for (size_t n = 2; n < luckyOdd.size(); ++n) { int m = luckyOdd[n - 1]; int end = (luckyOdd.size() / m) * m - 1; for (int j = end; j >= m - 1; j -= m) { std::copy(luckyOdd.begin() + j + 1, luckyOdd.end(), luckyOdd.begin() + j); luckyOdd.pop_back(); } } } void printBetween(size_t j, size_t k, bool even) { std::ostream_iterator<int> out_it{ std::cout, ", " }; if (even) { size_t max = luckyEven.back(); if (j > max || k > max) { std::cerr << "At least one are is too big\n"; exit(EXIT_FAILURE); } std::cout << "Lucky even numbers between " << j << " and " << k << " are: "; std::copy_if(luckyEven.begin(), luckyEven.end(), out_it, [j, k](size_t n) { return j <= n && n <= k; }); } else { size_t max = luckyOdd.back(); if (j > max || k > max) { std::cerr << "At least one are is too big\n"; exit(EXIT_FAILURE); } std::cout << "Lucky numbers between " << j << " and " << k << " are: "; std::copy_if(luckyOdd.begin(), luckyOdd.end(), out_it, [j, k](size_t n) { return j <= n && n <= k; }); } std::cout << '\n'; } void printRange(size_t j, size_t k, bool even) { std::ostream_iterator<int> out_it{ std::cout, ", " }; if (even) { if (k >= luckyEven.size()) { std::cerr << "The argument is too large\n"; exit(EXIT_FAILURE); } std::cout << "Lucky even numbers " << j << " to " << k << " are: "; std::copy(luckyEven.begin() + j - 1, luckyEven.begin() + k, out_it); } else { if (k >= luckyOdd.size()) { std::cerr << "The argument is too large\n"; exit(EXIT_FAILURE); } std::cout << "Lucky numbers " << j << " to " << k << " are: "; std::copy(luckyOdd.begin() + j - 1, luckyOdd.begin() + k, out_it); } } void printSingle(size_t j, bool even) { if (even) { if (j >= luckyEven.size()) { std::cerr << "The argument is too large\n"; exit(EXIT_FAILURE); } std::cout << "Lucky even number " << j << "=" << luckyEven[j - 1] << '\n'; } else { if (j >= luckyOdd.size()) { std::cerr << "The argument is too large\n"; exit(EXIT_FAILURE); } std::cout << "Lucky number " << j << "=" << luckyOdd[j - 1] << '\n'; } } void help() { std::cout << "./lucky j [k] [--lucky|--evenLucky]\n"; std::cout << "\n"; std::cout << " argument(s) | what is displayed\n"; std::cout << "==============================================\n"; std::cout << "-j=m | mth lucky number\n"; std::cout << "-j=m --lucky | mth lucky number\n"; std::cout << "-j=m --evenLucky | mth even lucky number\n"; std::cout << "-j=m -k=n | mth through nth (inclusive) lucky numbers\n"; std::cout << "-j=m -k=n --lucky | mth through nth (inclusive) lucky numbers\n"; std::cout << "-j=m -k=n --evenLucky | mth through nth (inclusive) even lucky numbers\n"; std::cout << "-j=m -k=-n | all lucky numbers in the range [m, n]\n"; std::cout << "-j=m -k=-n --lucky | all lucky numbers in the range [m, n]\n"; std::cout << "-j=m -k=-n --evenLucky | all even lucky numbers in the range [m, n]\n"; } int main(int argc, char **argv) { bool evenLucky = false; int j = 0; int k = 0; if (argc < 2) { help(); exit(EXIT_FAILURE); } bool good = false; for (int i = 1; i < argc; ++i) { if ('-' == argv[i][0]) { if ('-' == argv[i][1]) { if (0 == strcmp("--lucky", argv[i])) { evenLucky = false; } else if (0 == strcmp("--evenLucky", argv[i])) { evenLucky = true; } else { std::cerr << "Unknown long argument: [" << argv[i] << "]\n"; exit(EXIT_FAILURE); } } else { if ('j' == argv[i][1] && '=' == argv[i][2] && argv[i][3] != 0) { good = true; j = atoi(&argv[i][3]); } else if ('k' == argv[i][1] && '=' == argv[i][2]) { k = atoi(&argv[i][3]); } else { std::cerr << "Unknown short argument: " << argv[i] << '\n'; exit(EXIT_FAILURE); } } } else { std::cerr << "Unknown argument: " << argv[i] << '\n'; exit(EXIT_FAILURE); } } if (!good) { help(); exit(EXIT_FAILURE); } init(); filterLuckyEven(); filterLuckyOdd(); if (k > 0) { printRange(j, k, evenLucky); } else if (k < 0) { printBetween(j, -k, evenLucky); } else { printSingle(j, evenLucky); } return 0; }
from __future__ import print_function def lgen(even=False, nmax=1000000): start = 2 if even else 1 n, lst = 1, list(range(start, nmax + 1, 2)) lenlst = len(lst) yield lst[0] while n < lenlst and lst[n] < lenlst: yield lst[n] n, lst = n + 1, [j for i,j in enumerate(lst, 1) if i % lst[n]] lenlst = len(lst) for i in lst[n:]: yield i
Rewrite the snippet below in Python so it works the same as the original C++ code.
#include <iostream> #include <iterator> #include <string> #include <utility> #include <vector> namespace detail { template <typename ForwardIterator> class tokenizer { ForwardIterator _tbegin, _tend, _end; public: tokenizer(ForwardIterator begin, ForwardIterator end) : _tbegin(begin), _tend(begin), _end(end) { } template <typename Lambda> bool next(Lambda istoken) { if (_tbegin == _end) { return false; } _tbegin = _tend; for (; _tend != _end && !istoken(*_tend); ++_tend) { if (*_tend == '\\' && std::next(_tend) != _end) { ++_tend; } } if (_tend == _tbegin) { _tend++; } return _tbegin != _end; } ForwardIterator begin() const { return _tbegin; } ForwardIterator end() const { return _tend; } bool operator==(char c) { return *_tbegin == c; } }; template <typename List> void append_all(List & lista, const List & listb) { if (listb.size() == 1) { for (auto & a : lista) { a += listb.back(); } } else { List tmp; for (auto & a : lista) { for (auto & b : listb) { tmp.push_back(a + b); } } lista = std::move(tmp); } } template <typename String, typename List, typename Tokenizer> List expand(Tokenizer & token) { std::vector<List> alts{ { String() } }; while (token.next([](char c) { return c == '{' || c == ',' || c == '}'; })) { if (token == '{') { append_all(alts.back(), expand<String, List>(token)); } else if (token == ',') { alts.push_back({ String() }); } else if (token == '}') { if (alts.size() == 1) { for (auto & a : alts.back()) { a = '{' + a + '}'; } return alts.back(); } else { for (std::size_t i = 1; i < alts.size(); i++) { alts.front().insert(alts.front().end(), std::make_move_iterator(std::begin(alts[i])), std::make_move_iterator(std::end(alts[i]))); } return std::move(alts.front()); } } else { for (auto & a : alts.back()) { a.append(token.begin(), token.end()); } } } List result{ String{ '{' } }; append_all(result, alts.front()); for (std::size_t i = 1; i < alts.size(); i++) { for (auto & a : result) { a += ','; } append_all(result, alts[i]); } return result; } } template < typename ForwardIterator, typename String = std::basic_string< typename std::iterator_traits<ForwardIterator>::value_type >, typename List = std::vector<String> > List expand(ForwardIterator begin, ForwardIterator end) { detail::tokenizer<ForwardIterator> token(begin, end); List list{ String() }; while (token.next([](char c) { return c == '{'; })) { if (token == '{') { detail::append_all(list, detail::expand<String, List>(token)); } else { for (auto & a : list) { a.append(token.begin(), token.end()); } } } return list; } template < typename Range, typename String = std::basic_string<typename Range::value_type>, typename List = std::vector<String> > List expand(const Range & range) { using Iterator = typename Range::const_iterator; return expand<Iterator, String, List>(std::begin(range), std::end(range)); } int main() { for (std::string string : { R"(~/{Downloads,Pictures}/*.{jpg,gif,png})", R"(It{{em,alic}iz,erat}e{d,}, please.)", R"({,{,gotta have{ ,\, again\, }}more }cowbell!)", R"({}} some {\\{edge,edgy} }{ cases, here\\\})", R"(a{b{1,2}c)", R"(a{1,2}b}c)", R"(a{1,{2},3}b)", R"(a{b{1,2}c{}})", R"(more{ darn{ cowbell,},})", R"(ab{c,d\,e{f,g\h},i\,j{k,l\,m}n,o\,p}qr)", R"({a,{\,b}c)", R"(a{b,{{c}})", R"({a{\}b,c}d)", R"({a,b{{1,2}e}f)", R"({}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\})", R"({{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{)", }) { std::cout << string << '\n'; for (auto expansion : expand(string)) { std::cout << " " << expansion << '\n'; } std::cout << '\n'; } return 0; }
def getitem(s, depth=0): out = [""] while s: c = s[0] if depth and (c == ',' or c == '}'): return out,s if c == '{': x = getgroup(s[1:], depth+1) if x: out,s = [a+b for a in out for b in x[0]], x[1] continue if c == '\\' and len(s) > 1: s, c = s[1:], c + s[1] out, s = [a+c for a in out], s[1:] return out,s def getgroup(s, depth): out, comma = [], False while s: g,s = getitem(s, depth) if not s: break out += g if s[0] == '}': if comma: return out, s[1:] return ['{' + a + '}' for a in out], s[1:] if s[0] == ',': comma,s = True, s[1:] return None for s in .split('\n'): print "\n\t".join([s] + getitem(s)[0]) + "\n"
Please provide an equivalent version of this C++ code in Python.
#include <array> #include <iostream> #include <vector> constexpr int MAX = 12; static std::vector<char> sp; static std::array<int, MAX> count; static int pos = 0; int factSum(int n) { int s = 0; int x = 0; int f = 1; while (x < n) { f *= ++x; s += f; } return s; } bool r(int n) { if (n == 0) { return false; } char c = sp[pos - n]; if (--count[n] == 0) { count[n] = n; if (!r(n - 1)) { return false; } } sp[pos++] = c; return true; } void superPerm(int n) { pos = n; int len = factSum(n); if (len > 0) { sp.resize(len); } for (size_t i = 0; i <= n; i++) { count[i] = i; } for (size_t i = 1; i <= n; i++) { sp[i - 1] = '0' + i; } while (r(n)) {} } int main() { for (size_t n = 0; n < MAX; n++) { superPerm(n); std::cout << "superPerm(" << n << ") len = " << sp.size() << '\n'; } return 0; }
"Generate a short Superpermutation of n characters A... as a string using various algorithms." from __future__ import print_function, division from itertools import permutations from math import factorial import string import datetime import gc MAXN = 7 def s_perm0(n): allchars = string.ascii_uppercase[:n] allperms = [''.join(p) for p in permutations(allchars)] sp, tofind = allperms[0], set(allperms[1:]) while tofind: for skip in range(1, n): for trial_add in (''.join(p) for p in permutations(sp[-n:][:skip])): trial_perm = (sp + trial_add)[-n:] if trial_perm in tofind: sp += trial_add tofind.discard(trial_perm) trial_add = None break if trial_add is None: break assert all(perm in sp for perm in allperms) return sp def s_perm1(n): allchars = string.ascii_uppercase[:n] allperms = [''.join(p) for p in sorted(permutations(allchars))] perms, sp = allperms[::], '' while perms: nxt = perms.pop() if nxt not in sp: sp += nxt assert all(perm in sp for perm in allperms) return sp def s_perm2(n): allchars = string.ascii_uppercase[:n] allperms = [''.join(p) for p in sorted(permutations(allchars))] perms, sp = allperms[::], '' while perms: nxt = perms.pop(0) if nxt not in sp: sp += nxt if perms: nxt = perms.pop(-1) if nxt not in sp: sp += nxt assert all(perm in sp for perm in allperms) return sp def _s_perm3(n, cmp): allchars = string.ascii_uppercase[:n] allperms = [''.join(p) for p in sorted(permutations(allchars))] perms, sp = allperms[::], '' while perms: lastn = sp[-n:] nxt = cmp(perms, key=lambda pm: sum((ch1 == ch2) for ch1, ch2 in zip(pm, lastn))) perms.remove(nxt) if nxt not in sp: sp += nxt assert all(perm in sp for perm in allperms) return sp def s_perm3_max(n): return _s_perm3(n, max) def s_perm3_min(n): return _s_perm3(n, min) longest = [factorial(n) * n for n in range(MAXN + 1)] weight, runtime = {}, {} print(__doc__) for algo in [s_perm0, s_perm1, s_perm2, s_perm3_max, s_perm3_min]: print('\n print(algo.__doc__) weight[algo.__name__], runtime[algo.__name__] = 1, datetime.timedelta(0) for n in range(1, MAXN + 1): gc.collect() gc.disable() t = datetime.datetime.now() sp = algo(n) t = datetime.datetime.now() - t gc.enable() runtime[algo.__name__] += t lensp = len(sp) wt = (lensp / longest[n]) ** 2 print(' For N=%i: SP length %5i Max: %5i Weight: %5.2f' % (n, lensp, longest[n], wt)) weight[algo.__name__] *= wt weight[algo.__name__] **= 1 / n weight[algo.__name__] = 1 / weight[algo.__name__] print('%*s Overall Weight: %5.2f in %.1f seconds.' % (29, '', weight[algo.__name__], runtime[algo.__name__].total_seconds())) print('\n print('\n'.join('%12s (%.3f)' % kv for kv in sorted(weight.items(), key=lambda keyvalue: -keyvalue[1]))) print('\n print('\n'.join('%12s (%.3f)' % (k, v.total_seconds()) for k, v in sorted(runtime.items(), key=lambda keyvalue: keyvalue[1])))
Generate a Python translation of this C++ snippet without changing its computational steps.
#ifndef INTERACTION_H #define INTERACTION_H #include <QWidget> class QPushButton ; class QLineEdit ; class QVBoxLayout ; class MyWidget : public QWidget { Q_OBJECT public : MyWidget( QWidget *parent = 0 ) ; private : QLineEdit *entryField ; QPushButton *increaseButton ; QPushButton *randomButton ; QVBoxLayout *myLayout ; private slots : void doIncrement( ) ; void findRandomNumber( ) ; } ; #endif
import random, tkMessageBox from Tkinter import * window = Tk() window.geometry("300x50+100+100") options = { "padx":5, "pady":5} s=StringVar() s.set(1) def increase(): s.set(int(s.get())+1) def rand(): if tkMessageBox.askyesno("Confirmation", "Reset to random value ?"): s.set(random.randrange(0,5000)) def update(e): if not e.char.isdigit(): tkMessageBox.showerror('Error', 'Invalid input !') return "break" e = Entry(text=s) e.grid(column=0, row=0, **options) e.bind('<Key>', update) b1 = Button(text="Increase", command=increase, **options ) b1.grid(column=1, row=0, **options) b2 = Button(text="Random", command=rand, **options) b2.grid(column=2, row=0, **options) mainloop()
Rewrite the snippet below in Python so it works the same as the original C++ code.
#include <random> #include <iostream> #include <iterator> #include <algorithm> using namespace std; mt19937 engine; unsigned int one_of_n(unsigned int n) { unsigned int choice; for(unsigned int i = 0; i < n; ++i) { uniform_int_distribution<unsigned int> distribution(0, i); if(!distribution(engine)) choice = i; } return choice; } int main() { engine = mt19937(random_device()()); unsigned int results[10] = {0}; for(unsigned int i = 0; i < 1000000; ++i) results[one_of_n(10)]++; ostream_iterator<unsigned int> out_it(cout, " "); copy(results, results+10, out_it); cout << '\n'; }
from random import randrange try: range = xrange except: pass def one_of_n(lines): choice = None for i, line in enumerate(lines): if randrange(i+1) == 0: choice = line return choice def one_of_n_test(n=10, trials=1000000): bins = [0] * n if n: for i in range(trials): bins[one_of_n(range(n))] += 1 return bins print(one_of_n_test())
Rewrite this program in Python while keeping its functionality equivalent to the C++ version.
#include <random> #include <iostream> #include <iterator> #include <algorithm> using namespace std; mt19937 engine; unsigned int one_of_n(unsigned int n) { unsigned int choice; for(unsigned int i = 0; i < n; ++i) { uniform_int_distribution<unsigned int> distribution(0, i); if(!distribution(engine)) choice = i; } return choice; } int main() { engine = mt19937(random_device()()); unsigned int results[10] = {0}; for(unsigned int i = 0; i < 1000000; ++i) results[one_of_n(10)]++; ostream_iterator<unsigned int> out_it(cout, " "); copy(results, results+10, out_it); cout << '\n'; }
from random import randrange try: range = xrange except: pass def one_of_n(lines): choice = None for i, line in enumerate(lines): if randrange(i+1) == 0: choice = line return choice def one_of_n_test(n=10, trials=1000000): bins = [0] * n if n: for i in range(trials): bins[one_of_n(range(n))] += 1 return bins print(one_of_n_test())
Transform the following C++ implementation into Python, maintaining the same output and logic.
#include <iostream> #include <string> #include <map> #include <vector> #include <algorithm> std::map<char, int> _map; std::vector<std::string> _result; size_t longest = 0; void make_sequence( std::string n ) { _map.clear(); for( std::string::iterator i = n.begin(); i != n.end(); i++ ) _map.insert( std::make_pair( *i, _map[*i]++ ) ); std::string z; for( std::map<char, int>::reverse_iterator i = _map.rbegin(); i != _map.rend(); i++ ) { char c = ( *i ).second + 48; z.append( 1, c ); z.append( 1, i->first ); } if( longest <= z.length() ) { longest = z.length(); if( std::find( _result.begin(), _result.end(), z ) == _result.end() ) { _result.push_back( z ); make_sequence( z ); } } } int main( int argc, char* argv[] ) { std::vector<std::string> tests; tests.push_back( "9900" ); tests.push_back( "9090" ); tests.push_back( "9009" ); for( std::vector<std::string>::iterator i = tests.begin(); i != tests.end(); i++ ) { make_sequence( *i ); std::cout << "[" << *i << "] Iterations: " << _result.size() + 1 << "\n"; for( std::vector<std::string>::iterator j = _result.begin(); j != _result.end(); j++ ) { std::cout << *j << "\n"; } std::cout << "\n\n"; } return 0; }
from itertools import groupby, permutations def A036058(number): return ''.join( str(len(list(g))) + k for k,g in groupby(sorted(str(number), reverse=True)) ) def A036058_length(numberstring='0', printit=False): iterations, last_three, queue_index = 1, ([None] * 3), 0 def A036058(number): return ''.join( str(len(list(g))) + k for k,g in groupby(number) ) while True: if printit: print(" %2i %s" % (iterations, numberstring)) numberstring = ''.join(sorted(numberstring, reverse=True)) if numberstring in last_three: break assert iterations < 1000000 last_three[queue_index], numberstring = numberstring, A036058(numberstring) iterations += 1 queue_index +=1 queue_index %=3 return iterations def max_A036058_length( start_range=range(11) ): already_done = set() max_len = (-1, []) for n in start_range: sn = str(n) sns = tuple(sorted(sn, reverse=True)) if sns not in already_done: already_done.add(sns) size = A036058_length(sns) if size > max_len[0]: max_len = (size, [n]) elif size == max_len[0]: max_len[1].append(n) return max_len lenmax, starts = max_A036058_length( range(1000000) ) allstarts = [] for n in starts: allstarts += [int(''.join(x)) for x in set(k for k in permutations(str(n), 4) if k[0] != '0')] allstarts = [x for x in sorted(allstarts) if x < 1000000] print ( % (lenmax, allstarts) ) print ( ) for n in starts: print() A036058_length(str(n), printit=True)
Keep all operations the same but rewrite the snippet in Python.
#include <iostream> #include <string> #include <cstdint> typedef std::uint64_t integer; struct number_names { const char* cardinal; const char* ordinal; }; const number_names small[] = { { "zero", "zeroth" }, { "one", "first" }, { "two", "second" }, { "three", "third" }, { "four", "fourth" }, { "five", "fifth" }, { "six", "sixth" }, { "seven", "seventh" }, { "eight", "eighth" }, { "nine", "ninth" }, { "ten", "tenth" }, { "eleven", "eleventh" }, { "twelve", "twelfth" }, { "thirteen", "thirteenth" }, { "fourteen", "fourteenth" }, { "fifteen", "fifteenth" }, { "sixteen", "sixteenth" }, { "seventeen", "seventeenth" }, { "eighteen", "eighteenth" }, { "nineteen", "nineteenth" } }; const number_names tens[] = { { "twenty", "twentieth" }, { "thirty", "thirtieth" }, { "forty", "fortieth" }, { "fifty", "fiftieth" }, { "sixty", "sixtieth" }, { "seventy", "seventieth" }, { "eighty", "eightieth" }, { "ninety", "ninetieth" } }; struct named_number { const char* cardinal; const char* ordinal; integer number; }; const named_number named_numbers[] = { { "hundred", "hundredth", 100 }, { "thousand", "thousandth", 1000 }, { "million", "millionth", 1000000 }, { "billion", "billionth", 1000000000 }, { "trillion", "trillionth", 1000000000000 }, { "quadrillion", "quadrillionth", 1000000000000000ULL }, { "quintillion", "quintillionth", 1000000000000000000ULL } }; const char* get_name(const number_names& n, bool ordinal) { return ordinal ? n.ordinal : n.cardinal; } const char* get_name(const named_number& n, bool ordinal) { return ordinal ? n.ordinal : n.cardinal; } const named_number& get_named_number(integer n) { constexpr size_t names_len = std::size(named_numbers); for (size_t i = 0; i + 1 < names_len; ++i) { if (n < named_numbers[i + 1].number) return named_numbers[i]; } return named_numbers[names_len - 1]; } std::string number_name(integer n, bool ordinal) { std::string result; if (n < 20) result = get_name(small[n], ordinal); else if (n < 100) { if (n % 10 == 0) { result = get_name(tens[n/10 - 2], ordinal); } else { result = get_name(tens[n/10 - 2], false); result += "-"; result += get_name(small[n % 10], ordinal); } } else { const named_number& num = get_named_number(n); integer p = num.number; result = number_name(n/p, false); result += " "; if (n % p == 0) { result += get_name(num, ordinal); } else { result += get_name(num, false); result += " "; result += number_name(n % p, ordinal); } } return result; } void test_ordinal(integer n) { std::cout << n << ": " << number_name(n, true) << '\n'; } int main() { test_ordinal(1); test_ordinal(2); test_ordinal(3); test_ordinal(4); test_ordinal(5); test_ordinal(11); test_ordinal(15); test_ordinal(21); test_ordinal(42); test_ordinal(65); test_ordinal(98); test_ordinal(100); test_ordinal(101); test_ordinal(272); test_ordinal(300); test_ordinal(750); test_ordinal(23456); test_ordinal(7891233); test_ordinal(8007006005004003LL); return 0; }
irregularOrdinals = { "one": "first", "two": "second", "three": "third", "five": "fifth", "eight": "eighth", "nine": "ninth", "twelve": "twelfth", } def num2ordinal(n): conversion = int(float(n)) num = spell_integer(conversion) hyphen = num.rsplit("-", 1) num = num.rsplit(" ", 1) delim = " " if len(num[-1]) > len(hyphen[-1]): num = hyphen delim = "-" if num[-1] in irregularOrdinals: num[-1] = delim + irregularOrdinals[num[-1]] elif num[-1].endswith("y"): num[-1] = delim + num[-1][:-1] + "ieth" else: num[-1] = delim + num[-1] + "th" return "".join(num) if __name__ == "__main__": tests = "1 2 3 4 5 11 65 100 101 272 23456 8007006005004003 123 00123.0 1.23e2".split() for num in tests: print("{} => {}".format(num, num2ordinal(num))) 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)
Generate an equivalent Python version of this C++ code.
#include <iostream> typedef unsigned long long bigint; using namespace std; class sdn { public: bool check( bigint n ) { int cc = digitsCount( n ); return compare( n, cc ); } void displayAll( bigint s ) { for( bigint y = 1; y < s; y++ ) if( check( y ) ) cout << y << " is a Self-Describing Number." << endl; } private: bool compare( bigint n, int cc ) { bigint a; while( cc ) { cc--; a = n % 10; if( dig[cc] != a ) return false; n -= a; n /= 10; } return true; } int digitsCount( bigint n ) { int cc = 0; bigint a; memset( dig, 0, sizeof( dig ) ); while( n ) { a = n % 10; dig[a]++; cc++ ; n -= a; n /= 10; } return cc; } int dig[10]; }; int main( int argc, char* argv[] ) { sdn s; s. displayAll( 1000000000000 ); cout << endl << endl; system( "pause" ); bigint n; while( true ) { system( "cls" ); cout << "Enter a positive whole number ( 0 to QUIT ): "; cin >> n; if( !n ) return 0; if( s.check( n ) ) cout << n << " is"; else cout << n << " is NOT"; cout << " a Self-Describing Number!" << endl << endl; system( "pause" ); } return 0; }
>>> def isSelfDescribing(n): s = str(n) return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s)) >>> [x for x in range(4000000) if isSelfDescribing(x)] [1210, 2020, 21200, 3211000] >>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)] [(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]
Write the same algorithm in Python as shown in this C++ implementation.
#include <iostream> #include <tuple> #include <vector> std::pair<int, int> tryPerm(int, int, const std::vector<int>&, int, int); std::pair<int, int> checkSeq(int pos, const std::vector<int>& seq, int n, int minLen) { if (pos > minLen || seq[0] > n) return { minLen, 0 }; else if (seq[0] == n) return { pos, 1 }; else if (pos < minLen) return tryPerm(0, pos, seq, n, minLen); else return { minLen, 0 }; } std::pair<int, int> tryPerm(int i, int pos, const std::vector<int>& seq, int n, int minLen) { if (i > pos) return { minLen, 0 }; std::vector<int> seq2{ seq[0] + seq[i] }; seq2.insert(seq2.end(), seq.cbegin(), seq.cend()); auto res1 = checkSeq(pos + 1, seq2, n, minLen); auto res2 = tryPerm(i + 1, pos, seq, n, res1.first); if (res2.first < res1.first) return res2; else if (res2.first == res1.first) return { res2.first, res1.second + res2.second }; else throw std::runtime_error("tryPerm exception"); } std::pair<int, int> initTryPerm(int x) { return tryPerm(0, 0, { 1 }, x, 12); } void findBrauer(int num) { auto res = initTryPerm(num); std::cout << '\n'; std::cout << "N = " << num << '\n'; std::cout << "Minimum length of chains: L(n)= " << res.first << '\n'; std::cout << "Number of minimum length Brauer chains: " << res.second << '\n'; } int main() { std::vector<int> nums{ 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 }; for (int i : nums) { findBrauer(i); } return 0; }
def prepend(n, seq): return [n] + seq def check_seq(pos, seq, n, min_len): if pos > min_len or seq[0] > n: return min_len, 0 if seq[0] == n: return pos, 1 if pos < min_len: return try_perm(0, pos, seq, n, min_len) return min_len, 0 def try_perm(i, pos, seq, n, min_len): if i > pos: return min_len, 0 res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len) res2 = try_perm(i + 1, pos, seq, n, res1[0]) if res2[0] < res1[0]: return res2 if res2[0] == res1[0]: return res2[0], res1[1] + res2[1] raise Exception("try_perm exception") def init_try_perm(x): return try_perm(0, 0, [1], x, 12) def find_brauer(num): res = init_try_perm(num) print print "N = ", num print "Minimum length of chains: L(n) = ", res[0] print "Number of minimum length Brauer chains: ", res[1] nums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379] for i in nums: find_brauer(i)
Write the same code in Python as shown below in C++.
template <typename Function> void repeat(Function f, unsigned int n) { for(unsigned int i=n; 0<i; i--) f(); }
def repeat(f,n): for i in range(n): f(); def procedure(): print("Example"); repeat(procedure,3);
Produce a functionally identical Python code for the snippet given in C++.
#include <iostream> #include <sstream> #include <vector> #include <cmath> #include <algorithm> #include <locale> class Sparkline { public: Sparkline(std::wstring &cs) : charset( cs ){ } virtual ~Sparkline(){ } void print(std::string spark){ const char *delim = ", "; std::vector<float> data; std::string::size_type last = spark.find_first_not_of(delim, 0); std::string::size_type pos = spark.find_first_of(delim, last); while( pos != std::string::npos || last != std::string::npos ){ std::string tok = spark.substr(last, pos-last); std::stringstream ss(tok); float entry; ss >> entry; data.push_back( entry ); last = spark.find_first_not_of(delim, pos); pos = spark.find_first_of(delim, last); } float min = *std::min_element( data.begin(), data.end() ); float max = *std::max_element( data.begin(), data.end() ); float skip = (charset.length()-1) / (max - min); std::wcout<<L"Min: "<<min<<L"; Max: "<<max<<L"; Range: "<<(max-min)<<std::endl; std::vector<float>::const_iterator it; for(it = data.begin(); it != data.end(); it++){ float v = ( (*it) - min ) * skip; std::wcout<<charset[ (int)floor( v ) ]; } std::wcout<<std::endl; } private: std::wstring &charset; }; int main( int argc, char **argv ){ std::wstring charset = L"\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588"; std::locale::global(std::locale("en_US.utf8")); Sparkline sl(charset); sl.print("1 2 3 4 5 6 7 8 7 6 5 4 3 2 1"); sl.print("1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5"); return 0; }
bar = '▁▂▃▄▅▆▇█' barcount = len(bar) def sparkline(numbers): mn, mx = min(numbers), max(numbers) extent = mx - mn sparkline = ''.join(bar[min([barcount - 1, int((n - mn) / extent * barcount)])] for n in numbers) return mn, mx, sparkline if __name__ == '__main__': import re for line in ("0 0 1 1; 0 1 19 20; 0 999 4000 4999 7000 7999;" "1 2 3 4 5 6 7 8 7 6 5 4 3 2 1;" "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 ").split(';'): print("\nNumbers:", line) numbers = [float(n) for n in re.split(r'[\s,]+', line.strip())] mn, mx, sp = sparkline(numbers) print(' min: %5f; max: %5f' % (mn, mx)) print(" " + sp)
Write a version of this C++ function in Python with identical behavior.
#include <iostream> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int main(void) { std::cout << mul_inv(42, 2017) << std::endl; return 0; }
>>> def extended_gcd(aa, bb): lastremainder, remainder = abs(aa), abs(bb) x, lastx, y, lasty = 0, 1, 1, 0 while remainder: lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder) x, lastx = lastx - quotient*x, x y, lasty = lasty - quotient*y, y return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1) >>> def modinv(a, m): g, x, y = extended_gcd(a, m) if g != 1: raise ValueError return x % m >>> modinv(42, 2017) 1969 >>>
Port the following code from C++ to Python with equivalent syntax and logic.
#include <cmath> #include <fstream> #include <iostream> bool sunflower(const char* filename) { std::ofstream out(filename); if (!out) return false; constexpr int size = 600; constexpr int seeds = 5 * size; constexpr double pi = 3.14159265359; constexpr double phi = 1.61803398875; out << "<svg xmlns='http: out << "' height='" << size << "' style='stroke:gold'>\n"; out << "<rect width='100%' height='100%' fill='black'/>\n"; out << std::setprecision(2) << std::fixed; for (int i = 1; i <= seeds; ++i) { double r = 2 * std::pow(i, phi)/seeds; double theta = 2 * pi * phi * i; double x = r * std::sin(theta) + size/2; double y = r * std::cos(theta) + size/2; double radius = std::sqrt(i)/13; out << "<circle cx='" << x << "' cy='" << y << "' r='" << radius << "'/>\n"; } out << "</svg>\n"; return true; } int main(int argc, char *argv[]) { if (argc != 2) { std::cerr << "usage: " << argv[0] << " filename\n"; return EXIT_FAILURE; } if (!sunflower(argv[1])) { std::cerr << "image generation failed\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; }
from turtle import * from math import * iter = 3000 diskRatio = .5 factor = .5 + sqrt(1.25) screen = getscreen() (winWidth, winHeight) = screen.screensize() x = 0.0 y = 0.0 maxRad = pow(iter,factor)/iter; bgcolor("light blue") hideturtle() tracer(0, 0) for i in range(iter+1): r = pow(i,factor)/iter; if r/maxRad < diskRatio: pencolor("black") else: pencolor("yellow") theta = 2*pi*factor*i; up() setposition(x + r*sin(theta), y + r*cos(theta)) down() circle(10.0 * i/(1.0*iter)) update() done()
Translate this program into Python but keep the logic exactly as in C++.
#include <iostream> #include <numeric> #include <vector> template <typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *it; it = std::next(it); } return os << ']'; } std::vector<int> demand = { 30, 20, 70, 30, 60 }; std::vector<int> supply = { 50, 60, 50, 50 }; std::vector<std::vector<int>> costs = { {16, 16, 13, 22, 17}, {14, 14, 13, 19, 15}, {19, 19, 20, 23, 50}, {50, 12, 50, 15, 11} }; int nRows = supply.size(); int nCols = demand.size(); std::vector<bool> rowDone(nRows, false); std::vector<bool> colDone(nCols, false); std::vector<std::vector<int>> result(nRows, std::vector<int>(nCols, 0)); std::vector<int> diff(int j, int len, bool isRow) { int min1 = INT_MAX; int min2 = INT_MAX; int minP = -1; for (int i = 0; i < len; i++) { if (isRow ? colDone[i] : rowDone[i]) { continue; } int c = isRow ? costs[j][i] : costs[i][j]; if (c < min1) { min2 = min1; min1 = c; minP = i; } else if (c < min2) { min2 = c; } } return { min2 - min1, min1, minP }; } std::vector<int> maxPenalty(int len1, int len2, bool isRow) { int md = INT_MIN; int pc = -1; int pm = -1; int mc = -1; for (int i = 0; i < len1; i++) { if (isRow ? rowDone[i] : colDone[i]) { continue; } std::vector<int> res = diff(i, len2, isRow); if (res[0] > md) { md = res[0]; pm = i; mc = res[1]; pc = res[2]; } } return isRow ? std::vector<int> { pm, pc, mc, md } : std::vector<int>{ pc, pm, mc, md }; } std::vector<int> nextCell() { auto res1 = maxPenalty(nRows, nCols, true); auto res2 = maxPenalty(nCols, nRows, false); if (res1[3] == res2[3]) { return res1[2] < res2[2] ? res1 : res2; } return res1[3] > res2[3] ? res2 : res1; } int main() { int supplyLeft = std::accumulate(supply.cbegin(), supply.cend(), 0, [](int a, int b) { return a + b; }); int totalCost = 0; while (supplyLeft > 0) { auto cell = nextCell(); int r = cell[0]; int c = cell[1]; int quantity = std::min(demand[c], supply[r]); demand[c] -= quantity; if (demand[c] == 0) { colDone[c] = true; } supply[r] -= quantity; if (supply[r] == 0) { rowDone[r] = true; } result[r][c] = quantity; supplyLeft -= quantity; totalCost += quantity * costs[r][c]; } for (auto &a : result) { std::cout << a << '\n'; } std::cout << "Total cost: " << totalCost; return 0; }
from collections import defaultdict costs = {'W': {'A': 16, 'B': 16, 'C': 13, 'D': 22, 'E': 17}, 'X': {'A': 14, 'B': 14, 'C': 13, 'D': 19, 'E': 15}, 'Y': {'A': 19, 'B': 19, 'C': 20, 'D': 23, 'E': 50}, 'Z': {'A': 50, 'B': 12, 'C': 50, 'D': 15, 'E': 11}} demand = {'A': 30, 'B': 20, 'C': 70, 'D': 30, 'E': 60} cols = sorted(demand.iterkeys()) supply = {'W': 50, 'X': 60, 'Y': 50, 'Z': 50} res = dict((k, defaultdict(int)) for k in costs) g = {} for x in supply: g[x] = sorted(costs[x].iterkeys(), key=lambda g: costs[x][g]) for x in demand: g[x] = sorted(costs.iterkeys(), key=lambda g: costs[g][x]) while g: d = {} for x in demand: d[x] = (costs[g[x][1]][x] - costs[g[x][0]][x]) if len(g[x]) > 1 else costs[g[x][0]][x] s = {} for x in supply: s[x] = (costs[x][g[x][1]] - costs[x][g[x][0]]) if len(g[x]) > 1 else costs[x][g[x][0]] f = max(d, key=lambda n: d[n]) t = max(s, key=lambda n: s[n]) t, f = (f, g[f][0]) if d[f] > s[t] else (g[t][0], t) v = min(supply[f], demand[t]) res[f][t] += v demand[t] -= v if demand[t] == 0: for k, n in supply.iteritems(): if n != 0: g[k].remove(t) del g[t] del demand[t] supply[f] -= v if supply[f] == 0: for k, n in demand.iteritems(): if n != 0: g[k].remove(f) del g[f] del supply[f] for n in cols: print "\t", n, print cost = 0 for g in sorted(costs): print g, "\t", for n in cols: y = res[g][n] if y != 0: print y, cost += y * costs[g][n] print "\t", print print "\n\nTotal Cost = ", cost
Rewrite this program in Python while keeping its functionality equivalent to the C++ version.
#include <iomanip> #include <iostream> #include <map> #include <string> #include <vector> std::map<std::string, double> atomicMass = { {"H", 1.008}, {"He", 4.002602}, {"Li", 6.94}, {"Be", 9.0121831}, {"B", 10.81}, {"C", 12.011}, {"N", 14.007}, {"O", 15.999}, {"F", 18.998403163}, {"Ne", 20.1797}, {"Na", 22.98976928}, {"Mg", 24.305}, {"Al", 26.9815385}, {"Si", 28.085}, {"P", 30.973761998}, {"S", 32.06}, {"Cl", 35.45}, {"Ar", 39.948}, {"K", 39.0983}, {"Ca", 40.078}, {"Sc", 44.955908}, {"Ti", 47.867}, {"V", 50.9415}, {"Cr", 51.9961}, {"Mn", 54.938044}, {"Fe", 55.845}, {"Co", 58.933194}, {"Ni", 58.6934}, {"Cu", 63.546}, {"Zn", 65.38}, {"Ga", 69.723}, {"Ge", 72.630}, {"As", 74.921595}, {"Se", 78.971}, {"Br", 79.904}, {"Kr", 83.798}, {"Rb", 85.4678}, {"Sr", 87.62}, {"Y", 88.90584}, {"Zr", 91.224}, {"Nb", 92.90637}, {"Mo", 95.95}, {"Ru", 101.07}, {"Rh", 102.90550}, {"Pd", 106.42}, {"Ag", 107.8682}, {"Cd", 112.414}, {"In", 114.818}, {"Sn", 118.710}, {"Sb", 121.760}, {"Te", 127.60}, {"I", 126.90447}, {"Xe", 131.293}, {"Cs", 132.90545196}, {"Ba", 137.327}, {"La", 138.90547}, {"Ce", 140.116}, {"Pr", 140.90766}, {"Nd", 144.242}, {"Pm", 145}, {"Sm", 150.36}, {"Eu", 151.964}, {"Gd", 157.25}, {"Tb", 158.92535}, {"Dy", 162.500}, {"Ho", 164.93033}, {"Er", 167.259}, {"Tm", 168.93422}, {"Yb", 173.054}, {"Lu", 174.9668}, {"Hf", 178.49}, {"Ta", 180.94788}, {"W", 183.84}, {"Re", 186.207}, {"Os", 190.23}, {"Ir", 192.217}, {"Pt", 195.084}, {"Au", 196.966569}, {"Hg", 200.592}, {"Tl", 204.38}, {"Pb", 207.2}, {"Bi", 208.98040}, {"Po", 209}, {"At", 210}, {"Rn", 222}, {"Fr", 223}, {"Ra", 226}, {"Ac", 227}, {"Th", 232.0377}, {"Pa", 231.03588}, {"U", 238.02891}, {"Np", 237}, {"Pu", 244}, {"Am", 243}, {"Cm", 247}, {"Bk", 247}, {"Cf", 251}, {"Es", 252}, {"Fm", 257}, {"Uue", 315}, {"Ubn", 299}, }; double evaluate(std::string s) { s += '['; double sum = 0.0; std::string symbol; std::string number; for (auto c : s) { if ('@' <= c && c <= '[') { int n = 1; if (number != "") { n = stoi(number); } if (symbol != "") { sum += atomicMass[symbol] * n; } if (c == '[') { break; } symbol = c; number = ""; } else if ('a' <= c && c <= 'z') { symbol += c; } else if ('0' <= c && c <= '9') { number += c; } else { std::string msg = "Unexpected symbol "; msg += c; msg += " in molecule"; throw std::runtime_error(msg); } } return sum; } std::string replaceFirst(const std::string &text, const std::string &search, const std::string &replace) { auto pos = text.find(search); if (pos == std::string::npos) { return text; } auto beg = text.substr(0, pos); auto end = text.substr(pos + search.length()); return beg + replace + end; } std::string replaceParens(std::string s) { char letter = 'a'; while (true) { auto start = s.find("("); if (start == std::string::npos) { break; } for (size_t i = start + 1; i < s.length(); i++) { if (s[i] == ')') { auto expr = s.substr(start + 1, i - start - 1); std::string symbol = "@"; symbol += letter; auto search = s.substr(start, i + 1 - start); s = replaceFirst(s, search, symbol); atomicMass[symbol] = evaluate(expr); letter++; break; } if (s[i] == '(') { start = i; continue; } } } return s; } int main() { std::vector<std::string> molecules = { "H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12", "COOH(C(CH3)2)3CH3", "C6H4O2(OH)4", "C27H46O", "Uue" }; for (auto molecule : molecules) { auto mass = evaluate(replaceParens(molecule)); std::cout << std::setw(17) << molecule << " -> " << std::setw(7) << std::fixed << std::setprecision(3) << mass << '\n'; } return 0; }
assert 1.008 == molar_mass('H') assert 2.016 == molar_mass('H2') assert 18.015 == molar_mass('H2O') assert 34.014 == molar_mass('H2O2') assert 34.014 == molar_mass('(HO)2') assert 142.036 == molar_mass('Na2SO4') assert 84.162 == molar_mass('C6H12') assert 186.295 == molar_mass('COOH(C(CH3)2)3CH3') assert 176.124 == molar_mass('C6H4O2(OH)4') assert 386.664 == molar_mass('C27H46O') assert 315 == molar_mass('Uue')
Rewrite the snippet below in Python so it works the same as the original C++ code.
#include <iostream> #include <vector> using namespace std; vector<int> UpTo(int n, int offset = 0) { vector<int> retval(n); for (int ii = 0; ii < n; ++ii) retval[ii] = ii + offset; return retval; } struct JohnsonTrotterState_ { vector<int> values_; vector<int> positions_; vector<bool> directions_; int sign_; JohnsonTrotterState_(int n) : values_(UpTo(n, 1)), positions_(UpTo(n + 1, -1)), directions_(n + 1, false), sign_(1) {} int LargestMobile() const { for (int r = values_.size(); r > 0; --r) { const int loc = positions_[r] + (directions_[r] ? 1 : -1); if (loc >= 0 && loc < values_.size() && values_[loc] < r) return r; } return 0; } bool IsComplete() const { return LargestMobile() == 0; } void operator++() { const int r = LargestMobile(); const int rLoc = positions_[r]; const int lLoc = rLoc + (directions_[r] ? 1 : -1); const int l = values_[lLoc]; swap(values_[lLoc], values_[rLoc]); swap(positions_[l], positions_[r]); sign_ = -sign_; for (auto pd = directions_.begin() + r + 1; pd != directions_.end(); ++pd) *pd = !*pd; } }; int main(void) { JohnsonTrotterState_ state(4); do { for (auto v : state.values_) cout << v << " "; cout << "\n"; ++state; } while (!state.IsComplete()); }
from operator import itemgetter DEBUG = False def spermutations(n): sign = 1 p = [[i, 0 if i == 0 else -1] for i in range(n)] if DEBUG: print ' yield tuple(pp[0] for pp in p), sign while any(pp[1] for pp in p): i1, (n1, d1) = max(((i, pp) for i, pp in enumerate(p) if pp[1]), key=itemgetter(1)) sign *= -1 if d1 == -1: i2 = i1 - 1 p[i1], p[i2] = p[i2], p[i1] if i2 == 0 or p[i2 - 1][0] > n1: p[i2][1] = 0 elif d1 == 1: i2 = i1 + 1 p[i1], p[i2] = p[i2], p[i1] if i2 == n - 1 or p[i2 + 1][0] > n1: p[i2][1] = 0 if DEBUG: print ' yield tuple(pp[0] for pp in p), sign for i3, pp in enumerate(p): n3, d3 = pp if n3 > n1: pp[1] = 1 if i3 < i2 else -1 if DEBUG: print ' if __name__ == '__main__': from itertools import permutations for n in (3, 4): print '\nPermutations and sign of %i items' % n sp = set() for i in spermutations(n): sp.add(i[0]) print('Perm: %r Sign: %2i' % i) p = set(permutations(range(n))) assert sp == p, 'Two methods of generating permutations do not agree'
Write the same code in Python as shown below in C++.
#include <iomanip> #include <iostream> int digit_sum(int n) { int sum = 0; for (; n > 0; n /= 10) sum += n % 10; return sum; } int main() { for (int n = 1; n <= 70; ++n) { for (int m = 1;; ++m) { if (digit_sum(m * n) == n) { std::cout << std::setw(8) << m << (n % 10 == 0 ? '\n' : ' '); break; } } } }
from itertools import count, islice def a131382(): return ( elemIndex(x)( productDigitSums(x) ) for x in count(1) ) def productDigitSums(n): return (digitSum(n * x) for x in count(0)) def main(): print( table(10)([ str(x) for x in islice( a131382(), 40 ) ]) ) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go def digitSum(n): return sum(int(x) for x in list(str(n))) def elemIndex(x): def go(xs): try: return next( i for i, v in enumerate(xs) if x == v ) except StopIteration: return None return go def table(n): def go(xs): w = len(xs[-1]) return '\n'.join( ' '.join(row) for row in chunksOf(n)([ s.rjust(w, ' ') for s in xs ]) ) return go if __name__ == '__main__': main()
Produce a language-to-language conversion: from C++ to Python, same semantics.
#include <iomanip> #include <iostream> int digit_sum(int n) { int sum = 0; for (; n > 0; n /= 10) sum += n % 10; return sum; } int main() { for (int n = 1; n <= 70; ++n) { for (int m = 1;; ++m) { if (digit_sum(m * n) == n) { std::cout << std::setw(8) << m << (n % 10 == 0 ? '\n' : ' '); break; } } } }
from itertools import count, islice def a131382(): return ( elemIndex(x)( productDigitSums(x) ) for x in count(1) ) def productDigitSums(n): return (digitSum(n * x) for x in count(0)) def main(): print( table(10)([ str(x) for x in islice( a131382(), 40 ) ]) ) def chunksOf(n): def go(xs): return ( xs[i:n + i] for i in range(0, len(xs), n) ) if 0 < n else None return go def digitSum(n): return sum(int(x) for x in list(str(n))) def elemIndex(x): def go(xs): try: return next( i for i, v in enumerate(xs) if x == v ) except StopIteration: return None return go def table(n): def go(xs): w = len(xs[-1]) return '\n'.join( ' '.join(row) for row in chunksOf(n)([ s.rjust(w, ' ') for s in xs ]) ) return go if __name__ == '__main__': main()
Change the following C++ code into Python without altering its purpose.
#include <iostream> #include <vector> constexpr int N = 2200; constexpr int N2 = 2 * N * N; int main() { using namespace std; vector<bool> found(N + 1); vector<bool> aabb(N2 + 1); int s = 3; for (int a = 1; a < N; ++a) { int aa = a * a; for (int b = 1; b < N; ++b) { aabb[aa + b * b] = true; } } for (int c = 1; c <= N; ++c) { int s1 = s; s += 2; int s2 = s; for (int d = c + 1; d <= N; ++d) { if (aabb[s1]) { found[d] = true; } s1 += s2; s2 += 2; } } cout << "The values of d <= " << N << " which can't be represented:" << endl; for (int d = 1; d <= N; ++d) { if (!found[d]) { cout << d << " "; } } cout << endl; return 0; }
def quad(top=2200): r = [False] * top ab = [False] * (top * 2)**2 for a in range(1, top): for b in range(a, top): ab[a * a + b * b] = True s = 3 for c in range(1, top): s1, s, s2 = s, s + 2, s + 2 for d in range(c + 1, top): if ab[s1]: r[d] = True s1 += s2 s2 += 2 return [i for i, val in enumerate(r) if not val and i] if __name__ == '__main__': n = 2200 print(f"Those values of d in 1..{n} that can't be represented: {quad(n)}")
Generate a Python translation of this C++ snippet without changing its computational steps.
#include <iostream> using namespace std; bool steady(int n) { int mask = 1; for (int d = n; d != 0; d /= 10) mask *= 10; return (n * n) % mask == n; } int main() { for (int i = 1; i < 10000; i++) if (steady(i)) printf("%4d^2 = %8d\n", i, i * i); }
print("working...") print("Steady squares under 10.000 are:") limit = 10000 for n in range(1,limit): nstr = str(n) nlen = len(nstr) square = str(pow(n,2)) rn = square[-nlen:] if nstr == rn: print(str(n) + " " + str(square)) print("done...")
Preserve the algorithm and functionality while converting the code from C++ to Python.
#include <exception> #include <iostream> using ulong = unsigned long; class MiddleSquare { private: ulong state; ulong div, mod; public: MiddleSquare() = delete; MiddleSquare(ulong start, ulong length) { if (length % 2) throw std::invalid_argument("length must be even"); div = mod = 1; for (ulong i=0; i<length/2; i++) div *= 10; for (ulong i=0; i<length; i++) mod *= 10; state = start % mod; } ulong next() { return state = state * state / div % mod; } }; int main() { MiddleSquare msq(675248, 6); for (int i=0; i<5; i++) std::cout << msq.next() << std::endl; return 0; }
seed = 675248 def random(): global seed seed = int(str(seed ** 2).zfill(12)[3:9]) return seed for _ in range(5): print(random())
Preserve the algorithm and functionality while converting the code from C++ to Python.
#include <exception> #include <iostream> using ulong = unsigned long; class MiddleSquare { private: ulong state; ulong div, mod; public: MiddleSquare() = delete; MiddleSquare(ulong start, ulong length) { if (length % 2) throw std::invalid_argument("length must be even"); div = mod = 1; for (ulong i=0; i<length/2; i++) div *= 10; for (ulong i=0; i<length; i++) mod *= 10; state = start % mod; } ulong next() { return state = state * state / div % mod; } }; int main() { MiddleSquare msq(675248, 6); for (int i=0; i<5; i++) std::cout << msq.next() << std::endl; return 0; }
seed = 675248 def random(): global seed seed = int(str(seed ** 2).zfill(12)[3:9]) return seed for _ in range(5): print(random())
Write a version of this C++ function in Python with identical behavior.
#include <cmath> #include <cstdint> #include <iomanip> #include <iostream> #include <map> std::map<uint32_t, uint32_t> get_totals(uint32_t dice, uint32_t faces) { std::map<uint32_t, uint32_t> result; for (uint32_t i = 1; i <= faces; ++i) result.emplace(i, 1); for (uint32_t d = 2; d <= dice; ++d) { std::map<uint32_t, uint32_t> tmp; for (const auto& p : result) { for (uint32_t i = 1; i <= faces; ++i) tmp[p.first + i] += p.second; } tmp.swap(result); } return result; } double probability(uint32_t dice1, uint32_t faces1, uint32_t dice2, uint32_t faces2) { auto totals1 = get_totals(dice1, faces1); auto totals2 = get_totals(dice2, faces2); double wins = 0; for (const auto& p1 : totals1) { for (const auto& p2 : totals2) { if (p2.first >= p1.first) break; wins += p1.second * p2.second; } } double total = std::pow(faces1, dice1) * std::pow(faces2, dice2); return wins/total; } int main() { std::cout << std::setprecision(10); std::cout << probability(9, 4, 6, 6) << '\n'; std::cout << probability(5, 10, 6, 7) << '\n'; return 0; }
from itertools import product def gen_dict(n_faces, n_dice): counts = [0] * ((n_faces + 1) * n_dice) for t in product(range(1, n_faces + 1), repeat=n_dice): counts[sum(t)] += 1 return counts, n_faces ** n_dice def beating_probability(n_sides1, n_dice1, n_sides2, n_dice2): c1, p1 = gen_dict(n_sides1, n_dice1) c2, p2 = gen_dict(n_sides2, n_dice2) p12 = float(p1 * p2) return sum(p[1] * q[1] / p12 for p, q in product(enumerate(c1), enumerate(c2)) if p[0] > q[0]) print beating_probability(4, 9, 6, 6) print beating_probability(10, 5, 7, 6)
Maintain the same structure and functionality when rewriting this code in Python.
#include <cmath> #include <cstdint> #include <iomanip> #include <iostream> #include <map> std::map<uint32_t, uint32_t> get_totals(uint32_t dice, uint32_t faces) { std::map<uint32_t, uint32_t> result; for (uint32_t i = 1; i <= faces; ++i) result.emplace(i, 1); for (uint32_t d = 2; d <= dice; ++d) { std::map<uint32_t, uint32_t> tmp; for (const auto& p : result) { for (uint32_t i = 1; i <= faces; ++i) tmp[p.first + i] += p.second; } tmp.swap(result); } return result; } double probability(uint32_t dice1, uint32_t faces1, uint32_t dice2, uint32_t faces2) { auto totals1 = get_totals(dice1, faces1); auto totals2 = get_totals(dice2, faces2); double wins = 0; for (const auto& p1 : totals1) { for (const auto& p2 : totals2) { if (p2.first >= p1.first) break; wins += p1.second * p2.second; } } double total = std::pow(faces1, dice1) * std::pow(faces2, dice2); return wins/total; } int main() { std::cout << std::setprecision(10); std::cout << probability(9, 4, 6, 6) << '\n'; std::cout << probability(5, 10, 6, 7) << '\n'; return 0; }
from itertools import product def gen_dict(n_faces, n_dice): counts = [0] * ((n_faces + 1) * n_dice) for t in product(range(1, n_faces + 1), repeat=n_dice): counts[sum(t)] += 1 return counts, n_faces ** n_dice def beating_probability(n_sides1, n_dice1, n_sides2, n_dice2): c1, p1 = gen_dict(n_sides1, n_dice1) c2, p2 = gen_dict(n_sides2, n_dice2) p12 = float(p1 * p2) return sum(p[1] * q[1] / p12 for p, q in product(enumerate(c1), enumerate(c2)) if p[0] > q[0]) print beating_probability(4, 9, 6, 6) print beating_probability(10, 5, 7, 6)
Generate an equivalent Python version of this C++ code.
#include <stdio.h> #include <string.h> #define defenum(name, val0, val1, val2, val3, val4) \ enum name { val0, val1, val2, val3, val4 }; \ const char *name ## _str[] = { # val0, # val1, # val2, # val3, # val4 } defenum( Attrib, Color, Man, Drink, Animal, Smoke ); defenum( Colors, Red, Green, White, Yellow, Blue ); defenum( Mans, English, Swede, Dane, German, Norwegian ); defenum( Drinks, Tea, Coffee, Milk, Beer, Water ); defenum( Animals, Dog, Birds, Cats, Horse, Zebra ); defenum( Smokes, PallMall, Dunhill, Blend, BlueMaster, Prince ); void printHouses(int ha[5][5]) { const char **attr_names[5] = {Colors_str, Mans_str, Drinks_str, Animals_str, Smokes_str}; printf("%-10s", "House"); for (const char *name : Attrib_str) printf("%-10s", name); printf("\n"); for (int i = 0; i < 5; i++) { printf("%-10d", i); for (int j = 0; j < 5; j++) printf("%-10s", attr_names[j][ha[i][j]]); printf("\n"); } } struct HouseNoRule { int houseno; Attrib a; int v; } housenos[] = { {2, Drink, Milk}, {0, Man, Norwegian} }; struct AttrPairRule { Attrib a1; int v1; Attrib a2; int v2; bool invalid(int ha[5][5], int i) { return (ha[i][a1] >= 0 && ha[i][a2] >= 0) && ((ha[i][a1] == v1 && ha[i][a2] != v2) || (ha[i][a1] != v1 && ha[i][a2] == v2)); } } pairs[] = { {Man, English, Color, Red}, {Man, Swede, Animal, Dog}, {Man, Dane, Drink, Tea}, {Color, Green, Drink, Coffee}, {Smoke, PallMall, Animal, Birds}, {Smoke, Dunhill, Color, Yellow}, {Smoke, BlueMaster, Drink, Beer}, {Man, German, Smoke, Prince} }; struct NextToRule { Attrib a1; int v1; Attrib a2; int v2; bool invalid(int ha[5][5], int i) { return (ha[i][a1] == v1) && ((i == 0 && ha[i + 1][a2] >= 0 && ha[i + 1][a2] != v2) || (i == 4 && ha[i - 1][a2] != v2) || (ha[i + 1][a2] >= 0 && ha[i + 1][a2] != v2 && ha[i - 1][a2] != v2)); } } nexttos[] = { {Smoke, Blend, Animal, Cats}, {Smoke, Dunhill, Animal, Horse}, {Man, Norwegian, Color, Blue}, {Smoke, Blend, Drink, Water} }; struct LeftOfRule { Attrib a1; int v1; Attrib a2; int v2; bool invalid(int ha[5][5]) { return (ha[0][a2] == v2) || (ha[4][a1] == v1); } bool invalid(int ha[5][5], int i) { return ((i > 0 && ha[i][a1] >= 0) && ((ha[i - 1][a1] == v1 && ha[i][a2] != v2) || (ha[i - 1][a1] != v1 && ha[i][a2] == v2))); } } leftofs[] = { {Color, Green, Color, White} }; bool invalid(int ha[5][5]) { for (auto &rule : leftofs) if (rule.invalid(ha)) return true; for (int i = 0; i < 5; i++) { #define eval_rules(rules) for (auto &rule : rules) if (rule.invalid(ha, i)) return true; eval_rules(pairs); eval_rules(nexttos); eval_rules(leftofs); } return false; } void search(bool used[5][5], int ha[5][5], const int hno, const int attr) { int nexthno, nextattr; if (attr < 4) { nextattr = attr + 1; nexthno = hno; } else { nextattr = 0; nexthno = hno + 1; } if (ha[hno][attr] != -1) { search(used, ha, nexthno, nextattr); } else { for (int i = 0; i < 5; i++) { if (used[attr][i]) continue; used[attr][i] = true; ha[hno][attr] = i; if (!invalid(ha)) { if ((hno == 4) && (attr == 4)) { printHouses(ha); } else { search(used, ha, nexthno, nextattr); } } used[attr][i] = false; } ha[hno][attr] = -1; } } int main() { bool used[5][5] = {}; int ha[5][5]; memset(ha, -1, sizeof(ha)); for (auto &rule : housenos) { ha[rule.houseno][rule.a] = rule.v; used[rule.a][rule.v] = true; } search(used, ha, 0, 0); return 0; }
from logpy import * from logpy.core import lall import time def lefto(q, p, list): return membero((q,p), zip(list, list[1:])) def nexto(q, p, list): return conde([lefto(q, p, list)], [lefto(p, q, list)]) houses = var() zebraRules = lall( (eq, (var(), var(), var(), var(), var()), houses), (membero, ('Englishman', var(), var(), var(), 'red'), houses), (membero, ('Swede', var(), var(), 'dog', var()), houses), (membero, ('Dane', var(), 'tea', var(), var()), houses), (lefto, (var(), var(), var(), var(), 'green'), (var(), var(), var(), var(), 'white'), houses), (membero, (var(), var(), 'coffee', var(), 'green'), houses), (membero, (var(), 'Pall Mall', var(), 'birds', var()), houses), (membero, (var(), 'Dunhill', var(), var(), 'yellow'), houses), (eq, (var(), var(), (var(), var(), 'milk', var(), var()), var(), var()), houses), (eq, (('Norwegian', var(), var(), var(), var()), var(), var(), var(), var()), houses), (nexto, (var(), 'Blend', var(), var(), var()), (var(), var(), var(), 'cats', var()), houses), (nexto, (var(), 'Dunhill', var(), var(), var()), (var(), var(), var(), 'horse', var()), houses), (membero, (var(), 'Blue Master', 'beer', var(), var()), houses), (membero, ('German', 'Prince', var(), var(), var()), houses), (nexto, ('Norwegian', var(), var(), var(), var()), (var(), var(), var(), var(), 'blue'), houses), (nexto, (var(), 'Blend', var(), var(), var()), (var(), var(), 'water', var(), var()), houses), (membero, (var(), var(), var(), 'zebra', var()), houses) ) t0 = time.time() solutions = run(0, houses, zebraRules) t1 = time.time() dur = t1-t0 count = len(solutions) zebraOwner = [house for house in solutions[0] if 'zebra' in house][0][0] print "%i solutions in %.2f seconds" % (count, dur) print "The %s is the owner of the zebra" % zebraOwner print "Here are all the houses:" for line in solutions[0]: print str(line)
Can you help me rewrite this code in Python instead of C++, keeping it the same logically?
#include <array> #include <iostream> int main() { double x = 2.0; double xi = 0.5; double y = 4.0; double yi = 0.25; double z = x + y; double zi = 1.0 / ( x + y ); const std::array values{x, y, z}; const std::array inverses{xi, yi, zi}; auto multiplier = [](double a, double b) { return [=](double m){return a * b * m;}; }; for(size_t i = 0; i < values.size(); ++i) { auto new_function = multiplier(values[i], inverses[i]); double value = new_function(i + 1.0); std::cout << value << "\n"; } }
IDLE 2.6.1 >>> >>> x,xi, y,yi = 2.0,0.5, 4.0,0.25 >>> >>> z = x + y >>> zi = 1.0 / (x + y) >>> >>> multiplier = lambda n1, n2: (lambda m: n1 * n2 * m) >>> >>> numlist = [x, y, z] >>> numlisti = [xi, yi, zi] >>> >>> [multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)] [0.5, 0.5, 0.5] >>>
Write the same algorithm in Python as shown in this C++ implementation.
#include <array> #include <iostream> int main() { double x = 2.0; double xi = 0.5; double y = 4.0; double yi = 0.25; double z = x + y; double zi = 1.0 / ( x + y ); const std::array values{x, y, z}; const std::array inverses{xi, yi, zi}; auto multiplier = [](double a, double b) { return [=](double m){return a * b * m;}; }; for(size_t i = 0; i < values.size(); ++i) { auto new_function = multiplier(values[i], inverses[i]); double value = new_function(i + 1.0); std::cout << value << "\n"; } }
IDLE 2.6.1 >>> >>> x,xi, y,yi = 2.0,0.5, 4.0,0.25 >>> >>> z = x + y >>> zi = 1.0 / (x + y) >>> >>> multiplier = lambda n1, n2: (lambda m: n1 * n2 * m) >>> >>> numlist = [x, y, z] >>> numlisti = [xi, yi, zi] >>> >>> [multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)] [0.5, 0.5, 0.5] >>>
Produce a language-to-language conversion: from C++ to Python, same semantics.
#include <iostream> #include <string> #include <vector> #include <queue> #include <regex> #include <tuple> #include <set> #include <array> using namespace std; class Board { public: vector<vector<char>> sData, dData; int px, py; Board(string b) { regex pattern("([^\\n]+)\\n?"); sregex_iterator end, iter(b.begin(), b.end(), pattern); int w = 0; vector<string> data; for(; iter != end; ++iter){ data.push_back((*iter)[1]); w = max(w, (*iter)[1].length()); } for(int v = 0; v < data.size(); ++v){ vector<char> sTemp, dTemp; for(int u = 0; u < w; ++u){ if(u > data[v].size()){ sTemp.push_back(' '); dTemp.push_back(' '); }else{ char s = ' ', d = ' ', c = data[v][u]; if(c == '#') s = '#'; else if(c == '.' || c == '*' || c == '+') s = '.'; if(c == '@' || c == '+'){ d = '@'; px = u; py = v; }else if(c == '$' || c == '*') d = '*'; sTemp.push_back(s); dTemp.push_back(d); } } sData.push_back(sTemp); dData.push_back(dTemp); } } bool move(int x, int y, int dx, int dy, vector<vector<char>> &data) { if(sData[y+dy][x+dx] == '#' || data[y+dy][x+dx] != ' ') return false; data[y][x] = ' '; data[y+dy][x+dx] = '@'; return true; } bool push(int x, int y, int dx, int dy, vector<vector<char>> &data) { if(sData[y+2*dy][x+2*dx] == '#' || data[y+2*dy][x+2*dx] != ' ') return false; data[y][x] = ' '; data[y+dy][x+dx] = '@'; data[y+2*dy][x+2*dx] = '*'; return true; } bool isSolved(const vector<vector<char>> &data) { for(int v = 0; v < data.size(); ++v) for(int u = 0; u < data[v].size(); ++u) if((sData[v][u] == '.') ^ (data[v][u] == '*')) return false; return true; } string solve() { set<vector<vector<char>>> visited; queue<tuple<vector<vector<char>>, string, int, int>> open; open.push(make_tuple(dData, "", px, py)); visited.insert(dData); array<tuple<int, int, char, char>, 4> dirs; dirs[0] = make_tuple(0, -1, 'u', 'U'); dirs[1] = make_tuple(1, 0, 'r', 'R'); dirs[2] = make_tuple(0, 1, 'd', 'D'); dirs[3] = make_tuple(-1, 0, 'l', 'L'); while(open.size() > 0){ vector<vector<char>> temp, cur = get<0>(open.front()); string cSol = get<1>(open.front()); int x = get<2>(open.front()); int y = get<3>(open.front()); open.pop(); for(int i = 0; i < 4; ++i){ temp = cur; int dx = get<0>(dirs[i]); int dy = get<1>(dirs[i]); if(temp[y+dy][x+dx] == '*'){ if(push(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())){ if(isSolved(temp)) return cSol + get<3>(dirs[i]); open.push(make_tuple(temp, cSol + get<3>(dirs[i]), x+dx, y+dy)); visited.insert(temp); } }else if(move(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())){ if(isSolved(temp)) return cSol + get<2>(dirs[i]); open.push(make_tuple(temp, cSol + get<2>(dirs[i]), x+dx, y+dy)); visited.insert(temp); } } } return "No solution"; } }; int main() { string level = "#######\n" "# #\n" "# #\n" "#. # #\n" "#. $$ #\n" "#.$$ #\n" "#.# @#\n" "#######"; Board b(level); cout << level << endl << endl << b.solve() << endl; return 0; }
from array import array from collections import deque import psyco data = [] nrows = 0 px = py = 0 sdata = "" ddata = "" def init(board): global data, nrows, sdata, ddata, px, py data = filter(None, board.splitlines()) nrows = max(len(r) for r in data) maps = {' ':' ', '.': '.', '@':' ', ' mapd = {' ':' ', '.': ' ', '@':'@', ' for r, row in enumerate(data): for c, ch in enumerate(row): sdata += maps[ch] ddata += mapd[ch] if ch == '@': px = c py = r def push(x, y, dx, dy, data): if sdata[(y+2*dy) * nrows + x+2*dx] == ' data[(y+2*dy) * nrows + x+2*dx] != ' ': return None data2 = array("c", data) data2[y * nrows + x] = ' ' data2[(y+dy) * nrows + x+dx] = '@' data2[(y+2*dy) * nrows + x+2*dx] = '*' return data2.tostring() def is_solved(data): for i in xrange(len(data)): if (sdata[i] == '.') != (data[i] == '*'): return False return True def solve(): open = deque([(ddata, "", px, py)]) visited = set([ddata]) dirs = ((0, -1, 'u', 'U'), ( 1, 0, 'r', 'R'), (0, 1, 'd', 'D'), (-1, 0, 'l', 'L')) lnrows = nrows while open: cur, csol, x, y = open.popleft() for di in dirs: temp = cur dx, dy = di[0], di[1] if temp[(y+dy) * lnrows + x+dx] == '*': temp = push(x, y, dx, dy, temp) if temp and temp not in visited: if is_solved(temp): return csol + di[3] open.append((temp, csol + di[3], x+dx, y+dy)) visited.add(temp) else: if sdata[(y+dy) * lnrows + x+dx] == ' temp[(y+dy) * lnrows + x+dx] != ' ': continue data2 = array("c", temp) data2[y * lnrows + x] = ' ' data2[(y+dy) * lnrows + x+dx] = '@' temp = data2.tostring() if temp not in visited: if is_solved(temp): return csol + di[2] open.append((temp, csol + di[2], x+dx, y+dy)) visited.add(temp) return "No solution" level = """\ psyco.full() init(level) print level, "\n\n", solve()
Port the following code from C++ to Python with equivalent syntax and logic.
#include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/multiprecision/gmp.hpp> #include <iomanip> #include <iostream> namespace mp = boost::multiprecision; using big_int = mp::mpz_int; using big_float = mp::cpp_dec_float_100; using rational = mp::mpq_rational; big_int factorial(int n) { big_int result = 1; for (int i = 2; i <= n; ++i) result *= i; return result; } big_int almkvist_giullera(int n) { return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) / (pow(factorial(n), 6) * 3); } int main() { std::cout << "n | Integer portion of nth term\n" << "------------------------------------------------\n"; for (int n = 0; n < 10; ++n) std::cout << n << " | " << std::setw(44) << almkvist_giullera(n) << '\n'; big_float epsilon(pow(big_float(10), -70)); big_float prev = 0, pi = 0; rational sum = 0; for (int n = 0;; ++n) { rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3)); sum += term; pi = sqrt(big_float(1 / sum)); if (abs(pi - prev) < epsilon) break; prev = pi; } std::cout << "\nPi to 70 decimal places is:\n" << std::fixed << std::setprecision(70) << pi << '\n'; }
import mpmath as mp with mp.workdps(72): def integer_term(n): p = 532 * n * n + 126 * n + 9 return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6) def exponent_term(n): return -(mp.mpf("6.0") * n + 3) def nthterm(n): return integer_term(n) * mp.mpf("10.0")**exponent_term(n) for n in range(10): print("Term ", n, ' ', int(integer_term(n))) def almkvist_guillera(floatprecision): summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0') for n in range(100000000): nextadd = summed + nthterm(n) if abs(nextadd - summed) < 10.0**(-floatprecision): break summed = nextadd return nextadd print('\nπ to 70 digits is ', end='') mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71) print('mpmath π is ', end='') mp.nprint(mp.pi, 71)
Maintain the same structure and functionality when rewriting this code in Python.
#include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/multiprecision/gmp.hpp> #include <iomanip> #include <iostream> namespace mp = boost::multiprecision; using big_int = mp::mpz_int; using big_float = mp::cpp_dec_float_100; using rational = mp::mpq_rational; big_int factorial(int n) { big_int result = 1; for (int i = 2; i <= n; ++i) result *= i; return result; } big_int almkvist_giullera(int n) { return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) / (pow(factorial(n), 6) * 3); } int main() { std::cout << "n | Integer portion of nth term\n" << "------------------------------------------------\n"; for (int n = 0; n < 10; ++n) std::cout << n << " | " << std::setw(44) << almkvist_giullera(n) << '\n'; big_float epsilon(pow(big_float(10), -70)); big_float prev = 0, pi = 0; rational sum = 0; for (int n = 0;; ++n) { rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3)); sum += term; pi = sqrt(big_float(1 / sum)); if (abs(pi - prev) < epsilon) break; prev = pi; } std::cout << "\nPi to 70 decimal places is:\n" << std::fixed << std::setprecision(70) << pi << '\n'; }
import mpmath as mp with mp.workdps(72): def integer_term(n): p = 532 * n * n + 126 * n + 9 return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6) def exponent_term(n): return -(mp.mpf("6.0") * n + 3) def nthterm(n): return integer_term(n) * mp.mpf("10.0")**exponent_term(n) for n in range(10): print("Term ", n, ' ', int(integer_term(n))) def almkvist_guillera(floatprecision): summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0') for n in range(100000000): nextadd = summed + nthterm(n) if abs(nextadd - summed) < 10.0**(-floatprecision): break summed = nextadd return nextadd print('\nπ to 70 digits is ', end='') mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71) print('mpmath π is ', end='') mp.nprint(mp.pi, 71)
Translate this program into Python but keep the logic exactly as in C++.
#include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/multiprecision/gmp.hpp> #include <iomanip> #include <iostream> namespace mp = boost::multiprecision; using big_int = mp::mpz_int; using big_float = mp::cpp_dec_float_100; using rational = mp::mpq_rational; big_int factorial(int n) { big_int result = 1; for (int i = 2; i <= n; ++i) result *= i; return result; } big_int almkvist_giullera(int n) { return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) / (pow(factorial(n), 6) * 3); } int main() { std::cout << "n | Integer portion of nth term\n" << "------------------------------------------------\n"; for (int n = 0; n < 10; ++n) std::cout << n << " | " << std::setw(44) << almkvist_giullera(n) << '\n'; big_float epsilon(pow(big_float(10), -70)); big_float prev = 0, pi = 0; rational sum = 0; for (int n = 0;; ++n) { rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3)); sum += term; pi = sqrt(big_float(1 / sum)); if (abs(pi - prev) < epsilon) break; prev = pi; } std::cout << "\nPi to 70 decimal places is:\n" << std::fixed << std::setprecision(70) << pi << '\n'; }
import mpmath as mp with mp.workdps(72): def integer_term(n): p = 532 * n * n + 126 * n + 9 return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6) def exponent_term(n): return -(mp.mpf("6.0") * n + 3) def nthterm(n): return integer_term(n) * mp.mpf("10.0")**exponent_term(n) for n in range(10): print("Term ", n, ' ', int(integer_term(n))) def almkvist_guillera(floatprecision): summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0') for n in range(100000000): nextadd = summed + nthterm(n) if abs(nextadd - summed) < 10.0**(-floatprecision): break summed = nextadd return nextadd print('\nπ to 70 digits is ', end='') mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71) print('mpmath π is ', end='') mp.nprint(mp.pi, 71)
Change the programming language of this snippet from C++ to Python without modifying what it does.
#include <algorithm> #include <iostream> #include <numeric> #include <sstream> #include <vector> template <typename iterator> bool sum_of_any_subset(int n, iterator begin, iterator end) { if (begin == end) return false; if (std::find(begin, end, n) != end) return true; int total = std::accumulate(begin, end, 0); if (n == total) return true; if (n > total) return false; --end; int d = n - *end; return (d > 0 && sum_of_any_subset(d, begin, end)) || sum_of_any_subset(n, begin, end); } std::vector<int> factors(int n) { std::vector<int> f{1}; for (int i = 2; i * i <= n; ++i) { if (n % i == 0) { f.push_back(i); if (i * i != n) f.push_back(n / i); } } std::sort(f.begin(), f.end()); return f; } bool is_practical(int n) { std::vector<int> f = factors(n); for (int i = 1; i < n; ++i) { if (!sum_of_any_subset(i, f.begin(), f.end())) return false; } return true; } std::string shorten(const std::vector<int>& v, size_t n) { std::ostringstream out; size_t size = v.size(), i = 0; if (n > 0 && size > 0) out << v[i++]; for (; i < n && i < size; ++i) out << ", " << v[i]; if (size > i + n) { out << ", ..."; i = size - n; } for (; i < size; ++i) out << ", " << v[i]; return out.str(); } int main() { std::vector<int> practical; for (int n = 1; n <= 333; ++n) { if (is_practical(n)) practical.push_back(n); } std::cout << "Found " << practical.size() << " practical numbers:\n" << shorten(practical, 10) << '\n'; for (int n : {666, 6666, 66666, 672, 720, 222222}) std::cout << n << " is " << (is_practical(n) ? "" : "not ") << "a practical number.\n"; return 0; }
from itertools import chain, cycle, accumulate, combinations from typing import List, Tuple def factors5(n: int) -> List[int]: def prime_powers(n): for c in accumulate(chain([2, 1, 2], cycle([2,4]))): if c*c > n: break if n%c: continue d,p = (), c while not n%c: n,p,d = n//c, p*c, d + (p,) yield(d) if n > 1: yield((n,)) r = [1] for e in prime_powers(n): r += [a*b for a in r for b in e] return r[:-1] def powerset(s: List[int]) -> List[Tuple[int, ...]]: return chain.from_iterable(combinations(s, r) for r in range(1, len(s)+1)) def is_practical(x: int) -> bool: if x == 1: return True if x %2: return False f = factors5(x) ps = powerset(f) found = {y for y in {sum(i) for i in ps} if 1 <= y < x} return len(found) == x - 1 if __name__ == '__main__': n = 333 p = [x for x in range(1, n + 1) if is_practical(x)] print(f"There are {len(p)} Practical numbers from 1 to {n}:") print(' ', str(p[:10])[1:-1], '...', str(p[-10:])[1:-1]) x = 666 print(f"\nSTRETCH GOAL: {x} is {'not ' if not is_practical(x) else ''}Practical.")
Write the same algorithm in Python as shown in this C++ implementation.
#include <cstdint> #include <iostream> #include <vector> #include <primesieve.hpp> void print_diffs(const std::vector<uint64_t>& vec) { for (size_t i = 0, n = vec.size(); i != n; ++i) { if (i != 0) std::cout << " (" << vec[i] - vec[i - 1] << ") "; std::cout << vec[i]; } std::cout << '\n'; } int main() { std::cout.imbue(std::locale("")); std::vector<uint64_t> asc, desc; std::vector<std::vector<uint64_t>> max_asc, max_desc; size_t max_asc_len = 0, max_desc_len = 0; uint64_t prime; const uint64_t limit = 1000000; for (primesieve::iterator pi; (prime = pi.next_prime()) < limit; ) { size_t alen = asc.size(); if (alen > 1 && prime - asc[alen - 1] <= asc[alen - 1] - asc[alen - 2]) asc.erase(asc.begin(), asc.end() - 1); asc.push_back(prime); if (asc.size() >= max_asc_len) { if (asc.size() > max_asc_len) { max_asc_len = asc.size(); max_asc.clear(); } max_asc.push_back(asc); } size_t dlen = desc.size(); if (dlen > 1 && prime - desc[dlen - 1] >= desc[dlen - 1] - desc[dlen - 2]) desc.erase(desc.begin(), desc.end() - 1); desc.push_back(prime); if (desc.size() >= max_desc_len) { if (desc.size() > max_desc_len) { max_desc_len = desc.size(); max_desc.clear(); } max_desc.push_back(desc); } } std::cout << "Longest run(s) of ascending prime gaps up to " << limit << ":\n"; for (const auto& v : max_asc) print_diffs(v); std::cout << "\nLongest run(s) of descending prime gaps up to " << limit << ":\n"; for (const auto& v : max_desc) print_diffs(v); return 0; }
from sympy import sieve primelist = list(sieve.primerange(2,1000000)) listlen = len(primelist) pindex = 1 old_diff = -1 curr_list=[primelist[0]] longest_list=[] while pindex < listlen: diff = primelist[pindex] - primelist[pindex-1] if diff > old_diff: curr_list.append(primelist[pindex]) if len(curr_list) > len(longest_list): longest_list = curr_list else: curr_list = [primelist[pindex-1],primelist[pindex]] old_diff = diff pindex += 1 print(longest_list) pindex = 1 old_diff = -1 curr_list=[primelist[0]] longest_list=[] while pindex < listlen: diff = primelist[pindex] - primelist[pindex-1] if diff < old_diff: curr_list.append(primelist[pindex]) if len(curr_list) > len(longest_list): longest_list = curr_list else: curr_list = [primelist[pindex-1],primelist[pindex]] old_diff = diff pindex += 1 print(longest_list)
Generate an equivalent Python version of this C++ code.
#include <cstdint> #include <iostream> #include <vector> #include <primesieve.hpp> void print_diffs(const std::vector<uint64_t>& vec) { for (size_t i = 0, n = vec.size(); i != n; ++i) { if (i != 0) std::cout << " (" << vec[i] - vec[i - 1] << ") "; std::cout << vec[i]; } std::cout << '\n'; } int main() { std::cout.imbue(std::locale("")); std::vector<uint64_t> asc, desc; std::vector<std::vector<uint64_t>> max_asc, max_desc; size_t max_asc_len = 0, max_desc_len = 0; uint64_t prime; const uint64_t limit = 1000000; for (primesieve::iterator pi; (prime = pi.next_prime()) < limit; ) { size_t alen = asc.size(); if (alen > 1 && prime - asc[alen - 1] <= asc[alen - 1] - asc[alen - 2]) asc.erase(asc.begin(), asc.end() - 1); asc.push_back(prime); if (asc.size() >= max_asc_len) { if (asc.size() > max_asc_len) { max_asc_len = asc.size(); max_asc.clear(); } max_asc.push_back(asc); } size_t dlen = desc.size(); if (dlen > 1 && prime - desc[dlen - 1] >= desc[dlen - 1] - desc[dlen - 2]) desc.erase(desc.begin(), desc.end() - 1); desc.push_back(prime); if (desc.size() >= max_desc_len) { if (desc.size() > max_desc_len) { max_desc_len = desc.size(); max_desc.clear(); } max_desc.push_back(desc); } } std::cout << "Longest run(s) of ascending prime gaps up to " << limit << ":\n"; for (const auto& v : max_asc) print_diffs(v); std::cout << "\nLongest run(s) of descending prime gaps up to " << limit << ":\n"; for (const auto& v : max_desc) print_diffs(v); return 0; }
from sympy import sieve primelist = list(sieve.primerange(2,1000000)) listlen = len(primelist) pindex = 1 old_diff = -1 curr_list=[primelist[0]] longest_list=[] while pindex < listlen: diff = primelist[pindex] - primelist[pindex-1] if diff > old_diff: curr_list.append(primelist[pindex]) if len(curr_list) > len(longest_list): longest_list = curr_list else: curr_list = [primelist[pindex-1],primelist[pindex]] old_diff = diff pindex += 1 print(longest_list) pindex = 1 old_diff = -1 curr_list=[primelist[0]] longest_list=[] while pindex < listlen: diff = primelist[pindex] - primelist[pindex-1] if diff < old_diff: curr_list.append(primelist[pindex]) if len(curr_list) > len(longest_list): longest_list = curr_list else: curr_list = [primelist[pindex-1],primelist[pindex]] old_diff = diff pindex += 1 print(longest_list)
Transform the following C++ implementation into Python, maintaining the same output and logic.
#include <iostream> int main() { auto double1 = 2.5; auto float1 = 2.5f; auto longdouble1 = 2.5l; auto double2 = 2.5e-3; auto float2 = 2.5e3f; auto double3 = 0x1p4; auto float3 = 0xbeefp-8f; std::cout << "\ndouble1: " << double1; std::cout << "\nfloat1: " << float1; std::cout << "\nlongdouble1: " << longdouble1; std::cout << "\ndouble2: " << double2; std::cout << "\nfloat2: " << float2; std::cout << "\ndouble3: " << double3; std::cout << "\nfloat3: " << float3; std::cout << "\n"; }
2.3 .3 .3e4 .3e+34 .3e-34 2.e34
Port the provided C++ code into Python while preserving the original functionality.
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <cstdlib> #include <string> #include <bitset> using namespace std; typedef bitset<4> hood_t; struct node { int val; hood_t neighbors; }; class nSolver { public: void solve(vector<string>& puzz, int max_wid) { if (puzz.size() < 1) return; wid = max_wid; hei = static_cast<int>(puzz.size()) / wid; max = wid * hei; int len = max, c = 0; arr = vector<node>(len, node({ 0, 0 })); weHave = vector<bool>(len + 1, false); for (const auto& s : puzz) { if (s == "*") { max--; arr[c++].val = -1; continue; } arr[c].val = atoi(s.c_str()); if (arr[c].val > 0) weHave[arr[c].val] = true; c++; } solveIt(); c = 0; for (auto&& s : puzz) { if (s == ".") s = std::to_string(arr[c].val); c++; } } private: bool search(int x, int y, int w, int dr) { if ((w > max && dr > 0) || (w < 1 && dr < 0) || (w == max && weHave[w])) return true; node& n = arr[x + y * wid]; n.neighbors = getNeighbors(x, y); if (weHave[w]) { for (int d = 0; d < 4; d++) { if (n.neighbors[d]) { int a = x + dx[d], b = y + dy[d]; if (arr[a + b * wid].val == w) if (search(a, b, w + dr, dr)) return true; } } return false; } for (int d = 0; d < 4; d++) { if (n.neighbors[d]) { int a = x + dx[d], b = y + dy[d]; if (arr[a + b * wid].val == 0) { arr[a + b * wid].val = w; if (search(a, b, w + dr, dr)) return true; arr[a + b * wid].val = 0; } } } return false; } hood_t getNeighbors(int x, int y) { hood_t retval; for (int xx = 0; xx < 4; xx++) { int a = x + dx[xx], b = y + dy[xx]; if (a < 0 || b < 0 || a >= wid || b >= hei) continue; if (arr[a + b * wid].val > -1) retval.set(xx); } return retval; } void solveIt() { int x, y, z; findStart(x, y, z); if (z == 99999) { cout << "\nCan't find start point!\n"; return; } search(x, y, z + 1, 1); if (z > 1) search(x, y, z - 1, -1); } void findStart(int& x, int& y, int& z) { z = 99999; for (int b = 0; b < hei; b++) for (int a = 0; a < wid; a++) if (arr[a + wid * b].val > 0 && arr[a + wid * b].val < z) { x = a; y = b; z = arr[a + wid * b].val; } } vector<int> dx = vector<int>({ -1, 1, 0, 0 }); vector<int> dy = vector<int>({ 0, 0, -1, 1 }); int wid, hei, max; vector<node> arr; vector<bool> weHave; }; int main(int argc, char* argv[]) { int wid; string p; p = "17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45"; wid = 9; istringstream iss(p); vector<string> puzz; copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(puzz)); nSolver s; s.solve(puzz, wid); int c = 0; for (const auto& s : puzz) { if (s != "*" && s != ".") { if (atoi(s.c_str()) < 10) cout << "0"; cout << s << " "; } else cout << " "; if (++c >= wid) { cout << endl; c = 0; } } cout << endl << endl; return system("pause"); }
from sys import stdout neighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]] exists = [] lastNumber = 0 wid = 0 hei = 0 def find_next(pa, x, y, z): for i in range(4): a = x + neighbours[i][0] b = y + neighbours[i][1] if wid > a > -1 and hei > b > -1: if pa[a][b] == z: return a, b return -1, -1 def find_solution(pa, x, y, z): if z > lastNumber: return 1 if exists[z] == 1: s = find_next(pa, x, y, z) if s[0] < 0: return 0 return find_solution(pa, s[0], s[1], z + 1) for i in range(4): a = x + neighbours[i][0] b = y + neighbours[i][1] if wid > a > -1 and hei > b > -1: if pa[a][b] == 0: pa[a][b] = z r = find_solution(pa, a, b, z + 1) if r == 1: return 1 pa[a][b] = 0 return 0 def solve(pz, w, h): global lastNumber, wid, hei, exists lastNumber = w * h wid = w hei = h exists = [0 for j in range(lastNumber + 1)] pa = [[0 for j in range(h)] for i in range(w)] st = pz.split() idx = 0 for j in range(h): for i in range(w): if st[idx] == ".": idx += 1 else: pa[i][j] = int(st[idx]) exists[pa[i][j]] = 1 idx += 1 x = 0 y = 0 t = w * h + 1 for j in range(h): for i in range(w): if pa[i][j] != 0 and pa[i][j] < t: t = pa[i][j] x = i y = j return find_solution(pa, x, y, t + 1), pa def show_result(r): if r[0] == 1: for j in range(hei): for i in range(wid): stdout.write(" {:0{}d}".format(r[1][i][j], 2)) print() else: stdout.write("No Solution!\n") print() r = solve(". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17" " . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1 2 . . . . . . . . . . .", 9, 9) show_result(r) r = solve(". . . . . . . . . . 11 12 15 18 21 62 61 . . 6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37" " . 1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .", 9, 9) show_result(r) r = solve("17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55" " . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45", 9, 9) show_result(r)
Produce a language-to-language conversion: from C++ to Python, same semantics.
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <cstdlib> #include <string> #include <bitset> using namespace std; typedef bitset<4> hood_t; struct node { int val; hood_t neighbors; }; class nSolver { public: void solve(vector<string>& puzz, int max_wid) { if (puzz.size() < 1) return; wid = max_wid; hei = static_cast<int>(puzz.size()) / wid; max = wid * hei; int len = max, c = 0; arr = vector<node>(len, node({ 0, 0 })); weHave = vector<bool>(len + 1, false); for (const auto& s : puzz) { if (s == "*") { max--; arr[c++].val = -1; continue; } arr[c].val = atoi(s.c_str()); if (arr[c].val > 0) weHave[arr[c].val] = true; c++; } solveIt(); c = 0; for (auto&& s : puzz) { if (s == ".") s = std::to_string(arr[c].val); c++; } } private: bool search(int x, int y, int w, int dr) { if ((w > max && dr > 0) || (w < 1 && dr < 0) || (w == max && weHave[w])) return true; node& n = arr[x + y * wid]; n.neighbors = getNeighbors(x, y); if (weHave[w]) { for (int d = 0; d < 4; d++) { if (n.neighbors[d]) { int a = x + dx[d], b = y + dy[d]; if (arr[a + b * wid].val == w) if (search(a, b, w + dr, dr)) return true; } } return false; } for (int d = 0; d < 4; d++) { if (n.neighbors[d]) { int a = x + dx[d], b = y + dy[d]; if (arr[a + b * wid].val == 0) { arr[a + b * wid].val = w; if (search(a, b, w + dr, dr)) return true; arr[a + b * wid].val = 0; } } } return false; } hood_t getNeighbors(int x, int y) { hood_t retval; for (int xx = 0; xx < 4; xx++) { int a = x + dx[xx], b = y + dy[xx]; if (a < 0 || b < 0 || a >= wid || b >= hei) continue; if (arr[a + b * wid].val > -1) retval.set(xx); } return retval; } void solveIt() { int x, y, z; findStart(x, y, z); if (z == 99999) { cout << "\nCan't find start point!\n"; return; } search(x, y, z + 1, 1); if (z > 1) search(x, y, z - 1, -1); } void findStart(int& x, int& y, int& z) { z = 99999; for (int b = 0; b < hei; b++) for (int a = 0; a < wid; a++) if (arr[a + wid * b].val > 0 && arr[a + wid * b].val < z) { x = a; y = b; z = arr[a + wid * b].val; } } vector<int> dx = vector<int>({ -1, 1, 0, 0 }); vector<int> dy = vector<int>({ 0, 0, -1, 1 }); int wid, hei, max; vector<node> arr; vector<bool> weHave; }; int main(int argc, char* argv[]) { int wid; string p; p = "17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45"; wid = 9; istringstream iss(p); vector<string> puzz; copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(puzz)); nSolver s; s.solve(puzz, wid); int c = 0; for (const auto& s : puzz) { if (s != "*" && s != ".") { if (atoi(s.c_str()) < 10) cout << "0"; cout << s << " "; } else cout << " "; if (++c >= wid) { cout << endl; c = 0; } } cout << endl << endl; return system("pause"); }
from sys import stdout neighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]] exists = [] lastNumber = 0 wid = 0 hei = 0 def find_next(pa, x, y, z): for i in range(4): a = x + neighbours[i][0] b = y + neighbours[i][1] if wid > a > -1 and hei > b > -1: if pa[a][b] == z: return a, b return -1, -1 def find_solution(pa, x, y, z): if z > lastNumber: return 1 if exists[z] == 1: s = find_next(pa, x, y, z) if s[0] < 0: return 0 return find_solution(pa, s[0], s[1], z + 1) for i in range(4): a = x + neighbours[i][0] b = y + neighbours[i][1] if wid > a > -1 and hei > b > -1: if pa[a][b] == 0: pa[a][b] = z r = find_solution(pa, a, b, z + 1) if r == 1: return 1 pa[a][b] = 0 return 0 def solve(pz, w, h): global lastNumber, wid, hei, exists lastNumber = w * h wid = w hei = h exists = [0 for j in range(lastNumber + 1)] pa = [[0 for j in range(h)] for i in range(w)] st = pz.split() idx = 0 for j in range(h): for i in range(w): if st[idx] == ".": idx += 1 else: pa[i][j] = int(st[idx]) exists[pa[i][j]] = 1 idx += 1 x = 0 y = 0 t = w * h + 1 for j in range(h): for i in range(w): if pa[i][j] != 0 and pa[i][j] < t: t = pa[i][j] x = i y = j return find_solution(pa, x, y, t + 1), pa def show_result(r): if r[0] == 1: for j in range(hei): for i in range(wid): stdout.write(" {:0{}d}".format(r[1][i][j], 2)) print() else: stdout.write("No Solution!\n") print() r = solve(". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17" " . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1 2 . . . . . . . . . . .", 9, 9) show_result(r) r = solve(". . . . . . . . . . 11 12 15 18 21 62 61 . . 6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37" " . 1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .", 9, 9) show_result(r) r = solve("17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55" " . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45", 9, 9) show_result(r)
Can you help me rewrite this code in Python instead of C++, keeping it the same logically?
#include <iostream> auto Zero = [](auto){ return [](auto x){ return x; }; }; auto True = [](auto a){ return [=](auto){ return a; }; }; auto False = [](auto){ return [](auto b){ return b; }; }; auto Successor(auto a) { return [=](auto f) { return [=](auto x) { return a(f)(f(x)); }; }; } auto Add(auto a, auto b) { return [=](auto f) { return [=](auto x) { return a(f)(b(f)(x)); }; }; } auto Multiply(auto a, auto b) { return [=](auto f) { return a(b(f)); }; } auto Exp(auto a, auto b) { return b(a); } auto IsZero(auto a){ return a([](auto){ return False; })(True); } auto Predecessor(auto a) { return [=](auto f) { return [=](auto x) { return a( [=](auto g) { return [=](auto h){ return h(g(f)); }; } )([=](auto){ return x; })([](auto y){ return y; }); }; }; } auto Subtract(auto a, auto b) { { return b([](auto c){ return Predecessor(c); })(a); }; } namespace { auto Divr(decltype(Zero), auto) { return Zero; } auto Divr(auto a, auto b) { auto a_minus_b = Subtract(a, b); auto isZero = IsZero(a_minus_b); return isZero (Zero) (Successor(Divr(isZero(Zero)(a_minus_b), b))); } } auto Divide(auto a, auto b) { return Divr(Successor(a), b); } template <int N> constexpr auto ToChurch() { if constexpr(N<=0) return Zero; else return Successor(ToChurch<N-1>()); } int ToInt(auto church) { return church([](int n){ return n + 1; })(0); } int main() { auto three = Successor(Successor(Successor(Zero))); auto four = Successor(three); auto six = ToChurch<6>(); auto ten = ToChurch<10>(); auto thousand = Exp(ten, three); std::cout << "\n 3 + 4 = " << ToInt(Add(three, four)); std::cout << "\n 3 * 4 = " << ToInt(Multiply(three, four)); std::cout << "\n 3^4 = " << ToInt(Exp(three, four)); std::cout << "\n 4^3 = " << ToInt(Exp(four, three)); std::cout << "\n 0^0 = " << ToInt(Exp(Zero, Zero)); std::cout << "\n 4 - 3 = " << ToInt(Subtract(four, three)); std::cout << "\n 3 - 4 = " << ToInt(Subtract(three, four)); std::cout << "\n 6 / 3 = " << ToInt(Divide(six, three)); std::cout << "\n 3 / 6 = " << ToInt(Divide(three, six)); auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand)); auto looloolool = Successor(looloolooo); std::cout << "\n 10^9 + 10^6 + 10^3 + 1 = " << ToInt(looloolool); std::cout << "\n golden ratio = " << thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << "\n"; }
from itertools import repeat from functools import reduce def churchZero(): return lambda f: identity def churchSucc(cn): return lambda f: compose(f)(cn(f)) def churchAdd(m): return lambda n: lambda f: compose(m(f))(n(f)) def churchMult(m): return lambda n: compose(m)(n) def churchExp(m): return lambda n: n(m) def churchFromInt(n): return lambda f: ( foldl (compose) (identity) (replicate(n)(f)) ) def churchFromInt_(n): if 0 == n: return churchZero() else: return churchSucc(churchFromInt(n - 1)) def intFromChurch(cn): return cn(succ)(0) def main(): 'Tests' cThree = churchFromInt(3) cFour = churchFromInt(4) print(list(map(intFromChurch, [ churchAdd(cThree)(cFour), churchMult(cThree)(cFour), churchExp(cFour)(cThree), churchExp(cThree)(cFour), ]))) def compose(f): return lambda g: lambda x: g(f(x)) def foldl(f): def go(acc, xs): return reduce(lambda a, x: f(a)(x), xs, acc) return lambda acc: lambda xs: go(acc, xs) def identity(x): return x def replicate(n): return lambda x: repeat(x, n) def succ(x): return 1 + x if isinstance(x, int) else ( chr(1 + ord(x)) ) if __name__ == '__main__': main()
Produce a language-to-language conversion: from C++ to Python, same semantics.
#include <iostream> auto Zero = [](auto){ return [](auto x){ return x; }; }; auto True = [](auto a){ return [=](auto){ return a; }; }; auto False = [](auto){ return [](auto b){ return b; }; }; auto Successor(auto a) { return [=](auto f) { return [=](auto x) { return a(f)(f(x)); }; }; } auto Add(auto a, auto b) { return [=](auto f) { return [=](auto x) { return a(f)(b(f)(x)); }; }; } auto Multiply(auto a, auto b) { return [=](auto f) { return a(b(f)); }; } auto Exp(auto a, auto b) { return b(a); } auto IsZero(auto a){ return a([](auto){ return False; })(True); } auto Predecessor(auto a) { return [=](auto f) { return [=](auto x) { return a( [=](auto g) { return [=](auto h){ return h(g(f)); }; } )([=](auto){ return x; })([](auto y){ return y; }); }; }; } auto Subtract(auto a, auto b) { { return b([](auto c){ return Predecessor(c); })(a); }; } namespace { auto Divr(decltype(Zero), auto) { return Zero; } auto Divr(auto a, auto b) { auto a_minus_b = Subtract(a, b); auto isZero = IsZero(a_minus_b); return isZero (Zero) (Successor(Divr(isZero(Zero)(a_minus_b), b))); } } auto Divide(auto a, auto b) { return Divr(Successor(a), b); } template <int N> constexpr auto ToChurch() { if constexpr(N<=0) return Zero; else return Successor(ToChurch<N-1>()); } int ToInt(auto church) { return church([](int n){ return n + 1; })(0); } int main() { auto three = Successor(Successor(Successor(Zero))); auto four = Successor(three); auto six = ToChurch<6>(); auto ten = ToChurch<10>(); auto thousand = Exp(ten, three); std::cout << "\n 3 + 4 = " << ToInt(Add(three, four)); std::cout << "\n 3 * 4 = " << ToInt(Multiply(three, four)); std::cout << "\n 3^4 = " << ToInt(Exp(three, four)); std::cout << "\n 4^3 = " << ToInt(Exp(four, three)); std::cout << "\n 0^0 = " << ToInt(Exp(Zero, Zero)); std::cout << "\n 4 - 3 = " << ToInt(Subtract(four, three)); std::cout << "\n 3 - 4 = " << ToInt(Subtract(three, four)); std::cout << "\n 6 / 3 = " << ToInt(Divide(six, three)); std::cout << "\n 3 / 6 = " << ToInt(Divide(three, six)); auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand)); auto looloolool = Successor(looloolooo); std::cout << "\n 10^9 + 10^6 + 10^3 + 1 = " << ToInt(looloolool); std::cout << "\n golden ratio = " << thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << "\n"; }
from itertools import repeat from functools import reduce def churchZero(): return lambda f: identity def churchSucc(cn): return lambda f: compose(f)(cn(f)) def churchAdd(m): return lambda n: lambda f: compose(m(f))(n(f)) def churchMult(m): return lambda n: compose(m)(n) def churchExp(m): return lambda n: n(m) def churchFromInt(n): return lambda f: ( foldl (compose) (identity) (replicate(n)(f)) ) def churchFromInt_(n): if 0 == n: return churchZero() else: return churchSucc(churchFromInt(n - 1)) def intFromChurch(cn): return cn(succ)(0) def main(): 'Tests' cThree = churchFromInt(3) cFour = churchFromInt(4) print(list(map(intFromChurch, [ churchAdd(cThree)(cFour), churchMult(cThree)(cFour), churchExp(cFour)(cThree), churchExp(cThree)(cFour), ]))) def compose(f): return lambda g: lambda x: g(f(x)) def foldl(f): def go(acc, xs): return reduce(lambda a, x: f(a)(x), xs, acc) return lambda acc: lambda xs: go(acc, xs) def identity(x): return x def replicate(n): return lambda x: repeat(x, n) def succ(x): return 1 + x if isinstance(x, int) else ( chr(1 + ord(x)) ) if __name__ == '__main__': main()
Keep all operations the same but rewrite the snippet in Python.
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] = 2; dx[2] = 2; dy[2] = -2; dx[3] = 2; dy[3] = 2; dx[4] = -3; dy[4] = 0; dx[5] = 3; dy[5] = 0; dx[6] = 0; dy[6] = -3; dx[7] = 0; dy[7] = 3; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val == 0 ) { x = a; y = b; z = 1; arr[a + wid * b].val = z; return; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *"; wid = 7; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
from sys import stdout neighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]] cnt = 0 pWid = 0 pHei = 0 def is_valid(a, b): return -1 < a < pWid and -1 < b < pHei def iterate(pa, x, y, v): if v > cnt: return 1 for i in range(len(neighbours)): a = x + neighbours[i][0] b = y + neighbours[i][1] if is_valid(a, b) and pa[a][b] == 0: pa[a][b] = v r = iterate(pa, a, b, v + 1) if r == 1: return r pa[a][b] = 0 return 0 def solve(pz, w, h): global cnt, pWid, pHei pa = [[-1 for j in range(h)] for i in range(w)] f = 0 pWid = w pHei = h for j in range(h): for i in range(w): if pz[f] == "1": pa[i][j] = 0 cnt += 1 f += 1 for y in range(h): for x in range(w): if pa[x][y] == 0: pa[x][y] = 1 if 1 == iterate(pa, x, y, 2): return 1, pa pa[x][y] = 0 return 0, pa r = solve("011011011111111111111011111000111000001000", 7, 6) if r[0] == 1: for j in range(6): for i in range(7): if r[1][i][j] == -1: stdout.write(" ") else: stdout.write(" {:0{}d}".format(r[1][i][j], 2)) print() else: stdout.write("No solution!")
Generate an equivalent Python version of this C++ code.
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] = 2; dx[2] = 2; dy[2] = -2; dx[3] = 2; dy[3] = 2; dx[4] = -3; dy[4] = 0; dx[5] = 3; dy[5] = 0; dx[6] = 0; dy[6] = -3; dx[7] = 0; dy[7] = 3; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val == 0 ) { x = a; y = b; z = 1; arr[a + wid * b].val = z; return; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *"; wid = 7; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
from sys import stdout neighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]] cnt = 0 pWid = 0 pHei = 0 def is_valid(a, b): return -1 < a < pWid and -1 < b < pHei def iterate(pa, x, y, v): if v > cnt: return 1 for i in range(len(neighbours)): a = x + neighbours[i][0] b = y + neighbours[i][1] if is_valid(a, b) and pa[a][b] == 0: pa[a][b] = v r = iterate(pa, a, b, v + 1) if r == 1: return r pa[a][b] = 0 return 0 def solve(pz, w, h): global cnt, pWid, pHei pa = [[-1 for j in range(h)] for i in range(w)] f = 0 pWid = w pHei = h for j in range(h): for i in range(w): if pz[f] == "1": pa[i][j] = 0 cnt += 1 f += 1 for y in range(h): for x in range(w): if pa[x][y] == 0: pa[x][y] = 1 if 1 == iterate(pa, x, y, 2): return 1, pa pa[x][y] = 0 return 0, pa r = solve("011011011111111111111011111000111000001000", 7, 6) if r[0] == 1: for j in range(6): for i in range(7): if r[1][i][j] == -1: stdout.write(" ") else: stdout.write(" {:0{}d}".format(r[1][i][j], 2)) print() else: stdout.write("No solution!")
Port the following code from C++ to Python with equivalent syntax and logic.
template<uint _N, uint _G> class Nonogram { enum class ng_val : char {X='#',B='.',V='?'}; template<uint _NG> struct N { N() {} N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){} std::bitset<_NG> X, B, T, Tx, Tb; std::vector<int> ng; int En, gNG; void fn (const int n,const int i,const int g,const int e,const int l){ if (fe(g,l,false) and fe(g+l,e,true)){ if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);} else { if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;} }} if (l<=gNG-g-i-1) fn(n,i,g,e,l+1); } void fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);} ng_val fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;} inline bool fe (const int n,const int i, const bool g){ for (int e = n;e<n+i;++e) if ((g and fg(e)==ng_val::B) or (!g and fg(e)==ng_val::X)) return false; else T[e] = g; return true; } int fl (){ if (En == 1) return 1; Tx.set(); Tb.set(); En=0; fn(0,std::accumulate(ng.cbegin(),ng.cend(),0)+ng.size()-1,0,ng[0],0); return En; }}; std::vector<N<_G>> ng; std::vector<N<_N>> gn; int En, zN, zG; void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);} public: Nonogram(const std::vector<std::vector<int>>& n,const std::vector<std::vector<int>>& i,const std::vector<std::string>& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) { for (int n=0; n<zG; n++) gn.push_back(N<_N>(i[n],zN)); for (int i=0; i<zN; i++) { ng.push_back(N<_G>(n[i],zG)); if (i < g.size()) for(int e=0; e<zG or e<g[i].size(); e++) if (g[i][e]=='#') setCell(i,e,true); }} bool solve(){ int i{}, g{}; for (int l = 0; l<zN; l++) { if ((g = ng[l].fl()) == 0) return false; else i+=g; for (int i = 0; i<zG; i++) if (ng[l].Tx[i] != ng[l].Tb[i]) setCell (l,i,ng[l].Tx[i]); } for (int l = 0; l<zG; l++) { if ((g = gn[l].fl()) == 0) return false; else i+=g; for (int i = 0; i<zN; i++) if (gn[l].Tx[i] != gn[l].Tb[i]) setCell (i,l,gn[l].Tx[i]); } if (i == En) return false; else En = i; if (i == zN+zG) return true; else return solve(); } const std::string toStr() const { std::ostringstream n; for (int i = 0; i<zN; i++){for (int g = 0; g<zG; g++){n << static_cast<char>(ng[i].fg(g));}n<<std::endl;} return n.str(); }};
from itertools import izip def gen_row(w, s): def gen_seg(o, sp): if not o: return [[2] * sp] return [[2] * x + o[0] + tail for x in xrange(1, sp - len(o) + 2) for tail in gen_seg(o[1:], sp - x)] return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))] def deduce(hr, vr): def allowable(row): return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row) def fits(a, b): return all(x & y for x, y in izip(a, b)) def fix_col(n): c = [x[n] for x in can_do] cols[n] = [x for x in cols[n] if fits(x, c)] for i, x in enumerate(allowable(cols[n])): if x != can_do[i][n]: mod_rows.add(i) can_do[i][n] &= x def fix_row(n): c = can_do[n] rows[n] = [x for x in rows[n] if fits(x, c)] for i, x in enumerate(allowable(rows[n])): if x != can_do[n][i]: mod_cols.add(i) can_do[n][i] &= x def show_gram(m): for x in m: print " ".join("x print w, h = len(vr), len(hr) rows = [gen_row(w, x) for x in hr] cols = [gen_row(h, x) for x in vr] can_do = map(allowable, rows) mod_rows, mod_cols = set(), set(xrange(w)) while mod_cols: for i in mod_cols: fix_col(i) mod_cols = set() for i in mod_rows: fix_row(i) mod_rows = set() if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)): print "Solution would be unique" else: print "Solution may not be unique, doing exhaustive search:" out = [0] * h def try_all(n = 0): if n >= h: for j in xrange(w): if [x[j] for x in out] not in cols[j]: return 0 show_gram(out) return 1 sol = 0 for x in rows[n]: out[n] = x sol += try_all(n + 1) return sol n = try_all() if not n: print "No solution." elif n == 1: print "Unique solution." else: print n, "solutions." print def solve(p, show_runs=True): s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()] for l in p.splitlines()] if show_runs: print "Horizontal runs:", s[0] print "Vertical runs:", s[1] deduce(s[0], s[1]) def main(): fn = "nonogram_problems.txt" for p in (x for x in open(fn).read().split("\n\n") if x): solve(p) print "Extra example not solvable by deduction alone:" solve("B B A A\nB B A A") print "Extra example where there is no solution:" solve("B A A\nA A A") main()
Translate this program into Python but keep the logic exactly as in C++.
template<uint _N, uint _G> class Nonogram { enum class ng_val : char {X='#',B='.',V='?'}; template<uint _NG> struct N { N() {} N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){} std::bitset<_NG> X, B, T, Tx, Tb; std::vector<int> ng; int En, gNG; void fn (const int n,const int i,const int g,const int e,const int l){ if (fe(g,l,false) and fe(g+l,e,true)){ if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);} else { if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;} }} if (l<=gNG-g-i-1) fn(n,i,g,e,l+1); } void fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);} ng_val fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;} inline bool fe (const int n,const int i, const bool g){ for (int e = n;e<n+i;++e) if ((g and fg(e)==ng_val::B) or (!g and fg(e)==ng_val::X)) return false; else T[e] = g; return true; } int fl (){ if (En == 1) return 1; Tx.set(); Tb.set(); En=0; fn(0,std::accumulate(ng.cbegin(),ng.cend(),0)+ng.size()-1,0,ng[0],0); return En; }}; std::vector<N<_G>> ng; std::vector<N<_N>> gn; int En, zN, zG; void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);} public: Nonogram(const std::vector<std::vector<int>>& n,const std::vector<std::vector<int>>& i,const std::vector<std::string>& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) { for (int n=0; n<zG; n++) gn.push_back(N<_N>(i[n],zN)); for (int i=0; i<zN; i++) { ng.push_back(N<_G>(n[i],zG)); if (i < g.size()) for(int e=0; e<zG or e<g[i].size(); e++) if (g[i][e]=='#') setCell(i,e,true); }} bool solve(){ int i{}, g{}; for (int l = 0; l<zN; l++) { if ((g = ng[l].fl()) == 0) return false; else i+=g; for (int i = 0; i<zG; i++) if (ng[l].Tx[i] != ng[l].Tb[i]) setCell (l,i,ng[l].Tx[i]); } for (int l = 0; l<zG; l++) { if ((g = gn[l].fl()) == 0) return false; else i+=g; for (int i = 0; i<zN; i++) if (gn[l].Tx[i] != gn[l].Tb[i]) setCell (i,l,gn[l].Tx[i]); } if (i == En) return false; else En = i; if (i == zN+zG) return true; else return solve(); } const std::string toStr() const { std::ostringstream n; for (int i = 0; i<zN; i++){for (int g = 0; g<zG; g++){n << static_cast<char>(ng[i].fg(g));}n<<std::endl;} return n.str(); }};
from itertools import izip def gen_row(w, s): def gen_seg(o, sp): if not o: return [[2] * sp] return [[2] * x + o[0] + tail for x in xrange(1, sp - len(o) + 2) for tail in gen_seg(o[1:], sp - x)] return [x[1:] for x in gen_seg([[1] * i for i in s], w + 1 - sum(s))] def deduce(hr, vr): def allowable(row): return reduce(lambda a, b: [x | y for x, y in izip(a, b)], row) def fits(a, b): return all(x & y for x, y in izip(a, b)) def fix_col(n): c = [x[n] for x in can_do] cols[n] = [x for x in cols[n] if fits(x, c)] for i, x in enumerate(allowable(cols[n])): if x != can_do[i][n]: mod_rows.add(i) can_do[i][n] &= x def fix_row(n): c = can_do[n] rows[n] = [x for x in rows[n] if fits(x, c)] for i, x in enumerate(allowable(rows[n])): if x != can_do[n][i]: mod_cols.add(i) can_do[n][i] &= x def show_gram(m): for x in m: print " ".join("x print w, h = len(vr), len(hr) rows = [gen_row(w, x) for x in hr] cols = [gen_row(h, x) for x in vr] can_do = map(allowable, rows) mod_rows, mod_cols = set(), set(xrange(w)) while mod_cols: for i in mod_cols: fix_col(i) mod_cols = set() for i in mod_rows: fix_row(i) mod_rows = set() if all(can_do[i][j] in (1, 2) for j in xrange(w) for i in xrange(h)): print "Solution would be unique" else: print "Solution may not be unique, doing exhaustive search:" out = [0] * h def try_all(n = 0): if n >= h: for j in xrange(w): if [x[j] for x in out] not in cols[j]: return 0 show_gram(out) return 1 sol = 0 for x in rows[n]: out[n] = x sol += try_all(n + 1) return sol n = try_all() if not n: print "No solution." elif n == 1: print "Unique solution." else: print n, "solutions." print def solve(p, show_runs=True): s = [[[ord(c) - ord('A') + 1 for c in w] for w in l.split()] for l in p.splitlines()] if show_runs: print "Horizontal runs:", s[0] print "Vertical runs:", s[1] deduce(s[0], s[1]) def main(): fn = "nonogram_problems.txt" for p in (x for x in open(fn).read().split("\n\n") if x): solve(p) print "Extra example not solvable by deduction alone:" solve("B B A A\nB B A A") print "Extra example where there is no solution:" solve("B A A\nA A A") main()
Please provide an equivalent version of this C++ code in Python.
#include <iomanip> #include <ctime> #include <iostream> #include <vector> #include <string> #include <algorithm> #include <fstream> const int WID = 10, HEI = 10, MIN_WORD_LEN = 3, MIN_WORD_CNT = 25; class Cell { public: Cell() : val( 0 ), cntOverlap( 0 ) {} char val; int cntOverlap; }; class Word { public: Word( std::string s, int cs, int rs, int ce, int re, int dc, int dr ) : word( s ), cols( cs ), rows( rs ), cole( ce ), rowe( re ), dx( dc ), dy( dr ) {} bool operator ==( const std::string& s ) { return 0 == word.compare( s ); } std::string word; int cols, rows, cole, rowe, dx, dy; }; class words { public: void create( std::string& file ) { std::ifstream f( file.c_str(), std::ios_base::in ); std::string word; while( f >> word ) { if( word.length() < MIN_WORD_LEN || word.length() > WID || word.length() > HEI ) continue; if( word.find_first_not_of( "abcdefghijklmnopqrstuvwxyz" ) != word.npos ) continue; dictionary.push_back( word ); } f.close(); std::random_shuffle( dictionary.begin(), dictionary.end() ); buildPuzzle(); } void printOut() { std::cout << "\t"; for( int x = 0; x < WID; x++ ) std::cout << x << " "; std::cout << "\n\n"; for( int y = 0; y < HEI; y++ ) { std::cout << y << "\t"; for( int x = 0; x < WID; x++ ) std::cout << puzzle[x][y].val << " "; std::cout << "\n"; } size_t wid1 = 0, wid2 = 0; for( size_t x = 0; x < used.size(); x++ ) { if( x & 1 ) { if( used[x].word.length() > wid1 ) wid1 = used[x].word.length(); } else { if( used[x].word.length() > wid2 ) wid2 = used[x].word.length(); } } std::cout << "\n"; std::vector<Word>::iterator w = used.begin(); while( w != used.end() ) { std::cout << std::right << std::setw( wid1 ) << ( *w ).word << " (" << ( *w ).cols << ", " << ( *w ).rows << ") (" << ( *w ).cole << ", " << ( *w ).rowe << ")\t"; w++; if( w == used.end() ) break; std::cout << std::setw( wid2 ) << ( *w ).word << " (" << ( *w ).cols << ", " << ( *w ).rows << ") (" << ( *w ).cole << ", " << ( *w ).rowe << ")\n"; w++; } std::cout << "\n\n"; } private: void addMsg() { std::string msg = "ROSETTACODE"; int stp = 9, p = rand() % stp; for( size_t x = 0; x < msg.length(); x++ ) { puzzle[p % WID][p / HEI].val = msg.at( x ); p += rand() % stp + 4; } } int getEmptySpaces() { int es = 0; for( int y = 0; y < HEI; y++ ) { for( int x = 0; x < WID; x++ ) { if( !puzzle[x][y].val ) es++; } } return es; } bool check( std::string word, int c, int r, int dc, int dr ) { for( size_t a = 0; a < word.length(); a++ ) { if( c < 0 || r < 0 || c >= WID || r >= HEI ) return false; if( puzzle[c][r].val && puzzle[c][r].val != word.at( a ) ) return false; c += dc; r += dr; } return true; } bool setWord( std::string word, int c, int r, int dc, int dr ) { if( !check( word, c, r, dc, dr ) ) return false; int sx = c, sy = r; for( size_t a = 0; a < word.length(); a++ ) { if( !puzzle[c][r].val ) puzzle[c][r].val = word.at( a ); else puzzle[c][r].cntOverlap++; c += dc; r += dr; } used.push_back( Word( word, sx, sy, c - dc, r - dr, dc, dr ) ); return true; } bool add2Puzzle( std::string word ) { int x = rand() % WID, y = rand() % HEI, z = rand() % 8; for( int d = z; d < z + 8; d++ ) { switch( d % 8 ) { case 0: if( setWord( word, x, y, 1, 0 ) ) return true; break; case 1: if( setWord( word, x, y, -1, -1 ) ) return true; break; case 2: if( setWord( word, x, y, 0, 1 ) ) return true; break; case 3: if( setWord( word, x, y, 1, -1 ) ) return true; break; case 4: if( setWord( word, x, y, -1, 0 ) ) return true; break; case 5: if( setWord( word, x, y, -1, 1 ) ) return true; break; case 6: if( setWord( word, x, y, 0, -1 ) ) return true; break; case 7: if( setWord( word, x, y, 1, 1 ) ) return true; break; } } return false; } void clearWord() { if( used.size() ) { Word lastW = used.back(); used.pop_back(); for( size_t a = 0; a < lastW.word.length(); a++ ) { if( puzzle[lastW.cols][lastW.rows].cntOverlap == 0 ) { puzzle[lastW.cols][lastW.rows].val = 0; } if( puzzle[lastW.cols][lastW.rows].cntOverlap > 0 ) { puzzle[lastW.cols][lastW.rows].cntOverlap--; } lastW.cols += lastW.dx; lastW.rows += lastW.dy; } } } void buildPuzzle() { addMsg(); int es = 0, cnt = 0; size_t idx = 0; do { for( std::vector<std::string>::iterator w = dictionary.begin(); w != dictionary.end(); w++ ) { if( std::find( used.begin(), used.end(), *w ) != used.end() ) continue; if( add2Puzzle( *w ) ) { es = getEmptySpaces(); if( !es && used.size() >= MIN_WORD_CNT ) return; } } clearWord(); std::random_shuffle( dictionary.begin(), dictionary.end() ); } while( ++cnt < 100 ); } std::vector<Word> used; std::vector<std::string> dictionary; Cell puzzle[WID][HEI]; }; int main( int argc, char* argv[] ) { unsigned s = unsigned( time( 0 ) ); srand( s ); words w; w.create( std::string( "unixdict.txt" ) ); w.printOut(); return 0; }
import re from random import shuffle, randint dirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]] n_rows = 10 n_cols = 10 grid_size = n_rows * n_cols min_words = 25 class Grid: def __init__(self): self.num_attempts = 0 self.cells = [['' for _ in range(n_cols)] for _ in range(n_rows)] self.solutions = [] def read_words(filename): max_len = max(n_rows, n_cols) words = [] with open(filename, "r") as file: for line in file: s = line.strip().lower() if re.match(r'^[a-z]{3,' + re.escape(str(max_len)) + r'}$', s) is not None: words.append(s) return words def place_message(grid, msg): msg = re.sub(r'[^A-Z]', "", msg.upper()) message_len = len(msg) if 0 < message_len < grid_size: gap_size = grid_size // message_len for i in range(0, message_len): pos = i * gap_size + randint(0, gap_size) grid.cells[pos // n_cols][pos % n_cols] = msg[i] return message_len return 0 def try_location(grid, word, direction, pos): r = pos // n_cols c = pos % n_cols length = len(word) if (dirs[direction][0] == 1 and (length + c) > n_cols) or \ (dirs[direction][0] == -1 and (length - 1) > c) or \ (dirs[direction][1] == 1 and (length + r) > n_rows) or \ (dirs[direction][1] == -1 and (length - 1) > r): return 0 rr = r cc = c i = 0 overlaps = 0 while i < length: if grid.cells[rr][cc] != '' and grid.cells[rr][cc] != word[i]: return 0 cc += dirs[direction][0] rr += dirs[direction][1] i += 1 rr = r cc = c i = 0 while i < length: if grid.cells[rr][cc] == word[i]: overlaps += 1 else: grid.cells[rr][cc] = word[i] if i < length - 1: cc += dirs[direction][0] rr += dirs[direction][1] i += 1 letters_placed = length - overlaps if letters_placed > 0: grid.solutions.append("{0:<10} ({1},{2})({3},{4})".format(word, c, r, cc, rr)) return letters_placed def try_place_word(grid, word): rand_dir = randint(0, len(dirs)) rand_pos = randint(0, grid_size) for direction in range(0, len(dirs)): direction = (direction + rand_dir) % len(dirs) for pos in range(0, grid_size): pos = (pos + rand_pos) % grid_size letters_placed = try_location(grid, word, direction, pos) if letters_placed > 0: return letters_placed return 0 def create_word_search(words): grid = None num_attempts = 0 while num_attempts < 100: num_attempts += 1 shuffle(words) grid = Grid() message_len = place_message(grid, "Rosetta Code") target = grid_size - message_len cells_filled = 0 for word in words: cells_filled += try_place_word(grid, word) if cells_filled == target: if len(grid.solutions) >= min_words: grid.num_attempts = num_attempts return grid else: break return grid def print_result(grid): if grid is None or grid.num_attempts == 0: print("No grid to display") return size = len(grid.solutions) print("Attempts: {0}".format(grid.num_attempts)) print("Number of words: {0}".format(size)) print("\n 0 1 2 3 4 5 6 7 8 9\n") for r in range(0, n_rows): print("{0} ".format(r), end='') for c in range(0, n_cols): print(" %c " % grid.cells[r][c], end='') print() print() for i in range(0, size - 1, 2): print("{0} {1}".format(grid.solutions[i], grid.solutions[i+1])) if size % 2 == 1: print(grid.solutions[size - 1]) if __name__ == "__main__": print_result(create_word_search(read_words("unixdict.txt")))
Rewrite this program in Python while keeping its functionality equivalent to the C++ version.
#include <iostream> class CWidget; class CFactory { friend class CWidget; private: unsigned int m_uiCount; public: CFactory(); ~CFactory(); CWidget* GetWidget(); }; class CWidget { private: CFactory& m_parent; private: CWidget(); CWidget(const CWidget&); CWidget& operator=(const CWidget&); public: CWidget(CFactory& parent); ~CWidget(); }; CFactory::CFactory() : m_uiCount(0) {} CFactory::~CFactory() {} CWidget* CFactory::GetWidget() { return new CWidget(*this); } CWidget::CWidget(CFactory& parent) : m_parent(parent) { ++m_parent.m_uiCount; std::cout << "Widget spawning. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl; } CWidget::~CWidget() { --m_parent.m_uiCount; std::cout << "Widget dieing. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl; } int main() { CFactory factory; CWidget* pWidget1 = factory.GetWidget(); CWidget* pWidget2 = factory.GetWidget(); delete pWidget1; CWidget* pWidget3 = factory.GetWidget(); delete pWidget3; delete pWidget2; }
>>> class MyClassName: __private = 123 non_private = __private * 2 >>> mine = MyClassName() >>> mine.non_private 246 >>> mine.__private Traceback (most recent call last): File "<pyshell mine.__private AttributeError: 'MyClassName' object has no attribute '__private' >>> mine._MyClassName__private 123 >>>
Write the same algorithm in Python as shown in this C++ implementation.
#include <iostream> class CWidget; class CFactory { friend class CWidget; private: unsigned int m_uiCount; public: CFactory(); ~CFactory(); CWidget* GetWidget(); }; class CWidget { private: CFactory& m_parent; private: CWidget(); CWidget(const CWidget&); CWidget& operator=(const CWidget&); public: CWidget(CFactory& parent); ~CWidget(); }; CFactory::CFactory() : m_uiCount(0) {} CFactory::~CFactory() {} CWidget* CFactory::GetWidget() { return new CWidget(*this); } CWidget::CWidget(CFactory& parent) : m_parent(parent) { ++m_parent.m_uiCount; std::cout << "Widget spawning. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl; } CWidget::~CWidget() { --m_parent.m_uiCount; std::cout << "Widget dieing. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl; } int main() { CFactory factory; CWidget* pWidget1 = factory.GetWidget(); CWidget* pWidget2 = factory.GetWidget(); delete pWidget1; CWidget* pWidget3 = factory.GetWidget(); delete pWidget3; delete pWidget2; }
>>> class MyClassName: __private = 123 non_private = __private * 2 >>> mine = MyClassName() >>> mine.non_private 246 >>> mine.__private Traceback (most recent call last): File "<pyshell mine.__private AttributeError: 'MyClassName' object has no attribute '__private' >>> mine._MyClassName__private 123 >>>
Convert this C++ block to Python, preserving its control flow and logic.
#include <string> #include <fstream> #include <boost/serialization/string.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/serialization/base_object.hpp> #include <iostream> class Employee { public : Employee( ) { } Employee ( const std::string &dep , const std::string &namen ) : department( dep ) , name( namen ) { my_id = count++ ; } std::string getName( ) const { return name ; } std::string getDepartment( ) const { return department ; } int getId( ) const { return my_id ; } void setDepartment( const std::string &dep ) { department.assign( dep ) ; } virtual void print( ) { std::cout << "Name: " << name << '\n' ; std::cout << "Id: " << my_id << '\n' ; std::cout << "Department: " << department << '\n' ; } virtual ~Employee( ) { } static int count ; private : std::string name ; std::string department ; int my_id ; friend class boost::serialization::access ; template <class Archive> void serialize( Archive &ar, const unsigned int version ) { ar & my_id ; ar & name ; ar & department ; } } ; class Worker : public Employee { public : Worker( const std::string & dep, const std::string &namen , double hourlyPay ) : Employee( dep , namen ) , salary( hourlyPay) { } Worker( ) { } double getSalary( ) { return salary ; } void setSalary( double pay ) { if ( pay > 0 ) salary = pay ; } virtual void print( ) { Employee::print( ) ; std::cout << "wage per hour: " << salary << '\n' ; } private : double salary ; friend class boost::serialization::access ; template <class Archive> void serialize ( Archive & ar, const unsigned int version ) { ar & boost::serialization::base_object<Employee>( *this ) ; ar & salary ; } } ; int Employee::count = 0 ; int main( ) { std::ofstream storefile( "/home/ulrich/objects.dat" ) ; const Employee emp1( "maintenance" , "Fritz Schmalstieg" ) ; const Employee emp2( "maintenance" , "John Berry" ) ; const Employee emp3( "repair" , "Pawel Lichatschow" ) ; const Employee emp4( "IT" , "Marian Niculescu" ) ; const Worker worker1( "maintenance" , "Laurent Le Chef" , 20 ) ; const Worker worker2 ( "IT" , "Srinivan Taraman" , 55.35 ) ; boost::archive::text_oarchive oar ( storefile ) ; oar << emp1 ; oar << emp2 ; oar << emp3 ; oar << emp4 ; oar << worker1 ; oar << worker2 ; storefile.close( ) ; std::cout << "Reading out the data again\n" ; Employee e1 , e2 , e3 , e4 ; Worker w1, w2 ; std::ifstream sourcefile( "/home/ulrich/objects.dat" ) ; boost::archive::text_iarchive iar( sourcefile ) ; iar >> e1 >> e2 >> e3 >> e4 ; iar >> w1 >> w2 ; sourcefile.close( ) ; std::cout << "And here are the data after deserialization!( abridged):\n" ; e1.print( ) ; e3.print( ) ; w2.print( ) ; return 0 ; }
import pickle class Entity: def __init__(self): self.name = "Entity" def printName(self): print self.name class Person(Entity): def __init__(self): self.name = "Cletus" instance1 = Person() instance1.printName() instance2 = Entity() instance2.printName() target = file("objects.dat", "w") pickle.dump((instance1, instance2), target) target.close() print "Serialized..." target = file("objects.dat") i1, i2 = pickle.load(target) print "Unserialized..." i1.printName() i2.printName()
Port the following code from C++ to Python with equivalent syntax and logic.
#include <iostream> #include <functional> #include <map> #include <vector> struct Node { int length; std::map<char, int> edges; int suffix; Node(int l) : length(l), suffix(0) { } Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) { } }; constexpr int evenRoot = 0; constexpr int oddRoot = 1; std::vector<Node> eertree(const std::string& s) { std::vector<Node> tree = { Node(0, {}, oddRoot), Node(-1, {}, oddRoot) }; int suffix = oddRoot; int n, k; for (size_t i = 0; i < s.length(); ++i) { char c = s[i]; for (n = suffix; ; n = tree[n].suffix) { k = tree[n].length; int b = i - k - 1; if (b >= 0 && s[b] == c) { break; } } auto it = tree[n].edges.find(c); auto end = tree[n].edges.end(); if (it != end) { suffix = it->second; continue; } suffix = tree.size(); tree.push_back(Node(k + 2)); tree[n].edges[c] = suffix; if (tree[suffix].length == 1) { tree[suffix].suffix = 0; continue; } while (true) { n = tree[n].suffix; int b = i - tree[n].length - 1; if (b >= 0 && s[b] == c) { break; } } tree[suffix].suffix = tree[n].edges[c]; } return tree; } std::vector<std::string> subPalindromes(const std::vector<Node>& tree) { std::vector<std::string> s; std::function<void(int, std::string)> children; children = [&children, &tree, &s](int n, std::string p) { auto it = tree[n].edges.cbegin(); auto end = tree[n].edges.cend(); for (; it != end; it = std::next(it)) { auto c = it->first; auto m = it->second; std::string pl = c + p + c; s.push_back(pl); children(m, pl); } }; children(0, ""); auto it = tree[1].edges.cbegin(); auto end = tree[1].edges.cend(); for (; it != end; it = std::next(it)) { auto c = it->first; auto n = it->second; std::string ct(1, c); s.push_back(ct); children(n, ct); } return s; } int main() { using namespace std; auto tree = eertree("eertree"); auto pal = subPalindromes(tree); auto it = pal.cbegin(); auto end = pal.cend(); cout << "["; if (it != end) { cout << it->c_str(); it++; } while (it != end) { cout << ", " << it->c_str(); it++; } cout << "]" << endl; return 0; }
from __future__ import print_function class Node(object): def __init__(self): self.edges = {} self.link = None self.len = 0 class Eertree(object): def __init__(self): self.nodes = [] self.rto = Node() self.rte = Node() self.rto.link = self.rte.link = self.rto; self.rto.len = -1 self.rte.len = 0 self.S = [0] self.maxSufT = self.rte def get_max_suffix_pal(self, startNode, a): u = startNode i = len(self.S) k = u.len while id(u) != id(self.rto) and self.S[i - k - 1] != a: assert id(u) != id(u.link) u = u.link k = u.len return u def add(self, a): Q = self.get_max_suffix_pal(self.maxSufT, a) createANewNode = not a in Q.edges if createANewNode: P = Node() self.nodes.append(P) P.len = Q.len + 2 if P.len == 1: P.link = self.rte else: P.link = self.get_max_suffix_pal(Q.link, a).edges[a] Q.edges[a] = P self.maxSufT = Q.edges[a] self.S.append(a) return createANewNode def get_sub_palindromes(self, nd, nodesToHere, charsToHere, result): for lnkName in nd.edges: nd2 = nd.edges[lnkName] self.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result) if id(nd) != id(self.rto) and id(nd) != id(self.rte): tmp = "".join(charsToHere) if id(nodesToHere[0]) == id(self.rte): assembled = tmp[::-1] + tmp else: assembled = tmp[::-1] + tmp[1:] result.append(assembled) if __name__=="__main__": st = "eertree" print ("Processing string", st) eertree = Eertree() for ch in st: eertree.add(ch) print ("Number of sub-palindromes:", len(eertree.nodes)) result = [] eertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) eertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) print ("Sub-palindromes:", result)
Can you help me rewrite this code in Python instead of C++, keeping it the same logically?
#include <iostream> #include <functional> #include <map> #include <vector> struct Node { int length; std::map<char, int> edges; int suffix; Node(int l) : length(l), suffix(0) { } Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) { } }; constexpr int evenRoot = 0; constexpr int oddRoot = 1; std::vector<Node> eertree(const std::string& s) { std::vector<Node> tree = { Node(0, {}, oddRoot), Node(-1, {}, oddRoot) }; int suffix = oddRoot; int n, k; for (size_t i = 0; i < s.length(); ++i) { char c = s[i]; for (n = suffix; ; n = tree[n].suffix) { k = tree[n].length; int b = i - k - 1; if (b >= 0 && s[b] == c) { break; } } auto it = tree[n].edges.find(c); auto end = tree[n].edges.end(); if (it != end) { suffix = it->second; continue; } suffix = tree.size(); tree.push_back(Node(k + 2)); tree[n].edges[c] = suffix; if (tree[suffix].length == 1) { tree[suffix].suffix = 0; continue; } while (true) { n = tree[n].suffix; int b = i - tree[n].length - 1; if (b >= 0 && s[b] == c) { break; } } tree[suffix].suffix = tree[n].edges[c]; } return tree; } std::vector<std::string> subPalindromes(const std::vector<Node>& tree) { std::vector<std::string> s; std::function<void(int, std::string)> children; children = [&children, &tree, &s](int n, std::string p) { auto it = tree[n].edges.cbegin(); auto end = tree[n].edges.cend(); for (; it != end; it = std::next(it)) { auto c = it->first; auto m = it->second; std::string pl = c + p + c; s.push_back(pl); children(m, pl); } }; children(0, ""); auto it = tree[1].edges.cbegin(); auto end = tree[1].edges.cend(); for (; it != end; it = std::next(it)) { auto c = it->first; auto n = it->second; std::string ct(1, c); s.push_back(ct); children(n, ct); } return s; } int main() { using namespace std; auto tree = eertree("eertree"); auto pal = subPalindromes(tree); auto it = pal.cbegin(); auto end = pal.cend(); cout << "["; if (it != end) { cout << it->c_str(); it++; } while (it != end) { cout << ", " << it->c_str(); it++; } cout << "]" << endl; return 0; }
from __future__ import print_function class Node(object): def __init__(self): self.edges = {} self.link = None self.len = 0 class Eertree(object): def __init__(self): self.nodes = [] self.rto = Node() self.rte = Node() self.rto.link = self.rte.link = self.rto; self.rto.len = -1 self.rte.len = 0 self.S = [0] self.maxSufT = self.rte def get_max_suffix_pal(self, startNode, a): u = startNode i = len(self.S) k = u.len while id(u) != id(self.rto) and self.S[i - k - 1] != a: assert id(u) != id(u.link) u = u.link k = u.len return u def add(self, a): Q = self.get_max_suffix_pal(self.maxSufT, a) createANewNode = not a in Q.edges if createANewNode: P = Node() self.nodes.append(P) P.len = Q.len + 2 if P.len == 1: P.link = self.rte else: P.link = self.get_max_suffix_pal(Q.link, a).edges[a] Q.edges[a] = P self.maxSufT = Q.edges[a] self.S.append(a) return createANewNode def get_sub_palindromes(self, nd, nodesToHere, charsToHere, result): for lnkName in nd.edges: nd2 = nd.edges[lnkName] self.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result) if id(nd) != id(self.rto) and id(nd) != id(self.rte): tmp = "".join(charsToHere) if id(nodesToHere[0]) == id(self.rte): assembled = tmp[::-1] + tmp else: assembled = tmp[::-1] + tmp[1:] result.append(assembled) if __name__=="__main__": st = "eertree" print ("Processing string", st) eertree = Eertree() for ch in st: eertree.add(ch) print ("Number of sub-palindromes:", len(eertree.nodes)) result = [] eertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) eertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) print ("Sub-palindromes:", result)
Convert this C++ block to Python, preserving its control flow and logic.
#include <iostream> #include <functional> #include <map> #include <vector> struct Node { int length; std::map<char, int> edges; int suffix; Node(int l) : length(l), suffix(0) { } Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) { } }; constexpr int evenRoot = 0; constexpr int oddRoot = 1; std::vector<Node> eertree(const std::string& s) { std::vector<Node> tree = { Node(0, {}, oddRoot), Node(-1, {}, oddRoot) }; int suffix = oddRoot; int n, k; for (size_t i = 0; i < s.length(); ++i) { char c = s[i]; for (n = suffix; ; n = tree[n].suffix) { k = tree[n].length; int b = i - k - 1; if (b >= 0 && s[b] == c) { break; } } auto it = tree[n].edges.find(c); auto end = tree[n].edges.end(); if (it != end) { suffix = it->second; continue; } suffix = tree.size(); tree.push_back(Node(k + 2)); tree[n].edges[c] = suffix; if (tree[suffix].length == 1) { tree[suffix].suffix = 0; continue; } while (true) { n = tree[n].suffix; int b = i - tree[n].length - 1; if (b >= 0 && s[b] == c) { break; } } tree[suffix].suffix = tree[n].edges[c]; } return tree; } std::vector<std::string> subPalindromes(const std::vector<Node>& tree) { std::vector<std::string> s; std::function<void(int, std::string)> children; children = [&children, &tree, &s](int n, std::string p) { auto it = tree[n].edges.cbegin(); auto end = tree[n].edges.cend(); for (; it != end; it = std::next(it)) { auto c = it->first; auto m = it->second; std::string pl = c + p + c; s.push_back(pl); children(m, pl); } }; children(0, ""); auto it = tree[1].edges.cbegin(); auto end = tree[1].edges.cend(); for (; it != end; it = std::next(it)) { auto c = it->first; auto n = it->second; std::string ct(1, c); s.push_back(ct); children(n, ct); } return s; } int main() { using namespace std; auto tree = eertree("eertree"); auto pal = subPalindromes(tree); auto it = pal.cbegin(); auto end = pal.cend(); cout << "["; if (it != end) { cout << it->c_str(); it++; } while (it != end) { cout << ", " << it->c_str(); it++; } cout << "]" << endl; return 0; }
from __future__ import print_function class Node(object): def __init__(self): self.edges = {} self.link = None self.len = 0 class Eertree(object): def __init__(self): self.nodes = [] self.rto = Node() self.rte = Node() self.rto.link = self.rte.link = self.rto; self.rto.len = -1 self.rte.len = 0 self.S = [0] self.maxSufT = self.rte def get_max_suffix_pal(self, startNode, a): u = startNode i = len(self.S) k = u.len while id(u) != id(self.rto) and self.S[i - k - 1] != a: assert id(u) != id(u.link) u = u.link k = u.len return u def add(self, a): Q = self.get_max_suffix_pal(self.maxSufT, a) createANewNode = not a in Q.edges if createANewNode: P = Node() self.nodes.append(P) P.len = Q.len + 2 if P.len == 1: P.link = self.rte else: P.link = self.get_max_suffix_pal(Q.link, a).edges[a] Q.edges[a] = P self.maxSufT = Q.edges[a] self.S.append(a) return createANewNode def get_sub_palindromes(self, nd, nodesToHere, charsToHere, result): for lnkName in nd.edges: nd2 = nd.edges[lnkName] self.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result) if id(nd) != id(self.rto) and id(nd) != id(self.rte): tmp = "".join(charsToHere) if id(nodesToHere[0]) == id(self.rte): assembled = tmp[::-1] + tmp else: assembled = tmp[::-1] + tmp[1:] result.append(assembled) if __name__=="__main__": st = "eertree" print ("Processing string", st) eertree = Eertree() for ch in st: eertree.add(ch) print ("Number of sub-palindromes:", len(eertree.nodes)) result = [] eertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) eertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) print ("Sub-palindromes:", result)