Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Write the same algorithm in Python as shown in this C++ implementation.
#include <cstdint> #include <algorithm> #include <iostream> #include <sstream> #include <gmpxx.h> typedef mpz_class integer; bool is_prime(const integer& n, int reps = 50) { return mpz_probab_prime_p(n.get_mpz_t(), reps); } std::string to_string(const integer& n) { std::ostringstream out; out << n; return out.str(); } bool is_circular_prime(const integer& p) { if (!is_prime(p)) return false; std::string str(to_string(p)); for (size_t i = 0, n = str.size(); i + 1 < n; ++i) { std::rotate(str.begin(), str.begin() + 1, str.end()); integer p2(str, 10); if (p2 < p || !is_prime(p2)) return false; } return true; } integer next_repunit(const integer& n) { integer p = 1; while (p < n) p = 10 * p + 1; return p; } integer repunit(int digits) { std::string str(digits, '1'); integer p(str); return p; } void test_repunit(int digits) { if (is_prime(repunit(digits), 10)) std::cout << "R(" << digits << ") is probably prime\n"; else std::cout << "R(" << digits << ") is not prime\n"; } int main() { integer p = 2; std::cout << "First 19 circular primes:\n"; for (int count = 0; count < 19; ++p) { if (is_circular_prime(p)) { if (count > 0) std::cout << ", "; std::cout << p; ++count; } } std::cout << '\n'; std::cout << "Next 4 circular primes:\n"; p = next_repunit(p); std::string str(to_string(p)); int digits = str.size(); for (int count = 0; count < 4; ) { if (is_prime(p, 15)) { if (count > 0) std::cout << ", "; std::cout << "R(" << digits << ")"; ++count; } p = repunit(++digits); } std::cout << '\n'; test_repunit(5003); test_repunit(9887); test_repunit(15073); test_repunit(25031); test_repunit(35317); test_repunit(49081); return 0; }
import random def is_Prime(n): if n!=int(n): return False n=int(n) if n==0 or n==1 or n==4 or n==6 or n==8 or n==9: return False if n==2 or n==3 or n==5 or n==7: return True s = 0 d = n-1 while d%2==0: d>>=1 s+=1 assert(2**s * d == n-1) def trial_composite(a): if pow(a, d, n) == 1: return False for i in range(s): if pow(a, 2**i * d, n) == n-1: return False return True for i in range(8): a = random.randrange(2, n) if trial_composite(a): return False return True def isPrime(n: int) -> bool: if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True def rotations(n: int)-> set((int,)): a = str(n) return set(int(a[i:] + a[:i]) for i in range(len(a))) def isCircular(n: int) -> bool: return all(isPrime(int(o)) for o in rotations(n)) from itertools import product def main(): result = [2, 3, 5, 7] first = '137' latter = '1379' for i in range(1, 6): s = set(int(''.join(a)) for a in product(first, *((latter,) * i))) while s: a = s.pop() b = rotations(a) if isCircular(a): result.append(min(b)) s -= b result.sort() return result assert [2, 3, 5, 7, 11, 13, 17, 37, 79, 113, 197, 199, 337, 1193, 3779, 11939, 19937, 193939, 199933] == main() repunit = lambda n: int('1' * n) def repmain(n: int) -> list: result = [] i = 2 while len(result) < n: if is_Prime(repunit(i)): result.append(i) i += 1 return result assert [2, 19, 23, 317, 1031] == repmain(5)
Keep all operations the same but rewrite the snippet in Python.
#include <cstdint> #include <algorithm> #include <iostream> #include <sstream> #include <gmpxx.h> typedef mpz_class integer; bool is_prime(const integer& n, int reps = 50) { return mpz_probab_prime_p(n.get_mpz_t(), reps); } std::string to_string(const integer& n) { std::ostringstream out; out << n; return out.str(); } bool is_circular_prime(const integer& p) { if (!is_prime(p)) return false; std::string str(to_string(p)); for (size_t i = 0, n = str.size(); i + 1 < n; ++i) { std::rotate(str.begin(), str.begin() + 1, str.end()); integer p2(str, 10); if (p2 < p || !is_prime(p2)) return false; } return true; } integer next_repunit(const integer& n) { integer p = 1; while (p < n) p = 10 * p + 1; return p; } integer repunit(int digits) { std::string str(digits, '1'); integer p(str); return p; } void test_repunit(int digits) { if (is_prime(repunit(digits), 10)) std::cout << "R(" << digits << ") is probably prime\n"; else std::cout << "R(" << digits << ") is not prime\n"; } int main() { integer p = 2; std::cout << "First 19 circular primes:\n"; for (int count = 0; count < 19; ++p) { if (is_circular_prime(p)) { if (count > 0) std::cout << ", "; std::cout << p; ++count; } } std::cout << '\n'; std::cout << "Next 4 circular primes:\n"; p = next_repunit(p); std::string str(to_string(p)); int digits = str.size(); for (int count = 0; count < 4; ) { if (is_prime(p, 15)) { if (count > 0) std::cout << ", "; std::cout << "R(" << digits << ")"; ++count; } p = repunit(++digits); } std::cout << '\n'; test_repunit(5003); test_repunit(9887); test_repunit(15073); test_repunit(25031); test_repunit(35317); test_repunit(49081); return 0; }
import random def is_Prime(n): if n!=int(n): return False n=int(n) if n==0 or n==1 or n==4 or n==6 or n==8 or n==9: return False if n==2 or n==3 or n==5 or n==7: return True s = 0 d = n-1 while d%2==0: d>>=1 s+=1 assert(2**s * d == n-1) def trial_composite(a): if pow(a, d, n) == 1: return False for i in range(s): if pow(a, 2**i * d, n) == n-1: return False return True for i in range(8): a = random.randrange(2, n) if trial_composite(a): return False return True def isPrime(n: int) -> bool: if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True def rotations(n: int)-> set((int,)): a = str(n) return set(int(a[i:] + a[:i]) for i in range(len(a))) def isCircular(n: int) -> bool: return all(isPrime(int(o)) for o in rotations(n)) from itertools import product def main(): result = [2, 3, 5, 7] first = '137' latter = '1379' for i in range(1, 6): s = set(int(''.join(a)) for a in product(first, *((latter,) * i))) while s: a = s.pop() b = rotations(a) if isCircular(a): result.append(min(b)) s -= b result.sort() return result assert [2, 3, 5, 7, 11, 13, 17, 37, 79, 113, 197, 199, 337, 1193, 3779, 11939, 19937, 193939, 199933] == main() repunit = lambda n: int('1' * n) def repmain(n: int) -> list: result = [] i = 2 while len(result) < n: if is_Prime(repunit(i)): result.append(i) i += 1 return result assert [2, 19, 23, 317, 1031] == repmain(5)
Convert the following code from C++ to Python, ensuring the logic remains intact.
#include "animationwidget.h" #include <QLabel> #include <QTimer> #include <QVBoxLayout> #include <algorithm> AnimationWidget::AnimationWidget(QWidget *parent) : QWidget(parent) { setWindowTitle(tr("Animation")); QFont font("Courier", 24); QLabel* label = new QLabel("Hello World! "); label->setFont(font); QVBoxLayout* layout = new QVBoxLayout(this); layout->addWidget(label); QTimer* timer = new QTimer(this); connect(timer, &QTimer::timeout, this, [label,this]() { QString text = label->text(); std::rotate(text.begin(), text.begin() + (right_ ? text.length() - 1 : 1), text.end()); label->setText(text); }); timer->start(200); } void AnimationWidget::mousePressEvent(QMouseEvent*) { right_ = !right_; }
txt = "Hello, world! " left = True def draw(): global txt background(128) text(txt, 10, height / 2) if frameCount % 10 == 0: if (left): txt = rotate(txt, 1) else: txt = rotate(txt, -1) println(txt) def mouseReleased(): global left left = not left def rotate(text, startIdx): rotated = text[startIdx:] + text[:startIdx] return rotated
Change the programming language of this snippet from C++ to Python without modifying what it does.
#include <algorithm> #include <iostream> #include <iterator> class radix_test { const int bit; public: radix_test(int offset) : bit(offset) {} bool operator()(int value) const { if (bit == 31) return value < 0; else return !(value & (1 << bit)); } }; void lsd_radix_sort(int *first, int *last) { for (int lsb = 0; lsb < 32; ++lsb) { std::stable_partition(first, last, radix_test(lsb)); } } void msd_radix_sort(int *first, int *last, int msb = 31) { if (first != last && msb >= 0) { int *mid = std::partition(first, last, radix_test(msb)); msb--; msd_radix_sort(first, mid, msb); msd_radix_sort(mid, last, msb); } } int main() { int data[] = { 170, 45, 75, -90, -802, 24, 2, 66 }; lsd_radix_sort(data, data + 8); std::copy(data, data + 8, std::ostream_iterator<int>(std::cout, " ")); return 0; }
from math import log def getDigit(num, base, digit_num): return (num // base ** digit_num) % base def makeBlanks(size): return [ [] for i in range(size) ] def split(a_list, base, digit_num): buckets = makeBlanks(base) for num in a_list: buckets[getDigit(num, base, digit_num)].append(num) return buckets def merge(a_list): new_list = [] for sublist in a_list: new_list.extend(sublist) return new_list def maxAbs(a_list): return max(abs(num) for num in a_list) def split_by_sign(a_list): buckets = [[], []] for num in a_list: if num < 0: buckets[0].append(num) else: buckets[1].append(num) return buckets def radixSort(a_list, base): passes = int(round(log(maxAbs(a_list), base)) + 1) new_list = list(a_list) for digit_num in range(passes): new_list = merge(split(new_list, base, digit_num)) return merge(split_by_sign(new_list))
Write a version of this C++ function in Python with identical behavior.
#include <vector> #include <cmath> #include <iostream> #include <algorithm> #include <iterator> void list_comprehension( std::vector<int> & , int ) ; int main( ) { std::vector<int> triangles ; list_comprehension( triangles , 20 ) ; std::copy( triangles.begin( ) , triangles.end( ) , std::ostream_iterator<int>( std::cout , " " ) ) ; std::cout << std::endl ; return 0 ; } void list_comprehension( std::vector<int> & numbers , int upper_border ) { for ( int a = 1 ; a < upper_border ; a++ ) { for ( int b = a + 1 ; b < upper_border ; b++ ) { double c = pow( a * a + b * b , 0.5 ) ; if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) { if ( c == floor( c ) ) { numbers.push_back( a ) ; numbers.push_back( b ) ; numbers.push_back( static_cast<int>( c ) ) ; } } } } }
[(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]
Keep all operations the same but rewrite the snippet in Python.
#include <algorithm> #include <iterator> #include <iostream> template<typename ForwardIterator> void selection_sort(ForwardIterator begin, ForwardIterator end) { for(auto i = begin; i != end; ++i) { std::iter_swap(i, std::min_element(i, end)); } } int main() { int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; selection_sort(std::begin(a), std::end(a)); copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; }
def selection_sort(lst): for i, e in enumerate(lst): mn = min(range(i,len(lst)), key=lst.__getitem__) lst[i], lst[mn] = lst[mn], e return lst
Maintain the same structure and functionality when rewriting this code in Python.
#include <algorithm> #include <iterator> #include <iostream> template<typename ForwardIterator> void selection_sort(ForwardIterator begin, ForwardIterator end) { for(auto i = begin; i != end; ++i) { std::iter_swap(i, std::min_element(i, end)); } } int main() { int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; selection_sort(std::begin(a), std::end(a)); copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; }
def selection_sort(lst): for i, e in enumerate(lst): mn = min(range(i,len(lst)), key=lst.__getitem__) lst[i], lst[mn] = lst[mn], e return lst
Write a version of this C++ function in Python with identical behavior.
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream> int jacobi(int n, int k) { assert(k > 0 && k % 2 == 1); n %= k; int t = 1; while (n != 0) { while (n % 2 == 0) { n /= 2; int r = k % 8; if (r == 3 || r == 5) t = -t; } std::swap(n, k); if (n % 4 == 3 && k % 4 == 3) t = -t; n %= k; } return k == 1 ? t : 0; } void print_table(std::ostream& out, int kmax, int nmax) { out << "n\\k|"; for (int k = 0; k <= kmax; ++k) out << ' ' << std::setw(2) << k; out << "\n----"; for (int k = 0; k <= kmax; ++k) out << "---"; out << '\n'; for (int n = 1; n <= nmax; n += 2) { out << std::setw(2) << n << " |"; for (int k = 0; k <= kmax; ++k) out << ' ' << std::setw(2) << jacobi(k, n); out << '\n'; } } int main() { print_table(std::cout, 20, 21); return 0; }
def jacobi(a, n): if n <= 0: raise ValueError("'n' must be a positive integer.") if n % 2 == 0: raise ValueError("'n' must be odd.") a %= n result = 1 while a != 0: while a % 2 == 0: a /= 2 n_mod_8 = n % 8 if n_mod_8 in (3, 5): result = -result a, n = n, a if a % 4 == 3 and n % 4 == 3: result = -result a %= n if n == 1: return result else: return 0
Generate a Python translation of this C++ snippet without changing its computational steps.
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream> int jacobi(int n, int k) { assert(k > 0 && k % 2 == 1); n %= k; int t = 1; while (n != 0) { while (n % 2 == 0) { n /= 2; int r = k % 8; if (r == 3 || r == 5) t = -t; } std::swap(n, k); if (n % 4 == 3 && k % 4 == 3) t = -t; n %= k; } return k == 1 ? t : 0; } void print_table(std::ostream& out, int kmax, int nmax) { out << "n\\k|"; for (int k = 0; k <= kmax; ++k) out << ' ' << std::setw(2) << k; out << "\n----"; for (int k = 0; k <= kmax; ++k) out << "---"; out << '\n'; for (int n = 1; n <= nmax; n += 2) { out << std::setw(2) << n << " |"; for (int k = 0; k <= kmax; ++k) out << ' ' << std::setw(2) << jacobi(k, n); out << '\n'; } } int main() { print_table(std::cout, 20, 21); return 0; }
def jacobi(a, n): if n <= 0: raise ValueError("'n' must be a positive integer.") if n % 2 == 0: raise ValueError("'n' must be odd.") a %= n result = 1 while a != 0: while a % 2 == 0: a /= 2 n_mod_8 = n % 8 if n_mod_8 in (3, 5): result = -result a, n = n, a if a % 4 == 3 and n % 4 == 3: result = -result a %= n if n == 1: return result else: return 0
Write the same code in Python as shown below in C++.
#include <algorithm> #include <array> #include <cmath> #include <iostream> #include <random> #include <vector> template<typename coordinate_type, size_t dimensions> class point { public: point(std::array<coordinate_type, dimensions> c) : coords_(c) {} point(std::initializer_list<coordinate_type> list) { size_t n = std::min(dimensions, list.size()); std::copy_n(list.begin(), n, coords_.begin()); } coordinate_type get(size_t index) const { return coords_[index]; } double distance(const point& pt) const { double dist = 0; for (size_t i = 0; i < dimensions; ++i) { double d = get(i) - pt.get(i); dist += d * d; } return dist; } private: std::array<coordinate_type, dimensions> coords_; }; template<typename coordinate_type, size_t dimensions> std::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) { out << '('; for (size_t i = 0; i < dimensions; ++i) { if (i > 0) out << ", "; out << pt.get(i); } out << ')'; return out; } template<typename coordinate_type, size_t dimensions> class kdtree { public: typedef point<coordinate_type, dimensions> point_type; private: struct node { node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {} coordinate_type get(size_t index) const { return point_.get(index); } double distance(const point_type& pt) const { return point_.distance(pt); } point_type point_; node* left_; node* right_; }; node* root_ = nullptr; node* best_ = nullptr; double best_dist_ = 0; size_t visited_ = 0; std::vector<node> nodes_; struct node_cmp { node_cmp(size_t index) : index_(index) {} bool operator()(const node& n1, const node& n2) const { return n1.point_.get(index_) < n2.point_.get(index_); } size_t index_; }; node* make_tree(size_t begin, size_t end, size_t index) { if (end <= begin) return nullptr; size_t n = begin + (end - begin)/2; auto i = nodes_.begin(); std::nth_element(i + begin, i + n, i + end, node_cmp(index)); index = (index + 1) % dimensions; nodes_[n].left_ = make_tree(begin, n, index); nodes_[n].right_ = make_tree(n + 1, end, index); return &nodes_[n]; } void nearest(node* root, const point_type& point, size_t index) { if (root == nullptr) return; ++visited_; double d = root->distance(point); if (best_ == nullptr || d < best_dist_) { best_dist_ = d; best_ = root; } if (best_dist_ == 0) return; double dx = root->get(index) - point.get(index); index = (index + 1) % dimensions; nearest(dx > 0 ? root->left_ : root->right_, point, index); if (dx * dx >= best_dist_) return; nearest(dx > 0 ? root->right_ : root->left_, point, index); } public: kdtree(const kdtree&) = delete; kdtree& operator=(const kdtree&) = delete; template<typename iterator> kdtree(iterator begin, iterator end) : nodes_(begin, end) { root_ = make_tree(0, nodes_.size(), 0); } template<typename func> kdtree(func&& f, size_t n) { nodes_.reserve(n); for (size_t i = 0; i < n; ++i) nodes_.push_back(f()); root_ = make_tree(0, nodes_.size(), 0); } bool empty() const { return nodes_.empty(); } size_t visited() const { return visited_; } double distance() const { return std::sqrt(best_dist_); } const point_type& nearest(const point_type& pt) { if (root_ == nullptr) throw std::logic_error("tree is empty"); best_ = nullptr; visited_ = 0; best_dist_ = 0; nearest(root_, pt, 0); return best_->point_; } }; void test_wikipedia() { typedef point<int, 2> point2d; typedef kdtree<int, 2> tree2d; point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } }; tree2d tree(std::begin(points), std::end(points)); point2d n = tree.nearest({ 9, 2 }); std::cout << "Wikipedia example data:\n"; std::cout << "nearest point: " << n << '\n'; std::cout << "distance: " << tree.distance() << '\n'; std::cout << "nodes visited: " << tree.visited() << '\n'; } typedef point<double, 3> point3d; typedef kdtree<double, 3> tree3d; struct random_point_generator { random_point_generator(double min, double max) : engine_(std::random_device()()), distribution_(min, max) {} point3d operator()() { double x = distribution_(engine_); double y = distribution_(engine_); double z = distribution_(engine_); return point3d({x, y, z}); } std::mt19937 engine_; std::uniform_real_distribution<double> distribution_; }; void test_random(size_t count) { random_point_generator rpg(0, 1); tree3d tree(rpg, count); point3d pt(rpg()); point3d n = tree.nearest(pt); std::cout << "Random data (" << count << " points):\n"; std::cout << "point: " << pt << '\n'; std::cout << "nearest point: " << n << '\n'; std::cout << "distance: " << tree.distance() << '\n'; std::cout << "nodes visited: " << tree.visited() << '\n'; } int main() { try { test_wikipedia(); std::cout << '\n'; test_random(1000); std::cout << '\n'; test_random(1000000); } catch (const std::exception& e) { std::cerr << e.what() << '\n'; } return 0; }
from random import seed, random from time import time from operator import itemgetter from collections import namedtuple from math import sqrt from copy import deepcopy def sqd(p1, p2): return sum((c1 - c2) ** 2 for c1, c2 in zip(p1, p2)) class KdNode(object): __slots__ = ("dom_elt", "split", "left", "right") def __init__(self, dom_elt, split, left, right): self.dom_elt = dom_elt self.split = split self.left = left self.right = right class Orthotope(object): __slots__ = ("min", "max") def __init__(self, mi, ma): self.min, self.max = mi, ma class KdTree(object): __slots__ = ("n", "bounds") def __init__(self, pts, bounds): def nk2(split, exset): if not exset: return None exset.sort(key=itemgetter(split)) m = len(exset) // 2 d = exset[m] while m + 1 < len(exset) and exset[m + 1][split] == d[split]: m += 1 d = exset[m] s2 = (split + 1) % len(d) return KdNode(d, split, nk2(s2, exset[:m]), nk2(s2, exset[m + 1:])) self.n = nk2(0, pts) self.bounds = bounds T3 = namedtuple("T3", "nearest dist_sqd nodes_visited") def find_nearest(k, t, p): def nn(kd, target, hr, max_dist_sqd): if kd is None: return T3([0.0] * k, float("inf"), 0) nodes_visited = 1 s = kd.split pivot = kd.dom_elt left_hr = deepcopy(hr) right_hr = deepcopy(hr) left_hr.max[s] = pivot[s] right_hr.min[s] = pivot[s] if target[s] <= pivot[s]: nearer_kd, nearer_hr = kd.left, left_hr further_kd, further_hr = kd.right, right_hr else: nearer_kd, nearer_hr = kd.right, right_hr further_kd, further_hr = kd.left, left_hr n1 = nn(nearer_kd, target, nearer_hr, max_dist_sqd) nearest = n1.nearest dist_sqd = n1.dist_sqd nodes_visited += n1.nodes_visited if dist_sqd < max_dist_sqd: max_dist_sqd = dist_sqd d = (pivot[s] - target[s]) ** 2 if d > max_dist_sqd: return T3(nearest, dist_sqd, nodes_visited) d = sqd(pivot, target) if d < dist_sqd: nearest = pivot dist_sqd = d max_dist_sqd = dist_sqd n2 = nn(further_kd, target, further_hr, max_dist_sqd) nodes_visited += n2.nodes_visited if n2.dist_sqd < dist_sqd: nearest = n2.nearest dist_sqd = n2.dist_sqd return T3(nearest, dist_sqd, nodes_visited) return nn(t.n, p, t.bounds, float("inf")) def show_nearest(k, heading, kd, p): print(heading + ":") print("Point: ", p) n = find_nearest(k, kd, p) print("Nearest neighbor:", n.nearest) print("Distance: ", sqrt(n.dist_sqd)) print("Nodes visited: ", n.nodes_visited, "\n") def random_point(k): return [random() for _ in range(k)] def random_points(k, n): return [random_point(k) for _ in range(n)] if __name__ == "__main__": seed(1) P = lambda *coords: list(coords) kd1 = KdTree([P(2, 3), P(5, 4), P(9, 6), P(4, 7), P(8, 1), P(7, 2)], Orthotope(P(0, 0), P(10, 10))) show_nearest(2, "Wikipedia example data", kd1, P(9, 2)) N = 400000 t0 = time() kd2 = KdTree(random_points(3, N), Orthotope(P(0, 0, 0), P(1, 1, 1))) t1 = time() text = lambda *parts: "".join(map(str, parts)) show_nearest(2, text("k-d tree with ", N, " random 3D points (generation time: ", t1-t0, "s)"), kd2, random_point(3))
Translate this program into Python but keep the logic exactly as in C++.
#include <algorithm> #include <array> #include <cmath> #include <iostream> #include <random> #include <vector> template<typename coordinate_type, size_t dimensions> class point { public: point(std::array<coordinate_type, dimensions> c) : coords_(c) {} point(std::initializer_list<coordinate_type> list) { size_t n = std::min(dimensions, list.size()); std::copy_n(list.begin(), n, coords_.begin()); } coordinate_type get(size_t index) const { return coords_[index]; } double distance(const point& pt) const { double dist = 0; for (size_t i = 0; i < dimensions; ++i) { double d = get(i) - pt.get(i); dist += d * d; } return dist; } private: std::array<coordinate_type, dimensions> coords_; }; template<typename coordinate_type, size_t dimensions> std::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) { out << '('; for (size_t i = 0; i < dimensions; ++i) { if (i > 0) out << ", "; out << pt.get(i); } out << ')'; return out; } template<typename coordinate_type, size_t dimensions> class kdtree { public: typedef point<coordinate_type, dimensions> point_type; private: struct node { node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {} coordinate_type get(size_t index) const { return point_.get(index); } double distance(const point_type& pt) const { return point_.distance(pt); } point_type point_; node* left_; node* right_; }; node* root_ = nullptr; node* best_ = nullptr; double best_dist_ = 0; size_t visited_ = 0; std::vector<node> nodes_; struct node_cmp { node_cmp(size_t index) : index_(index) {} bool operator()(const node& n1, const node& n2) const { return n1.point_.get(index_) < n2.point_.get(index_); } size_t index_; }; node* make_tree(size_t begin, size_t end, size_t index) { if (end <= begin) return nullptr; size_t n = begin + (end - begin)/2; auto i = nodes_.begin(); std::nth_element(i + begin, i + n, i + end, node_cmp(index)); index = (index + 1) % dimensions; nodes_[n].left_ = make_tree(begin, n, index); nodes_[n].right_ = make_tree(n + 1, end, index); return &nodes_[n]; } void nearest(node* root, const point_type& point, size_t index) { if (root == nullptr) return; ++visited_; double d = root->distance(point); if (best_ == nullptr || d < best_dist_) { best_dist_ = d; best_ = root; } if (best_dist_ == 0) return; double dx = root->get(index) - point.get(index); index = (index + 1) % dimensions; nearest(dx > 0 ? root->left_ : root->right_, point, index); if (dx * dx >= best_dist_) return; nearest(dx > 0 ? root->right_ : root->left_, point, index); } public: kdtree(const kdtree&) = delete; kdtree& operator=(const kdtree&) = delete; template<typename iterator> kdtree(iterator begin, iterator end) : nodes_(begin, end) { root_ = make_tree(0, nodes_.size(), 0); } template<typename func> kdtree(func&& f, size_t n) { nodes_.reserve(n); for (size_t i = 0; i < n; ++i) nodes_.push_back(f()); root_ = make_tree(0, nodes_.size(), 0); } bool empty() const { return nodes_.empty(); } size_t visited() const { return visited_; } double distance() const { return std::sqrt(best_dist_); } const point_type& nearest(const point_type& pt) { if (root_ == nullptr) throw std::logic_error("tree is empty"); best_ = nullptr; visited_ = 0; best_dist_ = 0; nearest(root_, pt, 0); return best_->point_; } }; void test_wikipedia() { typedef point<int, 2> point2d; typedef kdtree<int, 2> tree2d; point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } }; tree2d tree(std::begin(points), std::end(points)); point2d n = tree.nearest({ 9, 2 }); std::cout << "Wikipedia example data:\n"; std::cout << "nearest point: " << n << '\n'; std::cout << "distance: " << tree.distance() << '\n'; std::cout << "nodes visited: " << tree.visited() << '\n'; } typedef point<double, 3> point3d; typedef kdtree<double, 3> tree3d; struct random_point_generator { random_point_generator(double min, double max) : engine_(std::random_device()()), distribution_(min, max) {} point3d operator()() { double x = distribution_(engine_); double y = distribution_(engine_); double z = distribution_(engine_); return point3d({x, y, z}); } std::mt19937 engine_; std::uniform_real_distribution<double> distribution_; }; void test_random(size_t count) { random_point_generator rpg(0, 1); tree3d tree(rpg, count); point3d pt(rpg()); point3d n = tree.nearest(pt); std::cout << "Random data (" << count << " points):\n"; std::cout << "point: " << pt << '\n'; std::cout << "nearest point: " << n << '\n'; std::cout << "distance: " << tree.distance() << '\n'; std::cout << "nodes visited: " << tree.visited() << '\n'; } int main() { try { test_wikipedia(); std::cout << '\n'; test_random(1000); std::cout << '\n'; test_random(1000000); } catch (const std::exception& e) { std::cerr << e.what() << '\n'; } return 0; }
from random import seed, random from time import time from operator import itemgetter from collections import namedtuple from math import sqrt from copy import deepcopy def sqd(p1, p2): return sum((c1 - c2) ** 2 for c1, c2 in zip(p1, p2)) class KdNode(object): __slots__ = ("dom_elt", "split", "left", "right") def __init__(self, dom_elt, split, left, right): self.dom_elt = dom_elt self.split = split self.left = left self.right = right class Orthotope(object): __slots__ = ("min", "max") def __init__(self, mi, ma): self.min, self.max = mi, ma class KdTree(object): __slots__ = ("n", "bounds") def __init__(self, pts, bounds): def nk2(split, exset): if not exset: return None exset.sort(key=itemgetter(split)) m = len(exset) // 2 d = exset[m] while m + 1 < len(exset) and exset[m + 1][split] == d[split]: m += 1 d = exset[m] s2 = (split + 1) % len(d) return KdNode(d, split, nk2(s2, exset[:m]), nk2(s2, exset[m + 1:])) self.n = nk2(0, pts) self.bounds = bounds T3 = namedtuple("T3", "nearest dist_sqd nodes_visited") def find_nearest(k, t, p): def nn(kd, target, hr, max_dist_sqd): if kd is None: return T3([0.0] * k, float("inf"), 0) nodes_visited = 1 s = kd.split pivot = kd.dom_elt left_hr = deepcopy(hr) right_hr = deepcopy(hr) left_hr.max[s] = pivot[s] right_hr.min[s] = pivot[s] if target[s] <= pivot[s]: nearer_kd, nearer_hr = kd.left, left_hr further_kd, further_hr = kd.right, right_hr else: nearer_kd, nearer_hr = kd.right, right_hr further_kd, further_hr = kd.left, left_hr n1 = nn(nearer_kd, target, nearer_hr, max_dist_sqd) nearest = n1.nearest dist_sqd = n1.dist_sqd nodes_visited += n1.nodes_visited if dist_sqd < max_dist_sqd: max_dist_sqd = dist_sqd d = (pivot[s] - target[s]) ** 2 if d > max_dist_sqd: return T3(nearest, dist_sqd, nodes_visited) d = sqd(pivot, target) if d < dist_sqd: nearest = pivot dist_sqd = d max_dist_sqd = dist_sqd n2 = nn(further_kd, target, further_hr, max_dist_sqd) nodes_visited += n2.nodes_visited if n2.dist_sqd < dist_sqd: nearest = n2.nearest dist_sqd = n2.dist_sqd return T3(nearest, dist_sqd, nodes_visited) return nn(t.n, p, t.bounds, float("inf")) def show_nearest(k, heading, kd, p): print(heading + ":") print("Point: ", p) n = find_nearest(k, kd, p) print("Nearest neighbor:", n.nearest) print("Distance: ", sqrt(n.dist_sqd)) print("Nodes visited: ", n.nodes_visited, "\n") def random_point(k): return [random() for _ in range(k)] def random_points(k, n): return [random_point(k) for _ in range(n)] if __name__ == "__main__": seed(1) P = lambda *coords: list(coords) kd1 = KdTree([P(2, 3), P(5, 4), P(9, 6), P(4, 7), P(8, 1), P(7, 2)], Orthotope(P(0, 0), P(10, 10))) show_nearest(2, "Wikipedia example data", kd1, P(9, 2)) N = 400000 t0 = time() kd2 = KdTree(random_points(3, N), Orthotope(P(0, 0, 0), P(1, 1, 1))) t1 = time() text = lambda *parts: "".join(map(str, parts)) show_nearest(2, text("k-d tree with ", N, " random 3D points (generation time: ", t1-t0, "s)"), kd2, random_point(3))
Convert this C++ block to Python, preserving its control flow and logic.
#include <iostream> #include <algorithm> void print_square(int i) { std::cout << i*i << " "; } int main() { int ary[]={1,2,3,4,5}; std::for_each(ary,ary+5,print_square); return 0; }
def square(n): return n * n numbers = [1, 3, 5, 7] squares1 = [square(n) for n in numbers] squares2a = map(square, numbers) squares2b = map(lambda x: x*x, numbers) squares3 = [n * n for n in numbers] isquares1 = (n * n for n in numbers) import itertools isquares2 = itertools.imap(square, numbers)
Preserve the algorithm and functionality while converting the code from C++ to Python.
#include <stdexcept> template <typename Self> class singleton { protected: static Self* sentry; public: static Self& instance() { return *sentry; } singleton() { if(sentry) throw std::logic_error("Error: attempt to instantiate a singleton over a pre-existing one!"); sentry = (Self*)this; } virtual ~singleton() { if(sentry == this) sentry = 0; } }; template <typename Self> Self* singleton<Self>::sentry = 0; #include <iostream> #include <string> using namespace std; class controller : public singleton<controller> { public: controller(string const& name) : name(name) { trace("begin"); } ~controller() { trace("end"); } void work() { trace("doing stuff"); } void trace(string const& message) { cout << name << ": " << message << endl; } string name; }; int main() { controller* first = new controller("first"); controller::instance().work(); delete first; controller second("second"); controller::instance().work(); try { controller goner("goner"); controller::instance().work(); } catch(exception const& error) { cout << error.what() << endl; } controller::instance().work(); controller goner("goner"); controller::instance().work(); }
>>> class Borg(object): __state = {} def __init__(self): self.__dict__ = self.__state >>> b1 = Borg() >>> b2 = Borg() >>> b1 is b2 False >>> b1.datum = range(5) >>> b1.datum [0, 1, 2, 3, 4] >>> b2.datum [0, 1, 2, 3, 4] >>> b1.datum is b2.datum True >>>
Generate a Python translation of this C++ snippet without changing its computational steps.
#include <iostream> #include <tuple> union conv { int i; float f; }; float nextUp(float d) { if (isnan(d) || d == -INFINITY || d == INFINITY) return d; if (d == 0.0) return FLT_EPSILON; conv c; c.f = d; c.i++; return c.f; } float nextDown(float d) { if (isnan(d) || d == -INFINITY || d == INFINITY) return d; if (d == 0.0) return -FLT_EPSILON; conv c; c.f = d; c.i--; return c.f; } auto safeAdd(float a, float b) { return std::make_tuple(nextDown(a + b), nextUp(a + b)); } int main() { float a = 1.20f; float b = 0.03f; auto result = safeAdd(a, b); printf("(%f + %f) is in the range (%0.16f, %0.16f)\n", a, b, std::get<0>(result), std::get<1>(result)); return 0; }
>>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) 0.9999999999999999 >>> from math import fsum >>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) 1.0
Can you help me rewrite this code in Python instead of C++, keeping it the same logically?
#include <iostream> #include <string> using namespace std; int main() { string dog = "Benjamin", Dog = "Samba", DOG = "Bernie"; cout << "The three dogs are named " << dog << ", " << Dog << ", and " << DOG << endl; }
>>> dog = 'Benjamin'; Dog = 'Samba'; DOG = 'Bernie' >>> print ('The three dogs are named ',dog,', ',Dog,', and ',DOG) The three dogs are named Benjamin , Samba , and Bernie >>>
Port the following code from C++ to Python with equivalent syntax and logic.
for(int i = 10; i >= 0; --i) std::cout << i << "\n";
for i in xrange(10, -1, -1): print i
Ensure the translated Python code behaves exactly like the original C++ snippet.
#include <fstream> using namespace std; int main() { ofstream file("new.txt"); file << "this is a string"; file.close(); return 0; }
with open(filename, 'w') as f: f.write(data)
Convert this C++ snippet to Python and keep its semantics consistent.
for(int i = 0; i < 5; ++i) { for(int j = 0; j < i; ++j) std::cout.put('*'); std::cout.put('\n'); }
for i in 1..5: for j in 1..i: stdout.write("*") echo("")
Generate an equivalent Python version of this C++ code.
#include <iostream> #include <cstdint> typedef uint64_t integer; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } class palindrome_generator { public: palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1), digit_(digit), even_(false) {} integer next_palindrome() { ++next_; if (next_ == power_ * (digit_ + 1)) { if (even_) power_ *= 10; next_ = digit_ * power_; even_ = !even_; } return next_ * (even_ ? 10 * power_ : power_) + reverse(even_ ? next_ : next_/10); } private: integer power_; integer next_; int digit_; bool even_; }; bool gapful(integer n) { integer m = n; while (m >= 10) m /= 10; return n % (n % 10 + 10 * m) == 0; } template<size_t len> void print(integer (&array)[9][len]) { for (int digit = 1; digit < 10; ++digit) { std::cout << digit << ":"; for (int i = 0; i < len; ++i) std::cout << ' ' << array[digit - 1][i]; std::cout << '\n'; } } int main() { const int n1 = 20, n2 = 15, n3 = 10; const int m1 = 100, m2 = 1000; integer pg1[9][n1]; integer pg2[9][n2]; integer pg3[9][n3]; for (int digit = 1; digit < 10; ++digit) { palindrome_generator pgen(digit); for (int i = 0; i < m2; ) { integer n = pgen.next_palindrome(); if (!gapful(n)) continue; if (i < n1) pg1[digit - 1][i] = n; else if (i < m1 && i >= m1 - n2) pg2[digit - 1][i - (m1 - n2)] = n; else if (i >= m2 - n3) pg3[digit - 1][i - (m2 - n3)] = n; ++i; } } std::cout << "First " << n1 << " palindromic gapful numbers ending in:\n"; print(pg1); std::cout << "\nLast " << n2 << " of first " << m1 << " palindromic gapful numbers ending in:\n"; print(pg2); std::cout << "\nLast " << n3 << " of first " << m2 << " palindromic gapful numbers ending in:\n"; print(pg3); return 0; }
from itertools import count from pprint import pformat import re import heapq def pal_part_gen(odd=True): for i in count(1): fwd = str(i) rev = fwd[::-1][1:] if odd else fwd[::-1] yield int(fwd + rev) def pal_ordered_gen(): yield from heapq.merge(pal_part_gen(odd=True), pal_part_gen(odd=False)) def is_gapful(x): return (x % (int(str(x)[0]) * 10 + (x % 10)) == 0) if __name__ == '__main__': start = 100 for mx, last in [(20, 20), (100, 15), (1_000, 10)]: print(f"\nLast {last} of the first {mx} binned-by-last digit " f"gapful numbers >= {start}") bin = {i: [] for i in range(1, 10)} gen = (i for i in pal_ordered_gen() if i >= start and is_gapful(i)) while any(len(val) < mx for val in bin.values()): g = next(gen) val = bin[g % 10] if len(val) < mx: val.append(g) b = {k:v[-last:] for k, v in bin.items()} txt = pformat(b, width=220) print('', re.sub(r"[{},\[\]]", '', txt))
Can you help me rewrite this code in Python instead of C++, keeping it the same logically?
#include <iostream> #include <cstdint> typedef uint64_t integer; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } class palindrome_generator { public: palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1), digit_(digit), even_(false) {} integer next_palindrome() { ++next_; if (next_ == power_ * (digit_ + 1)) { if (even_) power_ *= 10; next_ = digit_ * power_; even_ = !even_; } return next_ * (even_ ? 10 * power_ : power_) + reverse(even_ ? next_ : next_/10); } private: integer power_; integer next_; int digit_; bool even_; }; bool gapful(integer n) { integer m = n; while (m >= 10) m /= 10; return n % (n % 10 + 10 * m) == 0; } template<size_t len> void print(integer (&array)[9][len]) { for (int digit = 1; digit < 10; ++digit) { std::cout << digit << ":"; for (int i = 0; i < len; ++i) std::cout << ' ' << array[digit - 1][i]; std::cout << '\n'; } } int main() { const int n1 = 20, n2 = 15, n3 = 10; const int m1 = 100, m2 = 1000; integer pg1[9][n1]; integer pg2[9][n2]; integer pg3[9][n3]; for (int digit = 1; digit < 10; ++digit) { palindrome_generator pgen(digit); for (int i = 0; i < m2; ) { integer n = pgen.next_palindrome(); if (!gapful(n)) continue; if (i < n1) pg1[digit - 1][i] = n; else if (i < m1 && i >= m1 - n2) pg2[digit - 1][i - (m1 - n2)] = n; else if (i >= m2 - n3) pg3[digit - 1][i - (m2 - n3)] = n; ++i; } } std::cout << "First " << n1 << " palindromic gapful numbers ending in:\n"; print(pg1); std::cout << "\nLast " << n2 << " of first " << m1 << " palindromic gapful numbers ending in:\n"; print(pg2); std::cout << "\nLast " << n3 << " of first " << m2 << " palindromic gapful numbers ending in:\n"; print(pg3); return 0; }
from itertools import count from pprint import pformat import re import heapq def pal_part_gen(odd=True): for i in count(1): fwd = str(i) rev = fwd[::-1][1:] if odd else fwd[::-1] yield int(fwd + rev) def pal_ordered_gen(): yield from heapq.merge(pal_part_gen(odd=True), pal_part_gen(odd=False)) def is_gapful(x): return (x % (int(str(x)[0]) * 10 + (x % 10)) == 0) if __name__ == '__main__': start = 100 for mx, last in [(20, 20), (100, 15), (1_000, 10)]: print(f"\nLast {last} of the first {mx} binned-by-last digit " f"gapful numbers >= {start}") bin = {i: [] for i in range(1, 10)} gen = (i for i in pal_ordered_gen() if i >= start and is_gapful(i)) while any(len(val) < mx for val in bin.values()): g = next(gen) val = bin[g % 10] if len(val) < mx: val.append(g) b = {k:v[-last:] for k, v in bin.items()} txt = pformat(b, width=220) print('', re.sub(r"[{},\[\]]", '', txt))
Convert the following code from C++ to Python, ensuring the logic remains intact.
#include <iostream> #include <cstdint> typedef uint64_t integer; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } class palindrome_generator { public: palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1), digit_(digit), even_(false) {} integer next_palindrome() { ++next_; if (next_ == power_ * (digit_ + 1)) { if (even_) power_ *= 10; next_ = digit_ * power_; even_ = !even_; } return next_ * (even_ ? 10 * power_ : power_) + reverse(even_ ? next_ : next_/10); } private: integer power_; integer next_; int digit_; bool even_; }; bool gapful(integer n) { integer m = n; while (m >= 10) m /= 10; return n % (n % 10 + 10 * m) == 0; } template<size_t len> void print(integer (&array)[9][len]) { for (int digit = 1; digit < 10; ++digit) { std::cout << digit << ":"; for (int i = 0; i < len; ++i) std::cout << ' ' << array[digit - 1][i]; std::cout << '\n'; } } int main() { const int n1 = 20, n2 = 15, n3 = 10; const int m1 = 100, m2 = 1000; integer pg1[9][n1]; integer pg2[9][n2]; integer pg3[9][n3]; for (int digit = 1; digit < 10; ++digit) { palindrome_generator pgen(digit); for (int i = 0; i < m2; ) { integer n = pgen.next_palindrome(); if (!gapful(n)) continue; if (i < n1) pg1[digit - 1][i] = n; else if (i < m1 && i >= m1 - n2) pg2[digit - 1][i - (m1 - n2)] = n; else if (i >= m2 - n3) pg3[digit - 1][i - (m2 - n3)] = n; ++i; } } std::cout << "First " << n1 << " palindromic gapful numbers ending in:\n"; print(pg1); std::cout << "\nLast " << n2 << " of first " << m1 << " palindromic gapful numbers ending in:\n"; print(pg2); std::cout << "\nLast " << n3 << " of first " << m2 << " palindromic gapful numbers ending in:\n"; print(pg3); return 0; }
from itertools import count from pprint import pformat import re import heapq def pal_part_gen(odd=True): for i in count(1): fwd = str(i) rev = fwd[::-1][1:] if odd else fwd[::-1] yield int(fwd + rev) def pal_ordered_gen(): yield from heapq.merge(pal_part_gen(odd=True), pal_part_gen(odd=False)) def is_gapful(x): return (x % (int(str(x)[0]) * 10 + (x % 10)) == 0) if __name__ == '__main__': start = 100 for mx, last in [(20, 20), (100, 15), (1_000, 10)]: print(f"\nLast {last} of the first {mx} binned-by-last digit " f"gapful numbers >= {start}") bin = {i: [] for i in range(1, 10)} gen = (i for i in pal_ordered_gen() if i >= start and is_gapful(i)) while any(len(val) < mx for val in bin.values()): g = next(gen) val = bin[g % 10] if len(val) < mx: val.append(g) b = {k:v[-last:] for k, v in bin.items()} txt = pformat(b, width=220) print('', re.sub(r"[{},\[\]]", '', txt))
Please provide an equivalent version of this C++ code in Python.
#include <windows.h> #include <string> #include <iostream> const int BMP_SIZE = 612; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( std::string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class sierpinski { public: void draw( int o ) { colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff; colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff; bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 ); bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( "./st.bmp" ); } private: void drawTri( HDC dc, float l, float t, float r, float b, int i ) { float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; if( i ) { drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 ); drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 ); drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 ); } bmp.setPenColor( colors[i % 6] ); MoveToEx( dc, ( int )( l + ww ), ( int )( t + hh ), NULL ); LineTo ( dc, ( int )( l + ww * 3.f ), ( int )( t + hh ) ); LineTo ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) ); LineTo ( dc, ( int )( l + ww ), ( int )( t + hh ) ); } myBitmap bmp; DWORD colors[6]; }; int main(int argc, char* argv[]) { sierpinski s; s.draw( 12 ); return 0; }
import turtle as t def sier(n,length): if n == 0: return for i in range(3): sier(n - 1, length / 2) t.fd(length) t.rt(120)
Port the provided C++ code into Python while preserving the original functionality.
#include <windows.h> #include <string> #include <iostream> const int BMP_SIZE = 612; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( std::string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class sierpinski { public: void draw( int o ) { colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff; colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff; bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 ); bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( "./st.bmp" ); } private: void drawTri( HDC dc, float l, float t, float r, float b, int i ) { float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; if( i ) { drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 ); drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 ); drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 ); } bmp.setPenColor( colors[i % 6] ); MoveToEx( dc, ( int )( l + ww ), ( int )( t + hh ), NULL ); LineTo ( dc, ( int )( l + ww * 3.f ), ( int )( t + hh ) ); LineTo ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) ); LineTo ( dc, ( int )( l + ww ), ( int )( t + hh ) ); } myBitmap bmp; DWORD colors[6]; }; int main(int argc, char* argv[]) { sierpinski s; s.draw( 12 ); return 0; }
import turtle as t def sier(n,length): if n == 0: return for i in range(3): sier(n - 1, length / 2) t.fd(length) t.rt(120)
Translate the given C++ code snippet into Python without altering its behavior.
#include <windows.h> #include <string> #include <iostream> const int BMP_SIZE = 612; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( std::string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class sierpinski { public: void draw( int o ) { colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff; colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff; bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 ); bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( "./st.bmp" ); } private: void drawTri( HDC dc, float l, float t, float r, float b, int i ) { float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; if( i ) { drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 ); drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 ); drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 ); } bmp.setPenColor( colors[i % 6] ); MoveToEx( dc, ( int )( l + ww ), ( int )( t + hh ), NULL ); LineTo ( dc, ( int )( l + ww * 3.f ), ( int )( t + hh ) ); LineTo ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) ); LineTo ( dc, ( int )( l + ww ), ( int )( t + hh ) ); } myBitmap bmp; DWORD colors[6]; }; int main(int argc, char* argv[]) { sierpinski s; s.draw( 12 ); return 0; }
import turtle as t def sier(n,length): if n == 0: return for i in range(3): sier(n - 1, length / 2) t.fd(length) t.rt(120)
Maintain the same structure and functionality when rewriting this code in Python.
#include <iostream> bool is_prime(int n) { if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } int i = 5; while (i * i <= n) { if (n % i == 0) { return false; } i += 2; if (n % i == 0) { return false; } i += 4; } return true; } int main() { const int start = 1; const int stop = 1000; int sum = 0; int count = 0; int sc = 0; for (int p = start; p < stop; p++) { if (is_prime(p)) { count++; sum += p; if (is_prime(sum)) { printf("The sum of %3d primes in [2, %3d] is %5d which is also prime\n", count, p, sum); sc++; } } } printf("There are %d summerized primes in [%d, %d)\n", sc, start, stop); return 0; }
from itertools import accumulate, chain, takewhile def primeSums(): return ( x for x in enumerate( accumulate( chain([(0, 0)], primes()), lambda a, p: (p, p + a[1]) ) ) if isPrime(x[1][1]) ) def main(): for x in takewhile( lambda t: 1000 > t[1][0], primeSums() ): print(f'{x[0]} -> {x[1][1]}') def isPrime(n): if n in (2, 3): return True if 2 > n or 0 == n % 2: return False if 9 > n: return True if 0 == n % 3: return False def p(x): return 0 == n % x or 0 == n % (2 + x) return not any(map(p, range(5, 1 + int(n ** 0.5), 6))) def primes(): n = 2 dct = {} while True: if n in dct: for p in dct[n]: dct.setdefault(n + p, []).append(p) del dct[n] else: yield n dct[n * n] = [n] n = 1 + n if __name__ == '__main__': main()
Ensure the translated Python code behaves exactly like the original C++ snippet.
#include <iostream> bool is_prime(int n) { if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } int i = 5; while (i * i <= n) { if (n % i == 0) { return false; } i += 2; if (n % i == 0) { return false; } i += 4; } return true; } int main() { const int start = 1; const int stop = 1000; int sum = 0; int count = 0; int sc = 0; for (int p = start; p < stop; p++) { if (is_prime(p)) { count++; sum += p; if (is_prime(sum)) { printf("The sum of %3d primes in [2, %3d] is %5d which is also prime\n", count, p, sum); sc++; } } } printf("There are %d summerized primes in [%d, %d)\n", sc, start, stop); return 0; }
from itertools import accumulate, chain, takewhile def primeSums(): return ( x for x in enumerate( accumulate( chain([(0, 0)], primes()), lambda a, p: (p, p + a[1]) ) ) if isPrime(x[1][1]) ) def main(): for x in takewhile( lambda t: 1000 > t[1][0], primeSums() ): print(f'{x[0]} -> {x[1][1]}') def isPrime(n): if n in (2, 3): return True if 2 > n or 0 == n % 2: return False if 9 > n: return True if 0 == n % 3: return False def p(x): return 0 == n % x or 0 == n % (2 + x) return not any(map(p, range(5, 1 + int(n ** 0.5), 6))) def primes(): n = 2 dct = {} while True: if n in dct: for p in dct[n]: dct.setdefault(n + p, []).append(p) del dct[n] else: yield n dct[n * n] = [n] n = 1 + n if __name__ == '__main__': main()
Keep all operations the same but rewrite the snippet in Python.
#include <iostream> #include <vector> #include <set> #include <algorithm> template<typename T> std::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) { std::set<T> resultset; std::vector<T> result; for (auto& list : ll) for (auto& item : list) resultset.insert(item); for (auto& item : resultset) result.push_back(item); std::sort(result.begin(), result.end()); return result; } int main() { std::vector<int> a = {5,1,3,8,9,4,8,7}; std::vector<int> b = {3,5,9,8,4}; std::vector<int> c = {1,3,7,9}; std::vector<std::vector<int>> nums = {a, b, c}; auto csl = common_sorted_list(nums); for (auto n : csl) std::cout << n << " "; std::cout << std::endl; return 0; }
from itertools import chain def main(): print( sorted(nub(concat([ [5, 1, 3, 8, 9, 4, 8, 7], [3, 5, 9, 8, 4], [1, 3, 7, 9] ]))) ) def concat(xs): return list(chain(*xs)) def nub(xs): return list(dict.fromkeys(xs)) if __name__ == '__main__': main()
Ensure the translated Python code behaves exactly like the original C++ snippet.
#include <iostream> #include <vector> #include <set> #include <algorithm> template<typename T> std::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) { std::set<T> resultset; std::vector<T> result; for (auto& list : ll) for (auto& item : list) resultset.insert(item); for (auto& item : resultset) result.push_back(item); std::sort(result.begin(), result.end()); return result; } int main() { std::vector<int> a = {5,1,3,8,9,4,8,7}; std::vector<int> b = {3,5,9,8,4}; std::vector<int> c = {1,3,7,9}; std::vector<std::vector<int>> nums = {a, b, c}; auto csl = common_sorted_list(nums); for (auto n : csl) std::cout << n << " "; std::cout << std::endl; return 0; }
from itertools import chain def main(): print( sorted(nub(concat([ [5, 1, 3, 8, 9, 4, 8, 7], [3, 5, 9, 8, 4], [1, 3, 7, 9] ]))) ) def concat(xs): return list(chain(*xs)) def nub(xs): return list(dict.fromkeys(xs)) if __name__ == '__main__': main()
Write a version of this C++ function in Python with identical behavior.
#include <iostream> #include <vector> #include <set> #include <algorithm> template<typename T> std::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) { std::set<T> resultset; std::vector<T> result; for (auto& list : ll) for (auto& item : list) resultset.insert(item); for (auto& item : resultset) result.push_back(item); std::sort(result.begin(), result.end()); return result; } int main() { std::vector<int> a = {5,1,3,8,9,4,8,7}; std::vector<int> b = {3,5,9,8,4}; std::vector<int> c = {1,3,7,9}; std::vector<std::vector<int>> nums = {a, b, c}; auto csl = common_sorted_list(nums); for (auto n : csl) std::cout << n << " "; std::cout << std::endl; return 0; }
from itertools import chain def main(): print( sorted(nub(concat([ [5, 1, 3, 8, 9, 4, 8, 7], [3, 5, 9, 8, 4], [1, 3, 7, 9] ]))) ) def concat(xs): return list(chain(*xs)) def nub(xs): return list(dict.fromkeys(xs)) if __name__ == '__main__': main()
Generate a Python translation of this C++ snippet without changing its computational steps.
class N{ uint n,i,g,e,l; public: N(uint n): n(n-1),i{},g{},e(1),l(n-1){} bool hasNext(){ g=(1<<n)+e;for(i=l;i<n;++i) g+=1<<i; if (l==2) {l=--n; e=1; return true;} if (e<((1<<(l-1))-1)) {++e; return true;} e=1; --l; return (l>0); } uint next() {return g;} };
def ncsub(seq, s=0): if seq: x = seq[:1] xs = seq[1:] p2 = s % 2 p1 = not p2 return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + p2) else: return [[]] if s >= 3 else []
Keep all operations the same but rewrite the snippet in Python.
#include <windows.h> #include <string> using namespace std; class myBitmap { public: myBitmap() : pen( NULL ) {} ~myBitmap() { DeleteObject( pen ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; clear(); return true; } void clear() { ZeroMemory( pBits, width * height * sizeof( DWORD ) ); } void setPenColor( DWORD clr ) { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, 1, clr ); SelectObject( hdc, pen ); } void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD* dwpBits; DWORD wb; HANDLE file; GetObject( bmp, sizeof( bitmap ), &bitmap ); dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() { return hdc; } int getWidth() { return width; } int getHeight() { return height; } private: HBITMAP bmp; HDC hdc; HPEN pen; void *pBits; int width, height; }; class fiboFractal { public: fiboFractal( int l ) { bmp.create( 600, 440 ); bmp.setPenColor( 0x00ff00 ); createWord( l ); createFractal(); bmp.saveBitmap( "path_to_save_bitmap" ); } private: void createWord( int l ) { string a = "1", b = "0", c; l -= 2; while( l-- ) { c = b + a; a = b; b = c; } fWord = c; } void createFractal() { int n = 1, px = 10, dir, py = 420, len = 1, x = 0, y = -len, goingTo = 0; HDC dc = bmp.getDC(); MoveToEx( dc, px, py, NULL ); for( string::iterator si = fWord.begin(); si != fWord.end(); si++ ) { px += x; py += y; LineTo( dc, px, py ); if( !( *si - 48 ) ) { if( n & 1 ) dir = 1; else dir = 0; switch( goingTo ) { case 0: y = 0; if( dir ){ x = len; goingTo = 1; } else { x = -len; goingTo = 3; } break; case 1: x = 0; if( dir ) { y = len; goingTo = 2; } else { y = -len; goingTo = 0; } break; case 2: y = 0; if( dir ) { x = -len; goingTo = 3; } else { x = len; goingTo = 1; } break; case 3: x = 0; if( dir ) { y = -len; goingTo = 0; } else { y = len; goingTo = 2; } } } n++; } } string fWord; myBitmap bmp; }; int main( int argc, char* argv[] ) { fiboFractal ff( 23 ); return system( "pause" ); }
from functools import wraps from turtle import * def memoize(obj): cache = obj.cache = {} @wraps(obj) def memoizer(*args, **kwargs): key = str(args) + str(kwargs) if key not in cache: cache[key] = obj(*args, **kwargs) return cache[key] return memoizer @memoize def fibonacci_word(n): assert n > 0 if n == 1: return "1" if n == 2: return "0" return fibonacci_word(n - 1) + fibonacci_word(n - 2) def draw_fractal(word, step): for i, c in enumerate(word, 1): forward(step) if c == "0": if i % 2 == 0: left(90) else: right(90) def main(): n = 25 step = 1 width = 1050 height = 1050 w = fibonacci_word(n) setup(width=width, height=height) speed(0) setheading(90) left(90) penup() forward(500) right(90) backward(500) pendown() tracer(10000) hideturtle() draw_fractal(w, step) getscreen().getcanvas().postscript(file="fibonacci_word_fractal.eps") exitonclick() if __name__ == '__main__': main()
Preserve the algorithm and functionality while converting the code from C++ to Python.
#include <cstdint> #include <iostream> #include <string> #include <primesieve.hpp> void print_twin_prime_count(long long limit) { std::cout << "Number of twin prime pairs less than " << limit << " is " << (limit > 0 ? primesieve::count_twins(0, limit - 1) : 0) << '\n'; } int main(int argc, char** argv) { std::cout.imbue(std::locale("")); if (argc > 1) { for (int i = 1; i < argc; ++i) { try { print_twin_prime_count(std::stoll(argv[i])); } catch (const std::exception& ex) { std::cerr << "Cannot parse limit from '" << argv[i] << "'\n"; } } } else { uint64_t limit = 10; for (int power = 1; power < 12; ++power, limit *= 10) print_twin_prime_count(limit); } return 0; }
primes = [2, 3, 5, 7, 11, 13, 17, 19] def count_twin_primes(limit: int) -> int: global primes if limit > primes[-1]: ram_limit = primes[-1] + 90000000 - len(primes) reasonable_limit = min(limit, primes[-1] ** 2, ram_limit) - 1 while reasonable_limit < limit: ram_limit = primes[-1] + 90000000 - len(primes) if ram_limit > primes[-1]: reasonable_limit = min(limit, primes[-1] ** 2, ram_limit) else: reasonable_limit = min(limit, primes[-1] ** 2) sieve = list({x for prime in primes for x in range(primes[-1] + prime - (primes[-1] % prime), reasonable_limit, prime)}) primes += [x - 1 for i, x in enumerate(sieve) if i and x - 1 != sieve[i - 1] and x - 1 < limit] count = len([(x, y) for (x, y) in zip(primes, primes[1:]) if x + 2 == y]) return count def test(limit: int): count = count_twin_primes(limit) print(f"Number of twin prime pairs less than {limit} is {count}\n") test(10) test(100) test(1000) test(10000) test(100000) test(1000000) test(10000000) test(100000000)
Write a version of this C++ function in Python with identical behavior.
class fifteenSolver{ const int Nr[16]{3,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3}, Nc[16]{3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2}; int n{},_n{}, N0[100]{},N3[100]{},N4[100]{}; unsigned long N2[100]{}; const bool fY(){ if (N4[n]<_n) return fN(); if (N2[n]==0x123456789abcdef0) {std::cout<<"Solution found in "<<n<<" moves :"; for (int g{1};g<=n;++g) std::cout<<(char)N3[g]; std::cout<<std::endl; return true;}; if (N4[n]==_n) return fN(); else return false; } const bool fN(){ if (N3[n]!='u' && N0[n]/4<3){fI(); ++n; if (fY()) return true; --n;} if (N3[n]!='d' && N0[n]/4>0){fG(); ++n; if (fY()) return true; --n;} if (N3[n]!='l' && N0[n]%4<3){fE(); ++n; if (fY()) return true; --n;} if (N3[n]!='r' && N0[n]%4>0){fL(); ++n; if (fY()) return true; --n;} return false; } void fI(){ const int g = (11-N0[n])*4; const unsigned long a = N2[n]&((unsigned long)15<<g); N0[n+1]=N0[n]+4; N2[n+1]=N2[n]-a+(a<<16); N3[n+1]='d'; N4[n+1]=N4[n]+(Nr[a>>g]<=N0[n]/4?0:1); } void fG(){ const int g = (19-N0[n])*4; const unsigned long a = N2[n]&((unsigned long)15<<g); N0[n+1]=N0[n]-4; N2[n+1]=N2[n]-a+(a>>16); N3[n+1]='u'; N4[n+1]=N4[n]+(Nr[a>>g]>=N0[n]/4?0:1); } void fE(){ const int g = (14-N0[n])*4; const unsigned long a = N2[n]&((unsigned long)15<<g); N0[n+1]=N0[n]+1; N2[n+1]=N2[n]-a+(a<<4); N3[n+1]='r'; N4[n+1]=N4[n]+(Nc[a>>g]<=N0[n]%4?0:1); } void fL(){ const int g = (16-N0[n])*4; const unsigned long a = N2[n]&((unsigned long)15<<g); N0[n+1]=N0[n]-1; N2[n+1]=N2[n]-a+(a>>4); N3[n+1]='l'; N4[n+1]=N4[n]+(Nc[a>>g]>=N0[n]%4?0:1); } public: fifteenSolver(int n, unsigned long g){N0[0]=n; N2[0]=g;} void Solve(){for(;not fY();++_n);} };
import random class IDAStar: def __init__(self, h, neighbours): self.h = h self.neighbours = neighbours self.FOUND = object() def solve(self, root, is_goal, max_cost=None): self.is_goal = is_goal self.path = [root] self.is_in_path = {root} self.path_descrs = [] self.nodes_evaluated = 0 bound = self.h(root) while True: t = self._search(0, bound) if t is self.FOUND: return self.path, self.path_descrs, bound, self.nodes_evaluated if t is None: return None bound = t def _search(self, g, bound): self.nodes_evaluated += 1 node = self.path[-1] f = g + self.h(node) if f > bound: return f if self.is_goal(node): return self.FOUND m = None for cost, n, descr in self.neighbours(node): if n in self.is_in_path: continue self.path.append(n) self.is_in_path.add(n) self.path_descrs.append(descr) t = self._search(g + cost, bound) if t == self.FOUND: return self.FOUND if m is None or (t is not None and t < m): m = t self.path.pop() self.path_descrs.pop() self.is_in_path.remove(n) return m def slide_solved_state(n): return tuple(i % (n*n) for i in range(1, n*n+1)) def slide_randomize(p, neighbours): for _ in range(len(p) ** 2): _, p, _ = random.choice(list(neighbours(p))) return p def slide_neighbours(n): movelist = [] for gap in range(n*n): x, y = gap % n, gap // n moves = [] if x > 0: moves.append(-1) if x < n-1: moves.append(+1) if y > 0: moves.append(-n) if y < n-1: moves.append(+n) movelist.append(moves) def neighbours(p): gap = p.index(0) l = list(p) for m in movelist[gap]: l[gap] = l[gap + m] l[gap + m] = 0 yield (1, tuple(l), (l[gap], m)) l[gap + m] = l[gap] l[gap] = 0 return neighbours def slide_print(p): n = int(round(len(p) ** 0.5)) l = len(str(n*n)) for i in range(0, len(p), n): print(" ".join("{:>{}}".format(x, l) for x in p[i:i+n])) def encode_cfg(cfg, n): r = 0 b = n.bit_length() for i in range(len(cfg)): r |= cfg[i] << (b*i) return r def gen_wd_table(n): goal = [[0] * i + [n] + [0] * (n - 1 - i) for i in range(n)] goal[-1][-1] = n - 1 goal = tuple(sum(goal, [])) table = {} to_visit = [(goal, 0, n-1)] while to_visit: cfg, cost, e = to_visit.pop(0) enccfg = encode_cfg(cfg, n) if enccfg in table: continue table[enccfg] = cost for d in [-1, 1]: if 0 <= e + d < n: for c in range(n): if cfg[n*(e+d) + c] > 0: ncfg = list(cfg) ncfg[n*(e+d) + c] -= 1 ncfg[n*e + c] += 1 to_visit.append((tuple(ncfg), cost + 1, e+d)) return table def slide_wd(n, goal): wd = gen_wd_table(n) goals = {i : goal.index(i) for i in goal} b = n.bit_length() def h(p): ht = 0 vt = 0 d = 0 for i, c in enumerate(p): if c == 0: continue g = goals[c] xi, yi = i % n, i // n xg, yg = g % n, g // n ht += 1 << (b*(n*yi+yg)) vt += 1 << (b*(n*xi+xg)) if yg == yi: for k in range(i + 1, i - i%n + n): if p[k] and goals[p[k]] // n == yi and goals[p[k]] < g: d += 2 if xg == xi: for k in range(i + n, n * n, n): if p[k] and goals[p[k]] % n == xi and goals[p[k]] < g: d += 2 d += wd[ht] + wd[vt] return d return h if __name__ == "__main__": solved_state = slide_solved_state(4) neighbours = slide_neighbours(4) is_goal = lambda p: p == solved_state tests = [ (15, 14, 1, 6, 9, 11, 4, 12, 0, 10, 7, 3, 13, 8, 5, 2), ] slide_solver = IDAStar(slide_wd(4, solved_state), neighbours) for p in tests: path, moves, cost, num_eval = slide_solver.solve(p, is_goal, 80) slide_print(p) print(", ".join({-1: "Left", 1: "Right", -4: "Up", 4: "Down"}[move[1]] for move in moves)) print(cost, num_eval)
Produce a functionally identical Python code for the snippet given in C++.
#include <complex> #include <cmath> #include <iostream> double const pi = 4 * std::atan(1); int main() { for (int n = 2; n <= 10; ++n) { std::cout << n << ": "; for (int k = 0; k < n; ++k) std::cout << std::polar(1, 2*pi*k/n) << " "; std::cout << std::endl; } }
import cmath class Complex(complex): def __repr__(self): rp = '%7.5f' % self.real if not self.pureImag() else '' ip = '%7.5fj' % self.imag if not self.pureReal() else '' conj = '' if ( self.pureImag() or self.pureReal() or self.imag < 0.0 ) else '+' return '0.0' if ( self.pureImag() and self.pureReal() ) else rp + conj + ip def pureImag(self): return abs(self.real) < 0.000005 def pureReal(self): return abs(self.imag) < 0.000005 def croots(n): if n <= 0: return None return (Complex(cmath.rect(1, 2 * k * cmath.pi / n)) for k in range(n)) for nr in range(2, 11): print(nr, list(croots(nr)))
Rewrite the snippet below in Python so it works the same as the original C++ code.
#include <iostream> #include <sstream> typedef long long bigInt; using namespace std; class number { public: number() { s = "0"; neg = false; } number( bigInt a ) { set( a ); } number( string a ) { set( a ); } void set( bigInt a ) { neg = false; if( a < 0 ) { a = -a; neg = true; } ostringstream o; o << a; s = o.str(); clearStr(); } void set( string a ) { neg = false; s = a; if( s.length() > 1 && s[0] == '-' ) { neg = true; } clearStr(); } number operator * ( const number& b ) { return this->mul( b ); } number& operator *= ( const number& b ) { *this = *this * b; return *this; } number& operator = ( const number& b ) { s = b.s; return *this; } friend ostream& operator << ( ostream& out, const number& a ) { if( a.neg ) out << "-"; out << a.s; return out; } friend istream& operator >> ( istream& in, number& a ){ string b; in >> b; a.set( b ); return in; } private: number mul( const number& b ) { number a; bool neg = false; string r, bs = b.s; r.resize( 2 * max( b.s.length(), s.length() ), '0' ); int xx, ss, rr, t, c, stp = 0; string::reverse_iterator xi = bs.rbegin(), si, ri; for( ; xi != bs.rend(); xi++ ) { c = 0; ri = r.rbegin() + stp; for( si = s.rbegin(); si != s.rend(); si++ ) { xx = ( *xi ) - 48; ss = ( *si ) - 48; rr = ( *ri ) - 48; ss = ss * xx + rr + c; t = ss % 10; c = ( ss - t ) / 10; ( *ri++ ) = t + 48; } if( c > 0 ) ( *ri ) = c + 48; stp++; } trimLeft( r ); t = b.neg ? 1 : 0; t += neg ? 1 : 0; if( t & 1 ) a.s = "-" + r; else a.s = r; return a; } void trimLeft( string& r ) { if( r.length() < 2 ) return; for( string::iterator x = r.begin(); x != ( r.end() - 1 ); ) { if( ( *x ) != '0' ) return; x = r.erase( x ); } } void clearStr() { for( string::iterator x = s.begin(); x != s.end(); ) { if( ( *x ) < '0' || ( *x ) > '9' ) x = s.erase( x ); else x++; } } string s; bool neg; }; int main( int argc, char* argv[] ) { number a, b; a.set( "18446744073709551616" ); b.set( "18446744073709551616" ); cout << a * b << endl << endl; cout << "Factor 1 = "; cin >> a; cout << "Factor 2 = "; cin >> b; cout << "Product: = " << a * b << endl << endl; return system( "pause" ); }
print 2**64*2**64
Port the provided C++ code into Python while preserving the original functionality.
#include <iomanip> #include <iostream> #include <tuple> std::tuple<uint64_t, uint64_t> solvePell(int n) { int x = (int)sqrt(n); if (x * x == n) { return std::make_pair(1, 0); } int y = x; int z = 1; int r = 2 * x; std::tuple<uint64_t, uint64_t> e = std::make_pair(1, 0); std::tuple<uint64_t, uint64_t> f = std::make_pair(0, 1); uint64_t a = 0; uint64_t b = 0; while (true) { y = r * z - y; z = (n - y * y) / z; r = (x + y) / z; e = std::make_pair(std::get<1>(e), r * std::get<1>(e) + std::get<0>(e)); f = std::make_pair(std::get<1>(f), r * std::get<1>(f) + std::get<0>(f)); a = std::get<1>(e) + x * std::get<1>(f); b = std::get<1>(f); if (a * a - n * b * b == 1) { break; } } return std::make_pair(a, b); } void test(int n) { auto r = solvePell(n); std::cout << "x^2 - " << std::setw(3) << n << " * y^2 = 1 for x = " << std::setw(21) << std::get<0>(r) << " and y = " << std::setw(21) << std::get<1>(r) << '\n'; } int main() { test(61); test(109); test(181); test(277); return 0; }
import math def solvePell(n): x = int(math.sqrt(n)) y, z, r = x, 1, x << 1 e1, e2 = 1, 0 f1, f2 = 0, 1 while True: y = r * z - y z = (n - y * y) // z r = (x + y) // z e1, e2 = e2, e1 + e2 * r f1, f2 = f2, f1 + f2 * r a, b = f2 * x + e2, f2 if a * a - n * b * b == 1: return a, b for n in [61, 109, 181, 277]: x, y = solvePell(n) print("x^2 - %3d * y^2 = 1 for x = %27d and y = %25d" % (n, x, y))
Write the same code in Python as shown below in C++.
#include <iostream> #include <string> #include <algorithm> #include <cstdlib> bool contains_duplicates(std::string s) { std::sort(s.begin(), s.end()); return std::adjacent_find(s.begin(), s.end()) != s.end(); } void game() { typedef std::string::size_type index; std::string symbols = "0123456789"; unsigned int const selection_length = 4; std::random_shuffle(symbols.begin(), symbols.end()); std::string selection = symbols.substr(0, selection_length); std::string guess; while (std::cout << "Your guess? ", std::getline(std::cin, guess)) { if (guess.length() != selection_length || guess.find_first_not_of(symbols) != std::string::npos || contains_duplicates(guess)) { std::cout << guess << " is not a valid guess!"; continue; } unsigned int bulls = 0; unsigned int cows = 0; for (index i = 0; i != selection_length; ++i) { index pos = selection.find(guess[i]); if (pos == i) ++bulls; else if (pos != std::string::npos) ++cows; } std::cout << bulls << " bulls, " << cows << " cows.\n"; if (bulls == selection_length) { std::cout << "Congratulations! You have won!\n"; return; } } std::cerr << "Oops! Something went wrong with input, or you've entered end-of-file!\nExiting ...\n"; std::exit(EXIT_FAILURE); } int main() { std::cout << "Welcome to bulls and cows!\nDo you want to play? "; std::string answer; while (true) { while (true) { if (!std::getline(std::cin, answer)) { std::cout << "I can't get an answer. Exiting.\n"; return EXIT_FAILURE; } if (answer == "yes" || answer == "Yes" || answer == "y" || answer == "Y") break; if (answer == "no" || answer == "No" || answer == "n" || answer == "N") { std::cout << "Ok. Goodbye.\n"; return EXIT_SUCCESS; } std::cout << "Please answer yes or no: "; } game(); std::cout << "Another game? "; } }
import random digits = '123456789' size = 4 chosen = ''.join(random.sample(digits,size)) print % (size, size) guesses = 0 while True: guesses += 1 while True: guess = raw_input('\nNext guess [%i]: ' % guesses).strip() if len(guess) == size and \ all(char in digits for char in guess) \ and len(set(guess)) == size: break print "Problem, try again. You need to enter %i unique digits from 1 to 9" % size if guess == chosen: print '\nCongratulations you guessed correctly in',guesses,'attempts' break bulls = cows = 0 for i in range(size): if guess[i] == chosen[i]: bulls += 1 elif guess[i] in chosen: cows += 1 print ' %i Bulls\n %i Cows' % (bulls, cows)
Write the same code in Python as shown below in C++.
#include <algorithm> #include <iostream> #include <iterator> template <typename RandomAccessIterator> void bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) { bool swapped = true; while (begin != end-- && swapped) { swapped = false; for (auto i = begin; i != end; ++i) { if (*(i + 1) < *i) { std::iter_swap(i, i + 1); swapped = true; } } } } int main() { int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; bubble_sort(std::begin(a), std::end(a)); copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; }
def bubble_sort(seq): changed = True while changed: changed = False for i in range(len(seq) - 1): if seq[i] > seq[i+1]: seq[i], seq[i+1] = seq[i+1], seq[i] changed = True return seq if __name__ == "__main__": from random import shuffle testset = [_ for _ in range(100)] testcase = testset.copy() shuffle(testcase) assert testcase != testset bubble_sort(testcase) assert testcase == testset
Please provide an equivalent version of this C++ code in Python.
#include <cmath> #include <iomanip> #include <iostream> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) ++total; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) ++count; total *= count; } if (n > 1) total *= 2; return total; } unsigned int divisor_product(unsigned int n) { return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0)); } int main() { const unsigned int limit = 50; std::cout << "Product of divisors for the first " << limit << " positive integers:\n"; for (unsigned int n = 1; n <= limit; ++n) { std::cout << std::setw(11) << divisor_product(n); if (n % 5 == 0) std::cout << '\n'; } }
def product_of_divisors(n): assert(isinstance(n, int) and 0 < n) ans = i = j = 1 while i*i <= n: if 0 == n%i: ans *= i j = n//i if j != i: ans *= j i += 1 return ans if __name__ == "__main__": print([product_of_divisors(n) for n in range(1,51)])
Port the provided C++ code into Python while preserving the original functionality.
#include <cmath> #include <iomanip> #include <iostream> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) ++total; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) ++count; total *= count; } if (n > 1) total *= 2; return total; } unsigned int divisor_product(unsigned int n) { return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0)); } int main() { const unsigned int limit = 50; std::cout << "Product of divisors for the first " << limit << " positive integers:\n"; for (unsigned int n = 1; n <= limit; ++n) { std::cout << std::setw(11) << divisor_product(n); if (n % 5 == 0) std::cout << '\n'; } }
def product_of_divisors(n): assert(isinstance(n, int) and 0 < n) ans = i = j = 1 while i*i <= n: if 0 == n%i: ans *= i j = n//i if j != i: ans *= j i += 1 return ans if __name__ == "__main__": print([product_of_divisors(n) for n in range(1,51)])
Port the following code from C++ to Python with equivalent syntax and logic.
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { string line; ifstream input ( "input.txt" ); ofstream output ("output.txt"); if (output.is_open()) { if (input.is_open()){ while (getline (input,line)) { output << line << endl; } input.close(); } else { cout << "input.txt cannot be opened!\n"; } output.close(); } else { cout << "output.txt cannot be written to!\n"; } return 0; }
import shutil shutil.copyfile('input.txt', 'output.txt')
Generate a Python translation of this C++ snippet without changing its computational steps.
#include <iostream> int main() { int a, b; std::cin >> a >> b; std::cout << "a+b = " << a+b << "\n"; std::cout << "a-b = " << a-b << "\n"; std::cout << "a*b = " << a*b << "\n"; std::cout << "a/b = " << a/b << ", remainder " << a%b << "\n"; return 0; }
x = int(raw_input("Number 1: ")) y = int(raw_input("Number 2: ")) print "Sum: %d" % (x + y) print "Difference: %d" % (x - y) print "Product: %d" % (x * y) print "Quotient: %d" % (x / y) print "Remainder: %d" % (x % y) print "Quotient: %d with Remainder: %d" % divmod(x, y) print "Power: %d" % x**y raw_input( )
Produce a functionally identical Python code for the snippet given in C++.
#include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/io.hpp> int main() { using namespace boost::numeric::ublas; matrix<double> m(3,3); for(int i=0; i!=m.size1(); ++i) for(int j=0; j!=m.size2(); ++j) m(i,j)=3*i+j; std::cout << trans(m) << std::endl; }
m=((1, 1, 1, 1), (2, 4, 8, 16), (3, 9, 27, 81), (4, 16, 64, 256), (5, 25,125, 625)) print(zip(*m))
Port the following code from C++ to Python with equivalent syntax and logic.
#include <iostream> #include <tr1/memory> using std::tr1::shared_ptr; using std::tr1::enable_shared_from_this; struct Arg { virtual int run() = 0; virtual ~Arg() { }; }; int A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>); class B : public Arg, public enable_shared_from_this<B> { private: int k; const shared_ptr<Arg> x1, x2, x3, x4; public: B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3, shared_ptr<Arg> _x4) : k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { } int run() { return A(--k, shared_from_this(), x1, x2, x3, x4); } }; class Const : public Arg { private: const int x; public: Const(int _x) : x(_x) { } int run () { return x; } }; int A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3, shared_ptr<Arg> x4, shared_ptr<Arg> x5) { if (k <= 0) return x4->run() + x5->run(); else { shared_ptr<Arg> b(new B(k, x1, x2, x3, x4)); return b->run(); } } int main() { std::cout << A(10, shared_ptr<Arg>(new Const(1)), shared_ptr<Arg>(new Const(-1)), shared_ptr<Arg>(new Const(-1)), shared_ptr<Arg>(new Const(1)), shared_ptr<Arg>(new Const(0))) << std::endl; return 0; }
import sys sys.setrecursionlimit(1025) def a(in_k, x1, x2, x3, x4, x5): k = [in_k] def b(): k[0] -= 1 return a(k[0], b, x1, x2, x3, x4) return x4() + x5() if k[0] <= 0 else b() x = lambda i: lambda: i print(a(10, x(1), x(-1), x(-1), x(1), x(0)))
Convert this C++ snippet to Python and keep its semantics consistent.
#include <iostream> bool a(bool in) { std::cout << "a" << std::endl; return in; } bool b(bool in) { std::cout << "b" << std::endl; return in; } void test(bool i, bool j) { std::cout << std::boolalpha << i << " and " << j << " = " << (a(i) && b(j)) << std::endl; std::cout << std::boolalpha << i << " or " << j << " = " << (a(i) || b(j)) << std::endl; } int main() { test(false, false); test(false, true); test(true, false); test(true, true); return 0; }
>>> def a(answer): print(" return answer >>> def b(answer): print(" return answer >>> for i in (False, True): for j in (False, True): print ("\nCalculating: x = a(i) and b(j)") x = a(i) and b(j) print ("Calculating: y = a(i) or b(j)") y = a(i) or b(j) Calculating: x = a(i) and b(j) Calculating: y = a(i) or b(j) Calculating: x = a(i) and b(j) Calculating: y = a(i) or b(j) Calculating: x = a(i) and b(j) Calculating: y = a(i) or b(j) Calculating: x = a(i) and b(j) Calculating: y = a(i) or b(j)
Port the provided C++ code into Python while preserving the original functionality.
#include <iostream> void recurse(unsigned int i) { std::cout<<i<<"\n"; recurse(i+1); } int main() { recurse(0); }
import sys print(sys.getrecursionlimit())
Write the same algorithm in Python as shown in this C++ implementation.
#include <iostream> void recurse(unsigned int i) { std::cout<<i<<"\n"; recurse(i+1); } int main() { recurse(0); }
import sys print(sys.getrecursionlimit())
Maintain the same structure and functionality when rewriting this code in Python.
#include <iostream> void recurse(unsigned int i) { std::cout<<i<<"\n"; recurse(i+1); } int main() { recurse(0); }
import sys print(sys.getrecursionlimit())
Change the following C++ code into Python without altering its purpose.
#include <iomanip> #include <iostream> int mod(int n, int d) { return (d + n % d) % d; } bool is_prime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } void print_carmichael_numbers(int prime1) { for (int h3 = 1; h3 < prime1; ++h3) { for (int d = 1; d < h3 + prime1; ++d) { if (mod((h3 + prime1) * (prime1 - 1), d) != 0 || mod(-prime1 * prime1, h3) != mod(d, h3)) continue; int prime2 = 1 + (prime1 - 1) * (h3 + prime1)/d; if (!is_prime(prime2)) continue; int prime3 = 1 + prime1 * prime2/h3; if (!is_prime(prime3)) continue; if (mod(prime2 * prime3, prime1 - 1) != 1) continue; unsigned int c = prime1 * prime2 * prime3; std::cout << std::setw(2) << prime1 << " x " << std::setw(4) << prime2 << " x " << std::setw(5) << prime3 << " = " << std::setw(10) << c << '\n'; } } } int main() { for (int p = 2; p <= 61; ++p) { if (is_prime(p)) print_carmichael_numbers(p); } return 0; }
class Isprime(): multiples = {2} primes = [2] nmax = 2 def __init__(self, nmax): if nmax > self.nmax: self.check(nmax) def check(self, n): if type(n) == float: if not n.is_integer(): return False n = int(n) multiples = self.multiples if n <= self.nmax: return n not in multiples else: primes, nmax = self.primes, self.nmax newmax = max(nmax*2, n) for p in primes: multiples.update(range(p*((nmax + p + 1) // p), newmax+1, p)) for i in range(nmax+1, newmax+1): if i not in multiples: primes.append(i) multiples.update(range(i*2, newmax+1, i)) self.nmax = newmax return n not in multiples __call__ = check def carmichael(p1): ans = [] if isprime(p1): for h3 in range(2, p1): g = h3 + p1 for d in range(1, g): if (g * (p1 - 1)) % d == 0 and (-p1 * p1) % h3 == d % h3: p2 = 1 + ((p1 - 1)* g // d) if isprime(p2): p3 = 1 + (p1 * p2 // h3) if isprime(p3): if (p2 * p3) % (p1 - 1) == 1: ans += [tuple(sorted((p1, p2, p3)))] return ans isprime = Isprime(2) ans = sorted(sum((carmichael(n) for n in range(62) if isprime(n)), [])) print(',\n'.join(repr(ans[i:i+5])[1:-1] for i in range(0, len(ans)+1, 5)))
Please provide an equivalent version of this C++ code in Python.
#include <windows.h> #include <sstream> #include <tchar.h> using namespace std; const unsigned int BMP_WID = 320, BMP_HEI = 240, WHITE = 16777215, BLACK = 0; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } void* getBits( void ) const { return pBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void* pBits; int width, height, wid; DWORD clr; }; class bmpNoise { public: bmpNoise() { QueryPerformanceFrequency( &_frequency ); _bmp.create( BMP_WID, BMP_HEI ); _frameTime = _fps = 0; _start = getTime(); _frames = 0; } void mainLoop() { float now = getTime(); if( now - _start > 1.0f ) { _fps = static_cast<float>( _frames ) / ( now - _start ); _start = now; _frames = 0; } HDC wdc, dc = _bmp.getDC(); unsigned int* bits = reinterpret_cast<unsigned int*>( _bmp.getBits() ); for( int y = 0; y < BMP_HEI; y++ ) { for( int x = 0; x < BMP_WID; x++ ) { if( rand() % 10 < 5 ) memset( bits, 255, 3 ); else memset( bits, 0, 3 ); bits++; } } ostringstream o; o << _fps; TextOut( dc, 0, 0, o.str().c_str(), o.str().size() ); wdc = GetDC( _hwnd ); BitBlt( wdc, 0, 0, BMP_WID, BMP_HEI, dc, 0, 0, SRCCOPY ); ReleaseDC( _hwnd, wdc ); _frames++; _frameTime = getTime() - now; if( _frameTime > 1.0f ) _frameTime = 1.0f; } void setHWND( HWND hwnd ) { _hwnd = hwnd; } private: float getTime() { LARGE_INTEGER liTime; QueryPerformanceCounter( &liTime ); return liTime.QuadPart / ( float )_frequency.QuadPart; } myBitmap _bmp; HWND _hwnd; float _start, _fps, _frameTime; unsigned int _frames; LARGE_INTEGER _frequency; }; class wnd { public: wnd() { _inst = this; } int wnd::Run( HINSTANCE hInst ) { _hInst = hInst; _hwnd = InitAll(); _noise.setHWND( _hwnd ); ShowWindow( _hwnd, SW_SHOW ); UpdateWindow( _hwnd ); MSG msg; ZeroMemory( &msg, sizeof( msg ) ); while( msg.message != WM_QUIT ) { if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } else { _noise.mainLoop(); } } return UnregisterClass( "_MY_NOISE_", _hInst ); } private: static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_DESTROY: PostQuitMessage( 0 ); break; default: return DefWindowProc( hWnd, msg, wParam, lParam ); } return 0; } HWND InitAll() { WNDCLASSEX wcex; ZeroMemory( &wcex, sizeof( wcex ) ); wcex.cbSize = sizeof( WNDCLASSEX ); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = ( WNDPROC )WndProc; wcex.hInstance = _hInst; wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 ); wcex.lpszClassName = "_MY_NOISE_"; RegisterClassEx( &wcex ); RECT rc = { 0, 0, BMP_WID, BMP_HEI }; AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE ); int w = rc.right - rc.left, h = rc.bottom - rc.top; return CreateWindow( "_MY_NOISE_", ".: Noise image -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL ); } static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; bmpNoise _noise; }; wnd* wnd::_inst = 0; int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { srand( GetTickCount() ); wnd myWnd; return myWnd.Run( hInstance ); }
black = color(0) white = color(255) def setup(): size(320, 240) def draw(): loadPixels() for i in range(len(pixels)): if random(1) < 0.5: pixels[i] = black else: pixels[i] = white updatePixels() fill(0, 128) rect(0, 0, 60, 20) fill(255) text(frameRate, 5, 15)
Produce a functionally identical Python code for the snippet given in C++.
#include <conio.h> #include <iostream> using namespace std; int main() { char ch; _cputs( "Yes or no?" ); do { ch = _getch(); ch = toupper( ch ); } while(ch!='Y'&&ch!='N'); if(ch=='N') { cout << "You said no" << endl; } else { cout << "You said yes" << endl; } return 0; }
try: from msvcrt import getch except ImportError: def getch(): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch print "Press Y or N to continue" while True: char = getch() if char.lower() in ("y", "n"): print char break
Port the following code from C++ to Python with equivalent syntax and logic.
#include <conio.h> #include <iostream> using namespace std; int main() { char ch; _cputs( "Yes or no?" ); do { ch = _getch(); ch = toupper( ch ); } while(ch!='Y'&&ch!='N'); if(ch=='N') { cout << "You said no" << endl; } else { cout << "You said yes" << endl; } return 0; }
try: from msvcrt import getch except ImportError: def getch(): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch print "Press Y or N to continue" while True: char = getch() if char.lower() in ("y", "n"): print char break
Convert the following code from C++ to Python, ensuring the logic remains intact.
#include <iostream> using namespace std ; int divisor_sum( int number ) { int sum = 0 ; for ( int i = 1 ; i < number ; i++ ) if ( number % i == 0 ) sum += i ; return sum; } int main( ) { cout << "Perfect numbers from 1 to 33550337:\n" ; for ( int num = 1 ; num < 33550337 ; num++ ) { if (divisor_sum(num) == num) cout << num << '\n' ; } return 0 ; }
def perf1(n): sum = 0 for i in range(1, n): if n % i == 0: sum += i return sum == n
Can you help me rewrite this code in Python instead of C++, keeping it the same logically?
#include <iostream> using namespace std ; int divisor_sum( int number ) { int sum = 0 ; for ( int i = 1 ; i < number ; i++ ) if ( number % i == 0 ) sum += i ; return sum; } int main( ) { cout << "Perfect numbers from 1 to 33550337:\n" ; for ( int num = 1 ; num < 33550337 ; num++ ) { if (divisor_sum(num) == num) cout << num << '\n' ; } return 0 ; }
def perf1(n): sum = 0 for i in range(1, n): if n % i == 0: sum += i return sum == n
Port the following code from C++ to Python with equivalent syntax and logic.
#include <cassert> #include <cmath> #include <complex> #include <iomanip> #include <iostream> #include <sstream> #include <vector> template <typename scalar_type> class complex_matrix { public: using element_type = std::complex<scalar_type>; complex_matrix(size_t rows, size_t columns) : rows_(rows), columns_(columns), elements_(rows * columns) {} complex_matrix(size_t rows, size_t columns, element_type value) : rows_(rows), columns_(columns), elements_(rows * columns, value) {} complex_matrix(size_t rows, size_t columns, const std::initializer_list<std::initializer_list<element_type>>& values) : rows_(rows), columns_(columns), elements_(rows * columns) { assert(values.size() <= rows_); size_t i = 0; for (const auto& row : values) { assert(row.size() <= columns_); std::copy(begin(row), end(row), &elements_[i]); i += columns_; } } size_t rows() const { return rows_; } size_t columns() const { return columns_; } const element_type& operator()(size_t row, size_t column) const { assert(row < rows_); assert(column < columns_); return elements_[row * columns_ + column]; } element_type& operator()(size_t row, size_t column) { assert(row < rows_); assert(column < columns_); return elements_[row * columns_ + column]; } friend bool operator==(const complex_matrix& a, const complex_matrix& b) { return a.rows_ == b.rows_ && a.columns_ == b.columns_ && a.elements_ == b.elements_; } private: size_t rows_; size_t columns_; std::vector<element_type> elements_; }; template <typename scalar_type> complex_matrix<scalar_type> product(const complex_matrix<scalar_type>& a, const complex_matrix<scalar_type>& b) { assert(a.columns() == b.rows()); size_t arows = a.rows(); size_t bcolumns = b.columns(); size_t n = a.columns(); complex_matrix<scalar_type> c(arows, bcolumns); for (size_t i = 0; i < arows; ++i) { for (size_t j = 0; j < n; ++j) { for (size_t k = 0; k < bcolumns; ++k) c(i, k) += a(i, j) * b(j, k); } } return c; } template <typename scalar_type> complex_matrix<scalar_type> conjugate_transpose(const complex_matrix<scalar_type>& a) { size_t rows = a.rows(), columns = a.columns(); complex_matrix<scalar_type> b(columns, rows); for (size_t i = 0; i < columns; i++) { for (size_t j = 0; j < rows; j++) { b(i, j) = std::conj(a(j, i)); } } return b; } template <typename scalar_type> std::string to_string(const std::complex<scalar_type>& c) { std::ostringstream out; const int precision = 6; out << std::fixed << std::setprecision(precision); out << std::setw(precision + 3) << c.real(); if (c.imag() > 0) out << " + " << std::setw(precision + 2) << c.imag() << 'i'; else if (c.imag() == 0) out << " + " << std::setw(precision + 2) << 0.0 << 'i'; else out << " - " << std::setw(precision + 2) << -c.imag() << 'i'; return out.str(); } template <typename scalar_type> void print(std::ostream& out, const complex_matrix<scalar_type>& a) { size_t rows = a.rows(), columns = a.columns(); for (size_t row = 0; row < rows; ++row) { for (size_t column = 0; column < columns; ++column) { if (column > 0) out << ' '; out << to_string(a(row, column)); } out << '\n'; } } template <typename scalar_type> bool is_hermitian_matrix(const complex_matrix<scalar_type>& matrix) { if (matrix.rows() != matrix.columns()) return false; return matrix == conjugate_transpose(matrix); } template <typename scalar_type> bool is_normal_matrix(const complex_matrix<scalar_type>& matrix) { if (matrix.rows() != matrix.columns()) return false; auto c = conjugate_transpose(matrix); return product(c, matrix) == product(matrix, c); } bool is_equal(const std::complex<double>& a, double b) { constexpr double e = 1e-15; return std::abs(a.imag()) < e && std::abs(a.real() - b) < e; } template <typename scalar_type> bool is_identity_matrix(const complex_matrix<scalar_type>& matrix) { if (matrix.rows() != matrix.columns()) return false; size_t rows = matrix.rows(); for (size_t i = 0; i < rows; ++i) { for (size_t j = 0; j < rows; ++j) { if (!is_equal(matrix(i, j), scalar_type(i == j ? 1 : 0))) return false; } } return true; } template <typename scalar_type> bool is_unitary_matrix(const complex_matrix<scalar_type>& matrix) { if (matrix.rows() != matrix.columns()) return false; auto c = conjugate_transpose(matrix); auto p = product(c, matrix); return is_identity_matrix(p) && p == product(matrix, c); } template <typename scalar_type> void test(const complex_matrix<scalar_type>& matrix) { std::cout << "Matrix:\n"; print(std::cout, matrix); std::cout << "Conjugate transpose:\n"; print(std::cout, conjugate_transpose(matrix)); std::cout << std::boolalpha; std::cout << "Hermitian: " << is_hermitian_matrix(matrix) << '\n'; std::cout << "Normal: " << is_normal_matrix(matrix) << '\n'; std::cout << "Unitary: " << is_unitary_matrix(matrix) << '\n'; } int main() { using matrix = complex_matrix<double>; matrix matrix1(3, 3, {{{2, 0}, {2, 1}, {4, 0}}, {{2, -1}, {3, 0}, {0, 1}}, {{4, 0}, {0, -1}, {1, 0}}}); double n = std::sqrt(0.5); matrix matrix2(3, 3, {{{n, 0}, {n, 0}, {0, 0}}, {{0, -n}, {0, n}, {0, 0}}, {{0, 0}, {0, 0}, {0, 1}}}); matrix matrix3(3, 3, {{{2, 2}, {3, 1}, {-3, 5}}, {{2, -1}, {4, 1}, {0, 0}}, {{7, -5}, {1, -4}, {1, 0}}}); test(matrix1); std::cout << '\n'; test(matrix2); std::cout << '\n'; test(matrix3); return 0; }
def conjugate_transpose(m): return tuple(tuple(n.conjugate() for n in row) for row in zip(*m)) def mmul( ma, mb): return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma) def mi(size): 'Complex Identity matrix' sz = range(size) m = [[0 + 0j for i in sz] for j in sz] for i in range(size): m[i][i] = 1 + 0j return tuple(tuple(row) for row in m) def __allsame(vector): first, rest = vector[0], vector[1:] return all(i == first for i in rest) def __allnearsame(vector, eps=1e-14): first, rest = vector[0], vector[1:] return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps for i in rest) def isequal(matrices, eps=1e-14): 'Check any number of matrices for equality within eps' x = [len(m) for m in matrices] if not __allsame(x): return False y = [len(m[0]) for m in matrices] if not __allsame(y): return False for s in range(x[0]): for t in range(y[0]): if not __allnearsame([m[s][t] for m in matrices], eps): return False return True def ishermitian(m, ct): return isequal([m, ct]) def isnormal(m, ct): return isequal([mmul(m, ct), mmul(ct, m)]) def isunitary(m, ct): mct, ctm = mmul(m, ct), mmul(ct, m) mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0]) ident = mi(mctx) return isequal([mct, ctm, ident]) def printm(comment, m): print(comment) fields = [['%g%+gj' % (f.real, f.imag) for f in row] for row in m] width = max(max(len(f) for f in row) for row in fields) lines = (', '.join('%*s' % (width, f) for f in row) for row in fields) print('\n'.join(lines)) if __name__ == '__main__': for matrix in [ ((( 3.000+0.000j), (+2.000+1.000j)), (( 2.000-1.000j), (+1.000+0.000j))), ((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)), (( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)), (( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))), ((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)), (( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)), (( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]: printm('\nMatrix:', matrix) ct = conjugate_transpose(matrix) printm('Its conjugate transpose:', ct) print('Hermitian? %s.' % ishermitian(matrix, ct)) print('Normal? %s.' % isnormal(matrix, ct)) print('Unitary? %s.' % isunitary(matrix, ct))
Preserve the algorithm and functionality while converting the code from C++ to Python.
#include <cassert> #include <cmath> #include <complex> #include <iomanip> #include <iostream> #include <sstream> #include <vector> template <typename scalar_type> class complex_matrix { public: using element_type = std::complex<scalar_type>; complex_matrix(size_t rows, size_t columns) : rows_(rows), columns_(columns), elements_(rows * columns) {} complex_matrix(size_t rows, size_t columns, element_type value) : rows_(rows), columns_(columns), elements_(rows * columns, value) {} complex_matrix(size_t rows, size_t columns, const std::initializer_list<std::initializer_list<element_type>>& values) : rows_(rows), columns_(columns), elements_(rows * columns) { assert(values.size() <= rows_); size_t i = 0; for (const auto& row : values) { assert(row.size() <= columns_); std::copy(begin(row), end(row), &elements_[i]); i += columns_; } } size_t rows() const { return rows_; } size_t columns() const { return columns_; } const element_type& operator()(size_t row, size_t column) const { assert(row < rows_); assert(column < columns_); return elements_[row * columns_ + column]; } element_type& operator()(size_t row, size_t column) { assert(row < rows_); assert(column < columns_); return elements_[row * columns_ + column]; } friend bool operator==(const complex_matrix& a, const complex_matrix& b) { return a.rows_ == b.rows_ && a.columns_ == b.columns_ && a.elements_ == b.elements_; } private: size_t rows_; size_t columns_; std::vector<element_type> elements_; }; template <typename scalar_type> complex_matrix<scalar_type> product(const complex_matrix<scalar_type>& a, const complex_matrix<scalar_type>& b) { assert(a.columns() == b.rows()); size_t arows = a.rows(); size_t bcolumns = b.columns(); size_t n = a.columns(); complex_matrix<scalar_type> c(arows, bcolumns); for (size_t i = 0; i < arows; ++i) { for (size_t j = 0; j < n; ++j) { for (size_t k = 0; k < bcolumns; ++k) c(i, k) += a(i, j) * b(j, k); } } return c; } template <typename scalar_type> complex_matrix<scalar_type> conjugate_transpose(const complex_matrix<scalar_type>& a) { size_t rows = a.rows(), columns = a.columns(); complex_matrix<scalar_type> b(columns, rows); for (size_t i = 0; i < columns; i++) { for (size_t j = 0; j < rows; j++) { b(i, j) = std::conj(a(j, i)); } } return b; } template <typename scalar_type> std::string to_string(const std::complex<scalar_type>& c) { std::ostringstream out; const int precision = 6; out << std::fixed << std::setprecision(precision); out << std::setw(precision + 3) << c.real(); if (c.imag() > 0) out << " + " << std::setw(precision + 2) << c.imag() << 'i'; else if (c.imag() == 0) out << " + " << std::setw(precision + 2) << 0.0 << 'i'; else out << " - " << std::setw(precision + 2) << -c.imag() << 'i'; return out.str(); } template <typename scalar_type> void print(std::ostream& out, const complex_matrix<scalar_type>& a) { size_t rows = a.rows(), columns = a.columns(); for (size_t row = 0; row < rows; ++row) { for (size_t column = 0; column < columns; ++column) { if (column > 0) out << ' '; out << to_string(a(row, column)); } out << '\n'; } } template <typename scalar_type> bool is_hermitian_matrix(const complex_matrix<scalar_type>& matrix) { if (matrix.rows() != matrix.columns()) return false; return matrix == conjugate_transpose(matrix); } template <typename scalar_type> bool is_normal_matrix(const complex_matrix<scalar_type>& matrix) { if (matrix.rows() != matrix.columns()) return false; auto c = conjugate_transpose(matrix); return product(c, matrix) == product(matrix, c); } bool is_equal(const std::complex<double>& a, double b) { constexpr double e = 1e-15; return std::abs(a.imag()) < e && std::abs(a.real() - b) < e; } template <typename scalar_type> bool is_identity_matrix(const complex_matrix<scalar_type>& matrix) { if (matrix.rows() != matrix.columns()) return false; size_t rows = matrix.rows(); for (size_t i = 0; i < rows; ++i) { for (size_t j = 0; j < rows; ++j) { if (!is_equal(matrix(i, j), scalar_type(i == j ? 1 : 0))) return false; } } return true; } template <typename scalar_type> bool is_unitary_matrix(const complex_matrix<scalar_type>& matrix) { if (matrix.rows() != matrix.columns()) return false; auto c = conjugate_transpose(matrix); auto p = product(c, matrix); return is_identity_matrix(p) && p == product(matrix, c); } template <typename scalar_type> void test(const complex_matrix<scalar_type>& matrix) { std::cout << "Matrix:\n"; print(std::cout, matrix); std::cout << "Conjugate transpose:\n"; print(std::cout, conjugate_transpose(matrix)); std::cout << std::boolalpha; std::cout << "Hermitian: " << is_hermitian_matrix(matrix) << '\n'; std::cout << "Normal: " << is_normal_matrix(matrix) << '\n'; std::cout << "Unitary: " << is_unitary_matrix(matrix) << '\n'; } int main() { using matrix = complex_matrix<double>; matrix matrix1(3, 3, {{{2, 0}, {2, 1}, {4, 0}}, {{2, -1}, {3, 0}, {0, 1}}, {{4, 0}, {0, -1}, {1, 0}}}); double n = std::sqrt(0.5); matrix matrix2(3, 3, {{{n, 0}, {n, 0}, {0, 0}}, {{0, -n}, {0, n}, {0, 0}}, {{0, 0}, {0, 0}, {0, 1}}}); matrix matrix3(3, 3, {{{2, 2}, {3, 1}, {-3, 5}}, {{2, -1}, {4, 1}, {0, 0}}, {{7, -5}, {1, -4}, {1, 0}}}); test(matrix1); std::cout << '\n'; test(matrix2); std::cout << '\n'; test(matrix3); return 0; }
def conjugate_transpose(m): return tuple(tuple(n.conjugate() for n in row) for row in zip(*m)) def mmul( ma, mb): return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma) def mi(size): 'Complex Identity matrix' sz = range(size) m = [[0 + 0j for i in sz] for j in sz] for i in range(size): m[i][i] = 1 + 0j return tuple(tuple(row) for row in m) def __allsame(vector): first, rest = vector[0], vector[1:] return all(i == first for i in rest) def __allnearsame(vector, eps=1e-14): first, rest = vector[0], vector[1:] return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps for i in rest) def isequal(matrices, eps=1e-14): 'Check any number of matrices for equality within eps' x = [len(m) for m in matrices] if not __allsame(x): return False y = [len(m[0]) for m in matrices] if not __allsame(y): return False for s in range(x[0]): for t in range(y[0]): if not __allnearsame([m[s][t] for m in matrices], eps): return False return True def ishermitian(m, ct): return isequal([m, ct]) def isnormal(m, ct): return isequal([mmul(m, ct), mmul(ct, m)]) def isunitary(m, ct): mct, ctm = mmul(m, ct), mmul(ct, m) mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0]) ident = mi(mctx) return isequal([mct, ctm, ident]) def printm(comment, m): print(comment) fields = [['%g%+gj' % (f.real, f.imag) for f in row] for row in m] width = max(max(len(f) for f in row) for row in fields) lines = (', '.join('%*s' % (width, f) for f in row) for row in fields) print('\n'.join(lines)) if __name__ == '__main__': for matrix in [ ((( 3.000+0.000j), (+2.000+1.000j)), (( 2.000-1.000j), (+1.000+0.000j))), ((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)), (( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)), (( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))), ((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)), (( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)), (( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]: printm('\nMatrix:', matrix) ct = conjugate_transpose(matrix) printm('Its conjugate transpose:', ct) print('Hermitian? %s.' % ishermitian(matrix, ct)) print('Normal? %s.' % isnormal(matrix, ct)) print('Unitary? %s.' % isunitary(matrix, ct))
Keep all operations the same but rewrite the snippet in Python.
#include <gmpxx.h> #include <iomanip> #include <iostream> using big_int = mpz_class; bool is_probably_prime(const big_int& n) { return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0; } big_int jacobsthal_number(unsigned int n) { return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3; } big_int jacobsthal_lucas_number(unsigned int n) { return (big_int(1) << n) + (n % 2 == 0 ? 1 : -1); } big_int jacobsthal_oblong_number(unsigned int n) { return jacobsthal_number(n) * jacobsthal_number(n + 1); } int main() { std::cout << "First 30 Jacobsthal Numbers:\n"; for (unsigned int n = 0; n < 30; ++n) { std::cout << std::setw(9) << jacobsthal_number(n) << ((n + 1) % 5 == 0 ? '\n' : ' '); } std::cout << "\nFirst 30 Jacobsthal-Lucas Numbers:\n"; for (unsigned int n = 0; n < 30; ++n) { std::cout << std::setw(9) << jacobsthal_lucas_number(n) << ((n + 1) % 5 == 0 ? '\n' : ' '); } std::cout << "\nFirst 20 Jacobsthal oblong Numbers:\n"; for (unsigned int n = 0; n < 20; ++n) { std::cout << std::setw(11) << jacobsthal_oblong_number(n) << ((n + 1) % 5 == 0 ? '\n' : ' '); } std::cout << "\nFirst 20 Jacobsthal primes:\n"; for (unsigned int n = 0, count = 0; count < 20; ++n) { auto jn = jacobsthal_number(n); if (is_probably_prime(jn)) { ++count; std::cout << jn << '\n'; } } }
from math import floor, pow def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def odd(n): return n and 1 != 0 def jacobsthal(n): return floor((pow(2,n)+odd(n))/3) def jacobsthal_lucas(n): return int(pow(2,n)+pow(-1,n)) def jacobsthal_oblong(n): return jacobsthal(n)*jacobsthal(n+1) if __name__ == '__main__': print("First 30 Jacobsthal numbers:") for j in range(0, 30): print(jacobsthal(j), end=" ") print("\n\nFirst 30 Jacobsthal-Lucas numbers: ") for j in range(0, 30): print(jacobsthal_lucas(j), end = '\t') print("\n\nFirst 20 Jacobsthal oblong numbers: ") for j in range(0, 20): print(jacobsthal_oblong(j), end=" ") print("\n\nFirst 10 Jacobsthal primes: ") for j in range(3, 33): if isPrime(jacobsthal(j)): print(jacobsthal(j))
Generate an equivalent Python version of this C++ code.
#include <gmpxx.h> #include <iomanip> #include <iostream> using big_int = mpz_class; bool is_probably_prime(const big_int& n) { return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0; } big_int jacobsthal_number(unsigned int n) { return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3; } big_int jacobsthal_lucas_number(unsigned int n) { return (big_int(1) << n) + (n % 2 == 0 ? 1 : -1); } big_int jacobsthal_oblong_number(unsigned int n) { return jacobsthal_number(n) * jacobsthal_number(n + 1); } int main() { std::cout << "First 30 Jacobsthal Numbers:\n"; for (unsigned int n = 0; n < 30; ++n) { std::cout << std::setw(9) << jacobsthal_number(n) << ((n + 1) % 5 == 0 ? '\n' : ' '); } std::cout << "\nFirst 30 Jacobsthal-Lucas Numbers:\n"; for (unsigned int n = 0; n < 30; ++n) { std::cout << std::setw(9) << jacobsthal_lucas_number(n) << ((n + 1) % 5 == 0 ? '\n' : ' '); } std::cout << "\nFirst 20 Jacobsthal oblong Numbers:\n"; for (unsigned int n = 0; n < 20; ++n) { std::cout << std::setw(11) << jacobsthal_oblong_number(n) << ((n + 1) % 5 == 0 ? '\n' : ' '); } std::cout << "\nFirst 20 Jacobsthal primes:\n"; for (unsigned int n = 0, count = 0; count < 20; ++n) { auto jn = jacobsthal_number(n); if (is_probably_prime(jn)) { ++count; std::cout << jn << '\n'; } } }
from math import floor, pow def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def odd(n): return n and 1 != 0 def jacobsthal(n): return floor((pow(2,n)+odd(n))/3) def jacobsthal_lucas(n): return int(pow(2,n)+pow(-1,n)) def jacobsthal_oblong(n): return jacobsthal(n)*jacobsthal(n+1) if __name__ == '__main__': print("First 30 Jacobsthal numbers:") for j in range(0, 30): print(jacobsthal(j), end=" ") print("\n\nFirst 30 Jacobsthal-Lucas numbers: ") for j in range(0, 30): print(jacobsthal_lucas(j), end = '\t') print("\n\nFirst 20 Jacobsthal oblong numbers: ") for j in range(0, 20): print(jacobsthal_oblong(j), end=" ") print("\n\nFirst 10 Jacobsthal primes: ") for j in range(3, 33): if isPrime(jacobsthal(j)): print(jacobsthal(j))
Produce a functionally identical Python code for the snippet given in C++.
#include <iostream> #include <vector> using std::cout; using std::vector; void distribute(int dist, vector<int> &List) { if (dist > List.size() ) List.resize(dist); for (int i=0; i < dist; i++) List[i]++; } vector<int> beadSort(int *myints, int n) { vector<int> list, list2, fifth (myints, myints + n); cout << "#1 Beads falling down: "; for (int i=0; i < fifth.size(); i++) distribute (fifth[i], list); cout << '\n'; cout << "\nBeads on their sides: "; for (int i=0; i < list.size(); i++) cout << " " << list[i]; cout << '\n'; cout << "#2 Beads right side up: "; for (int i=0; i < list.size(); i++) distribute (list[i], list2); cout << '\n'; return list2; } int main() { int myints[] = {734,3,1,24,324,324,32,432,42,3,4,1,1}; vector<int> sorted = beadSort(myints, sizeof(myints)/sizeof(int)); cout << "Sorted list/array: "; for(unsigned int i=0; i<sorted.size(); i++) cout << sorted[i] << ' '; }
from itertools import zip_longest def beadsort(l): return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0))) print(beadsort([5,3,1,7,4,1,1]))
Convert this C++ block to Python, preserving its control flow and logic.
#include <array> #include <iostream> template<typename T, size_t S> using FixedSquareGrid = std::array<std::array<T, S>, S>; struct Cistercian { public: Cistercian() { initN(); } Cistercian(int v) { initN(); draw(v); } Cistercian &operator=(int v) { initN(); draw(v); } friend std::ostream &operator<<(std::ostream &, const Cistercian &); private: FixedSquareGrid<char, 15> canvas; void initN() { for (auto &row : canvas) { row.fill(' '); row[5] = 'x'; } } void horizontal(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r][c] = 'x'; } } void vertical(size_t r1, size_t r2, size_t c) { for (size_t r = r1; r <= r2; r++) { canvas[r][c] = 'x'; } } void diagd(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r + c - c1][c] = 'x'; } } void diagu(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r - c + c1][c] = 'x'; } } void drawOnes(int v) { switch (v) { case 1: horizontal(6, 10, 0); break; case 2: horizontal(6, 10, 4); break; case 3: diagd(6, 10, 0); break; case 4: diagu(6, 10, 4); break; case 5: drawOnes(1); drawOnes(4); break; case 6: vertical(0, 4, 10); break; case 7: drawOnes(1); drawOnes(6); break; case 8: drawOnes(2); drawOnes(6); break; case 9: drawOnes(1); drawOnes(8); break; default: break; } } void drawTens(int v) { switch (v) { case 1: horizontal(0, 4, 0); break; case 2: horizontal(0, 4, 4); break; case 3: diagu(0, 4, 4); break; case 4: diagd(0, 4, 0); break; case 5: drawTens(1); drawTens(4); break; case 6: vertical(0, 4, 0); break; case 7: drawTens(1); drawTens(6); break; case 8: drawTens(2); drawTens(6); break; case 9: drawTens(1); drawTens(8); break; default: break; } } void drawHundreds(int hundreds) { switch (hundreds) { case 1: horizontal(6, 10, 14); break; case 2: horizontal(6, 10, 10); break; case 3: diagu(6, 10, 14); break; case 4: diagd(6, 10, 10); break; case 5: drawHundreds(1); drawHundreds(4); break; case 6: vertical(10, 14, 10); break; case 7: drawHundreds(1); drawHundreds(6); break; case 8: drawHundreds(2); drawHundreds(6); break; case 9: drawHundreds(1); drawHundreds(8); break; default: break; } } void drawThousands(int thousands) { switch (thousands) { case 1: horizontal(0, 4, 14); break; case 2: horizontal(0, 4, 10); break; case 3: diagd(0, 4, 10); break; case 4: diagu(0, 4, 14); break; case 5: drawThousands(1); drawThousands(4); break; case 6: vertical(10, 14, 0); break; case 7: drawThousands(1); drawThousands(6); break; case 8: drawThousands(2); drawThousands(6); break; case 9: drawThousands(1); drawThousands(8); break; default: break; } } void draw(int v) { int thousands = v / 1000; v %= 1000; int hundreds = v / 100; v %= 100; int tens = v / 10; int ones = v % 10; if (thousands > 0) { drawThousands(thousands); } if (hundreds > 0) { drawHundreds(hundreds); } if (tens > 0) { drawTens(tens); } if (ones > 0) { drawOnes(ones); } } }; std::ostream &operator<<(std::ostream &os, const Cistercian &c) { for (auto &row : c.canvas) { for (auto cell : row) { os << cell; } os << '\n'; } return os; } int main() { for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) { std::cout << number << ":\n"; Cistercian c(number); std::cout << c << '\n'; } return 0; }
def _init(): "digit sections for forming numbers" digi_bits = .strip() lines = [[d.replace('.', ' ') for d in ln.strip().split()] for ln in digi_bits.strip().split('\n') if ' formats = '<2 >2 <2 >2'.split() digits = [[f"{dig:{f}}" for dig in line] for f, line in zip(formats, lines)] return digits _digits = _init() def _to_digits(n): assert 0 <= n < 10_000 and int(n) == n return [int(digit) for digit in f"{int(n):04}"][::-1] def num_to_lines(n): global _digits d = _to_digits(n) lines = [ ''.join((_digits[1][d[1]], '┃', _digits[0][d[0]])), ''.join((_digits[0][ 0], '┃', _digits[0][ 0])), ''.join((_digits[3][d[3]], '┃', _digits[2][d[2]])), ] return lines def cjoin(c1, c2, spaces=' '): return [spaces.join(by_row) for by_row in zip(c1, c2)] if __name__ == '__main__': for pow10 in range(4): step = 10 ** pow10 print(f'\nArabic {step}-to-{9*step} by {step} in Cistercian:\n') lines = num_to_lines(step) for n in range(step*2, step*10, step): lines = cjoin(lines, num_to_lines(n)) print('\n'.join(lines)) numbers = [0, 5555, 6789, 6666] print(f'\nArabic {str(numbers)[1:-1]} in Cistercian:\n') lines = num_to_lines(numbers[0]) for n in numbers[1:]: lines = cjoin(lines, num_to_lines(n)) print('\n'.join(lines))
Port the provided C++ code into Python while preserving the original functionality.
#include <array> #include <iostream> template<typename T, size_t S> using FixedSquareGrid = std::array<std::array<T, S>, S>; struct Cistercian { public: Cistercian() { initN(); } Cistercian(int v) { initN(); draw(v); } Cistercian &operator=(int v) { initN(); draw(v); } friend std::ostream &operator<<(std::ostream &, const Cistercian &); private: FixedSquareGrid<char, 15> canvas; void initN() { for (auto &row : canvas) { row.fill(' '); row[5] = 'x'; } } void horizontal(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r][c] = 'x'; } } void vertical(size_t r1, size_t r2, size_t c) { for (size_t r = r1; r <= r2; r++) { canvas[r][c] = 'x'; } } void diagd(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r + c - c1][c] = 'x'; } } void diagu(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r - c + c1][c] = 'x'; } } void drawOnes(int v) { switch (v) { case 1: horizontal(6, 10, 0); break; case 2: horizontal(6, 10, 4); break; case 3: diagd(6, 10, 0); break; case 4: diagu(6, 10, 4); break; case 5: drawOnes(1); drawOnes(4); break; case 6: vertical(0, 4, 10); break; case 7: drawOnes(1); drawOnes(6); break; case 8: drawOnes(2); drawOnes(6); break; case 9: drawOnes(1); drawOnes(8); break; default: break; } } void drawTens(int v) { switch (v) { case 1: horizontal(0, 4, 0); break; case 2: horizontal(0, 4, 4); break; case 3: diagu(0, 4, 4); break; case 4: diagd(0, 4, 0); break; case 5: drawTens(1); drawTens(4); break; case 6: vertical(0, 4, 0); break; case 7: drawTens(1); drawTens(6); break; case 8: drawTens(2); drawTens(6); break; case 9: drawTens(1); drawTens(8); break; default: break; } } void drawHundreds(int hundreds) { switch (hundreds) { case 1: horizontal(6, 10, 14); break; case 2: horizontal(6, 10, 10); break; case 3: diagu(6, 10, 14); break; case 4: diagd(6, 10, 10); break; case 5: drawHundreds(1); drawHundreds(4); break; case 6: vertical(10, 14, 10); break; case 7: drawHundreds(1); drawHundreds(6); break; case 8: drawHundreds(2); drawHundreds(6); break; case 9: drawHundreds(1); drawHundreds(8); break; default: break; } } void drawThousands(int thousands) { switch (thousands) { case 1: horizontal(0, 4, 14); break; case 2: horizontal(0, 4, 10); break; case 3: diagd(0, 4, 10); break; case 4: diagu(0, 4, 14); break; case 5: drawThousands(1); drawThousands(4); break; case 6: vertical(10, 14, 0); break; case 7: drawThousands(1); drawThousands(6); break; case 8: drawThousands(2); drawThousands(6); break; case 9: drawThousands(1); drawThousands(8); break; default: break; } } void draw(int v) { int thousands = v / 1000; v %= 1000; int hundreds = v / 100; v %= 100; int tens = v / 10; int ones = v % 10; if (thousands > 0) { drawThousands(thousands); } if (hundreds > 0) { drawHundreds(hundreds); } if (tens > 0) { drawTens(tens); } if (ones > 0) { drawOnes(ones); } } }; std::ostream &operator<<(std::ostream &os, const Cistercian &c) { for (auto &row : c.canvas) { for (auto cell : row) { os << cell; } os << '\n'; } return os; } int main() { for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) { std::cout << number << ":\n"; Cistercian c(number); std::cout << c << '\n'; } return 0; }
def _init(): "digit sections for forming numbers" digi_bits = .strip() lines = [[d.replace('.', ' ') for d in ln.strip().split()] for ln in digi_bits.strip().split('\n') if ' formats = '<2 >2 <2 >2'.split() digits = [[f"{dig:{f}}" for dig in line] for f, line in zip(formats, lines)] return digits _digits = _init() def _to_digits(n): assert 0 <= n < 10_000 and int(n) == n return [int(digit) for digit in f"{int(n):04}"][::-1] def num_to_lines(n): global _digits d = _to_digits(n) lines = [ ''.join((_digits[1][d[1]], '┃', _digits[0][d[0]])), ''.join((_digits[0][ 0], '┃', _digits[0][ 0])), ''.join((_digits[3][d[3]], '┃', _digits[2][d[2]])), ] return lines def cjoin(c1, c2, spaces=' '): return [spaces.join(by_row) for by_row in zip(c1, c2)] if __name__ == '__main__': for pow10 in range(4): step = 10 ** pow10 print(f'\nArabic {step}-to-{9*step} by {step} in Cistercian:\n') lines = num_to_lines(step) for n in range(step*2, step*10, step): lines = cjoin(lines, num_to_lines(n)) print('\n'.join(lines)) numbers = [0, 5555, 6789, 6666] print(f'\nArabic {str(numbers)[1:-1]} in Cistercian:\n') lines = num_to_lines(numbers[0]) for n in numbers[1:]: lines = cjoin(lines, num_to_lines(n)) print('\n'.join(lines))
Rewrite this program in Python while keeping its functionality equivalent to the C++ version.
#include <iostream> #include <boost/multiprecision/gmp.hpp> #include <string> namespace mp = boost::multiprecision; int main(int argc, char const *argv[]) { uint64_t tmpres = mp::pow(mp::mpz_int(4) , mp::pow(mp::mpz_int(3) , 2).convert_to<uint64_t>() ).convert_to<uint64_t>(); mp::mpz_int res = mp::pow(mp::mpz_int(5), tmpres); std::string s = res.str(); std::cout << s.substr(0, 20) << "..." << s.substr(s.length() - 20, 20) << std::endl; return 0; }
>>> y = str( 5**4**3**2 ) >>> print ("5**4**3**2 = %s...%s and has %i digits" % (y[:20], y[-20:], len(y))) 5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits
Keep all operations the same but rewrite the snippet in Python.
#include <QImage> #include <QPainter> int main() { const QColor black(0, 0, 0); const QColor white(255, 255, 255); const int size = 300; const double diameter = 0.6 * size; QImage image(size, size, QImage::Format_RGB32); QPainter painter(&image); painter.setRenderHint(QPainter::Antialiasing); QLinearGradient linearGradient(0, 0, 0, size); linearGradient.setColorAt(0, white); linearGradient.setColorAt(1, black); QBrush brush(linearGradient); painter.fillRect(QRect(0, 0, size, size), brush); QPointF point1(0.4 * size, 0.4 * size); QPointF point2(0.45 * size, 0.4 * size); QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1); radialGradient.setColorAt(0, white); radialGradient.setColorAt(1, black); QBrush brush2(radialGradient); painter.setPen(Qt::NoPen); painter.setBrush(brush2); painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter)); image.save("sphere.png"); return 0; }
import math shades = ('.',':','!','*','o','e','&',' def normalize(v): len = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2) return (v[0]/len, v[1]/len, v[2]/len) def dot(x,y): d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2] return -d if d < 0 else 0 def draw_sphere(r, k, ambient, light): for i in range(int(math.floor(-r)),int(math.ceil(r)+1)): x = i + 0.5 line = '' for j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)): y = j/2 + 0.5 if x*x + y*y <= r*r: vec = normalize((x,y,math.sqrt(r*r - x*x - y*y))) b = dot(light,vec)**k + ambient intensity = int((1-b)*(len(shades)-1)) line += shades[intensity] if 0 <= intensity < len(shades) else shades[0] else: line += ' ' print(line) light = normalize((30,30,-50)) draw_sphere(20,4,0.1, light) draw_sphere(10,2,0.4, light)
Generate a Python translation of this C++ snippet without changing its computational steps.
#include <QImage> #include <QPainter> int main() { const QColor black(0, 0, 0); const QColor white(255, 255, 255); const int size = 300; const double diameter = 0.6 * size; QImage image(size, size, QImage::Format_RGB32); QPainter painter(&image); painter.setRenderHint(QPainter::Antialiasing); QLinearGradient linearGradient(0, 0, 0, size); linearGradient.setColorAt(0, white); linearGradient.setColorAt(1, black); QBrush brush(linearGradient); painter.fillRect(QRect(0, 0, size, size), brush); QPointF point1(0.4 * size, 0.4 * size); QPointF point2(0.45 * size, 0.4 * size); QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1); radialGradient.setColorAt(0, white); radialGradient.setColorAt(1, black); QBrush brush2(radialGradient); painter.setPen(Qt::NoPen); painter.setBrush(brush2); painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter)); image.save("sphere.png"); return 0; }
import math shades = ('.',':','!','*','o','e','&',' def normalize(v): len = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2) return (v[0]/len, v[1]/len, v[2]/len) def dot(x,y): d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2] return -d if d < 0 else 0 def draw_sphere(r, k, ambient, light): for i in range(int(math.floor(-r)),int(math.ceil(r)+1)): x = i + 0.5 line = '' for j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)): y = j/2 + 0.5 if x*x + y*y <= r*r: vec = normalize((x,y,math.sqrt(r*r - x*x - y*y))) b = dot(light,vec)**k + ambient intensity = int((1-b)*(len(shades)-1)) line += shades[intensity] if 0 <= intensity < len(shades) else shades[0] else: line += ' ' print(line) light = normalize((30,30,-50)) draw_sphere(20,4,0.1, light) draw_sphere(10,2,0.4, light)
Produce a functionally identical Python code for the snippet given in C++.
#include <algorithm> #include <fstream> #include <iostream> #include <vector> #include <string> const std::string _CHARS = "abcdefghijklmnopqrstuvwxyz0123456789.:-_/"; const size_t MAX_NODES = 41; class node { public: node() { clear(); } node( char z ) { clear(); } ~node() { for( int x = 0; x < MAX_NODES; x++ ) if( next[x] ) delete next[x]; } void clear() { for( int x = 0; x < MAX_NODES; x++ ) next[x] = 0; isWord = false; } bool isWord; std::vector<std::string> files; node* next[MAX_NODES]; }; class index { public: void add( std::string s, std::string fileName ) { std::transform( s.begin(), s.end(), s.begin(), tolower ); std::string h; for( std::string::iterator i = s.begin(); i != s.end(); i++ ) { if( *i == 32 ) { pushFileName( addWord( h ), fileName ); h.clear(); continue; } h.append( 1, *i ); } if( h.length() ) pushFileName( addWord( h ), fileName ); } void findWord( std::string s ) { std::vector<std::string> v = find( s ); if( !v.size() ) { std::cout << s + " was not found!\n"; return; } std::cout << s << " found in:\n"; for( std::vector<std::string>::iterator i = v.begin(); i != v.end(); i++ ) { std::cout << *i << "\n"; } std::cout << "\n"; } private: void pushFileName( node* n, std::string fn ) { std::vector<std::string>::iterator i = std::find( n->files.begin(), n->files.end(), fn ); if( i == n->files.end() ) n->files.push_back( fn ); } const std::vector<std::string>& find( std::string s ) { size_t idx; std::transform( s.begin(), s.end(), s.begin(), tolower ); node* rt = &root; for( std::string::iterator i = s.begin(); i != s.end(); i++ ) { idx = _CHARS.find( *i ); if( idx < MAX_NODES ) { if( !rt->next[idx] ) return std::vector<std::string>(); rt = rt->next[idx]; } } if( rt->isWord ) return rt->files; return std::vector<std::string>(); } node* addWord( std::string s ) { size_t idx; node* rt = &root, *n; for( std::string::iterator i = s.begin(); i != s.end(); i++ ) { idx = _CHARS.find( *i ); if( idx < MAX_NODES ) { n = rt->next[idx]; if( n ){ rt = n; continue; } n = new node( *i ); rt->next[idx] = n; rt = n; } } rt->isWord = true; return rt; } node root; }; int main( int argc, char* argv[] ) { index t; std::string s; std::string files[] = { "file1.txt", "f_text.txt", "text_1b.txt" }; for( int x = 0; x < 3; x++ ) { std::ifstream f; f.open( files[x].c_str(), std::ios::in ); if( f.good() ) { while( !f.eof() ) { f >> s; t.add( s, files[x] ); s.clear(); } f.close(); } } while( true ) { std::cout << "Enter one word to search for, return to exit: "; std::getline( std::cin, s ); if( !s.length() ) break; t.findWord( s ); } return 0; }
from pprint import pprint as pp from glob import glob try: reduce except: from functools import reduce try: raw_input except: raw_input = input def parsetexts(fileglob='InvertedIndex/T*.txt'): texts, words = {}, set() for txtfile in glob(fileglob): with open(txtfile, 'r') as f: txt = f.read().split() words |= set(txt) texts[txtfile.split('\\')[-1]] = txt return texts, words def termsearch(terms): return reduce(set.intersection, (invindex[term] for term in terms), set(texts.keys())) texts, words = parsetexts() print('\nTexts') pp(texts) print('\nWords') pp(sorted(words)) invindex = {word:set(txt for txt, wrds in texts.items() if word in wrds) for word in words} print('\nInverted Index') pp({k:sorted(v) for k,v in invindex.items()}) terms = ["what", "is", "it"] print('\nTerm Search for: ' + repr(terms)) pp(sorted(termsearch(terms)))
Translate this program into Python but keep the logic exactly as in C++.
#include <boost/math/common_factor.hpp> #include <iostream> int main( ) { std::cout << "The least common multiple of 12 and 18 is " << boost::math::lcm( 12 , 18 ) << " ,\n" << "and the greatest common divisor " << boost::math::gcd( 12 , 18 ) << " !" << std::endl ; return 0 ; }
>>> import fractions >>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0 >>> lcm(12, 18) 36 >>> lcm(-6, 14) 42 >>> assert lcm(0, 2) == lcm(2, 0) == 0 >>>
Generate an equivalent Python version of this C++ code.
#include <boost/math/common_factor.hpp> #include <iostream> int main( ) { std::cout << "The least common multiple of 12 and 18 is " << boost::math::lcm( 12 , 18 ) << " ,\n" << "and the greatest common divisor " << boost::math::gcd( 12 , 18 ) << " !" << std::endl ; return 0 ; }
>>> import fractions >>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0 >>> lcm(12, 18) 36 >>> lcm(-6, 14) 42 >>> assert lcm(0, 2) == lcm(2, 0) == 0 >>>
Port the following code from C++ to Python with equivalent syntax and logic.
#include <iostream> #include <vector> #include <boost/integer/common_factor.hpp> #include <boost/multiprecision/cpp_int.hpp> #include <boost/multiprecision/miller_rabin.hpp> typedef boost::multiprecision::cpp_int integer; integer fermat(unsigned int n) { unsigned int p = 1; for (unsigned int i = 0; i < n; ++i) p *= 2; return 1 + pow(integer(2), p); } inline void g(integer& x, const integer& n) { x *= x; x += 1; x %= n; } integer pollard_rho(const integer& n) { integer x = 2, y = 2, d = 1, z = 1; int count = 0; for (;;) { g(x, n); g(y, n); g(y, n); d = abs(x - y); z = (z * d) % n; ++count; if (count == 100) { d = gcd(z, n); if (d != 1) break; z = 1; count = 0; } } if (d == n) return 0; return d; } std::vector<integer> get_prime_factors(integer n) { std::vector<integer> factors; for (;;) { if (miller_rabin_test(n, 25)) { factors.push_back(n); break; } integer f = pollard_rho(n); if (f == 0) { factors.push_back(n); break; } factors.push_back(f); n /= f; } return factors; } void print_vector(const std::vector<integer>& factors) { if (factors.empty()) return; auto i = factors.begin(); std::cout << *i++; for (; i != factors.end(); ++i) std::cout << ", " << *i; std::cout << '\n'; } int main() { std::cout << "First 10 Fermat numbers:\n"; for (unsigned int i = 0; i < 10; ++i) std::cout << "F(" << i << ") = " << fermat(i) << '\n'; std::cout << "\nPrime factors:\n"; for (unsigned int i = 0; i < 9; ++i) { std::cout << "F(" << i << "): "; print_vector(get_prime_factors(fermat(i))); } return 0; }
def factors(x): factors = [] i = 2 s = int(x ** 0.5) while i < s: if x % i == 0: factors.append(i) x = int(x / i) s = int(x ** 0.5) i += 1 factors.append(x) return factors print("First 10 Fermat numbers:") for i in range(10): fermat = 2 ** 2 ** i + 1 print("F{} = {}".format(chr(i + 0x2080) , fermat)) print("\nFactors of first few Fermat numbers:") for i in range(10): fermat = 2 ** 2 ** i + 1 fac = factors(fermat) if len(fac) == 1: print("F{} -> IS PRIME".format(chr(i + 0x2080))) else: print("F{} -> FACTORS: {}".format(chr(i + 0x2080), fac))
Generate an equivalent Python version of this C++ code.
#include <iostream> #include <ctime> #include <cstdlib> int main(){ srand(time(NULL)); while(true){ const int a = rand() % 20; std::cout << a << std::endl; if(a == 10) break; const int b = rand() % 20; std::cout << b << std::endl; } return 0; }
from random import randrange while True: a = randrange(20) print(a) if a == 10: break b = randrange(20) print(b)
Translate this program into Python but keep the logic exactly as in C++.
#include <iostream> #include <fstream> int main(){ std::ofstream lprFile; lprFile.open( "/dev/lp0" ); lprFile << "Hello World!\n"; lprFile.close(); return 0; }
lp = open("/dev/lp0") lp.write("Hello World!\n") lp.close()
Generate a Python translation of this C++ snippet without changing its computational steps.
#include <iostream> #include <fstream> int main(){ std::ofstream lprFile; lprFile.open( "/dev/lp0" ); lprFile << "Hello World!\n"; lprFile.close(); return 0; }
lp = open("/dev/lp0") lp.write("Hello World!\n") lp.close()
Change the programming language of this snippet from C++ to Python without modifying what it does.
#include <iostream> #include <vector> #include <algorithm> enum { EMPTY, WALL, WATER }; auto fill(const std::vector<int> b) { auto water = 0; const auto rows = *std::max_element(std::begin(b), std::end(b)); const auto cols = std::size(b); std::vector<std::vector<int>> g(rows); for (auto& r : g) { for (auto i = 0; i < cols; ++i) { r.push_back(EMPTY); } } for (auto c = 0; c < cols; ++c) { for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) { g[r][c] = WALL; } } for (auto c = 0; c < cols - 1; ++c) { auto start_row = rows - b[c]; while (start_row < rows) { if (g[start_row][c] == EMPTY) break; auto c2 = c + 1; bool hitWall = false; while (c2 < cols) { if (g[start_row][c2] == WALL) { hitWall = true; break; } ++c2; } if (hitWall) { for (auto i = c + 1; i < c2; ++i) { g[start_row][i] = WATER; ++water; } } ++start_row; } } return water; } int main() { std::vector<std::vector<int>> b = { { 1, 5, 3, 7, 2 }, { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 }, { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 }, { 5, 5, 5, 5 }, { 5, 6, 7, 8 }, { 8, 7, 7, 6 }, { 6, 7, 10, 7, 6 } }; for (const auto v : b) { auto water = fill(v); std::cout << water << " water drops." << std::endl; } std::cin.ignore(); std::cin.get(); return 0; }
def water_collected(tower): N = len(tower) highest_left = [0] + [max(tower[:n]) for n in range(1,N)] highest_right = [max(tower[n:N]) for n in range(1,N)] + [0] water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0) for n in range(N)] print("highest_left: ", highest_left) print("highest_right: ", highest_right) print("water_level: ", water_level) print("tower_level: ", tower) print("total_water: ", sum(water_level)) print("") return sum(water_level) towers = [[1, 5, 3, 7, 2], [5, 3, 7, 2, 6, 4, 5, 9, 1, 2], [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1], [5, 5, 5, 5], [5, 6, 7, 8], [8, 7, 7, 6], [6, 7, 10, 7, 6]] [water_collected(tower) for tower in towers]
Produce a functionally identical Python code for the snippet given in C++.
#include <iostream> bool ispr(unsigned int n) { if ((n & 1) == 0 || n < 2) return n == 2; for (unsigned int j = 3; j * j <= n; j += 2) if (n % j == 0) return false; return true; } int main() { unsigned int c = 0, nc, pc = 9, i, a, b, l, ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128]; while (true) { nc = 0; for (i = 0; i < pc; i++) { if (ispr(a = ps[i])) printf("%8d%s", a, ++c % 5 == 0 ? "\n" : " "); for (b = a * 10, l = a % 10 + b++; b < l; b++) nxt[nc++] = b; } if (nc > 1) for(i = 0, pc = nc; i < pc; i++) ps[i] = nxt[i]; else break; } printf("\n%d descending primes found", c); }
from sympy import isprime def descending(xs=range(10)): for x in xs: yield x yield from descending(x*10 + d for d in range(x%10)) for i, p in enumerate(sorted(filter(isprime, descending()))): print(f'{p:9d}', end=' ' if (1 + i)%8 else '\n') print()
Write a version of this C++ function in Python with identical behavior.
#include <cstdint> #include <iostream> #include <string> using integer = uint64_t; bool square_free(integer n) { if (n % 4 == 0) return false; for (integer p = 3; p * p <= n; p += 2) { integer count = 0; for (; n % p == 0; n /= p) { if (++count > 1) return false; } } return true; } void print_square_free_numbers(integer from, integer to) { std::cout << "Square-free numbers between " << from << " and " << to << ":\n"; std::string line; for (integer i = from; i <= to; ++i) { if (square_free(i)) { if (!line.empty()) line += ' '; line += std::to_string(i); if (line.size() >= 80) { std::cout << line << '\n'; line.clear(); } } } if (!line.empty()) std::cout << line << '\n'; } void print_square_free_count(integer from, integer to) { integer count = 0; for (integer i = from; i <= to; ++i) { if (square_free(i)) ++count; } std::cout << "Number of square-free numbers between " << from << " and " << to << ": " << count << '\n'; } int main() { print_square_free_numbers(1, 145); print_square_free_numbers(1000000000000LL, 1000000000145LL); print_square_free_count(1, 100); print_square_free_count(1, 1000); print_square_free_count(1, 10000); print_square_free_count(1, 100000); print_square_free_count(1, 1000000); return 0; }
import math def SquareFree ( _number ) : max = (int) (math.sqrt ( _number )) for root in range ( 2, max+1 ): if 0 == _number % ( root * root ): return False return True def ListSquareFrees( _start, _end ): count = 0 for i in range ( _start, _end+1 ): if True == SquareFree( i ): print ( "{}\t".format(i), end="" ) count += 1 print ( "\n\nTotal count of square-free numbers between {} and {}: {}".format(_start, _end, count)) ListSquareFrees( 1, 100 ) ListSquareFrees( 1000000000000, 1000000000145 )
Maintain the same structure and functionality when rewriting this code in Python.
#include <algorithm> #include <iostream> #include <string> double jaro(const std::string s1, const std::string s2) { const uint l1 = s1.length(), l2 = s2.length(); if (l1 == 0) return l2 == 0 ? 1.0 : 0.0; const uint match_distance = std::max(l1, l2) / 2 - 1; bool s1_matches[l1]; bool s2_matches[l2]; std::fill(s1_matches, s1_matches + l1, false); std::fill(s2_matches, s2_matches + l2, false); uint matches = 0; for (uint i = 0; i < l1; i++) { const int end = std::min(i + match_distance + 1, l2); for (int k = std::max(0u, i - match_distance); k < end; k++) if (!s2_matches[k] && s1[i] == s2[k]) { s1_matches[i] = true; s2_matches[k] = true; matches++; break; } } if (matches == 0) return 0.0; double t = 0.0; uint k = 0; for (uint i = 0; i < l1; i++) if (s1_matches[i]) { while (!s2_matches[k]) k++; if (s1[i] != s2[k]) t += 0.5; k++; } const double m = matches; return (m / l1 + m / l2 + (m - t) / m) / 3.0; } int main() { using namespace std; cout << jaro("MARTHA", "MARHTA") << endl; cout << jaro("DIXON", "DICKSONX") << endl; cout << jaro("JELLYFISH", "SMELLYFISH") << endl; return 0; }
from __future__ import division def jaro(s, t): s_len = len(s) t_len = len(t) if s_len == 0 and t_len == 0: return 1 match_distance = (max(s_len, t_len) // 2) - 1 s_matches = [False] * s_len t_matches = [False] * t_len matches = 0 transpositions = 0 for i in range(s_len): start = max(0, i - match_distance) end = min(i + match_distance + 1, t_len) for j in range(start, end): if t_matches[j]: continue if s[i] != t[j]: continue s_matches[i] = True t_matches[j] = True matches += 1 break if matches == 0: return 0 k = 0 for i in range(s_len): if not s_matches[i]: continue while not t_matches[k]: k += 1 if s[i] != t[k]: transpositions += 1 k += 1 return ((matches / s_len) + (matches / t_len) + ((matches - transpositions / 2) / matches)) / 3 def main(): for s, t in [('MARTHA', 'MARHTA'), ('DIXON', 'DICKSONX'), ('JELLYFISH', 'SMELLYFISH')]: print("jaro(%r, %r) = %.10f" % (s, t, jaro(s, t))) if __name__ == '__main__': main()
Generate an equivalent Python version of this C++ code.
#include <algorithm> #include <iostream> #include <map> #include <vector> std::ostream &operator<<(std::ostream &os, std::vector<std::pair<int, int>> &v) { for (auto &p : v) { auto sum = p.first + p.second; auto prod = p.first * p.second; os << '[' << p.first << ", " << p.second << "] S=" << sum << " P=" << prod; } return os << '\n'; } void print_count(const std::vector<std::pair<int, int>> &candidates) { auto c = candidates.size(); if (c == 0) { std::cout << "no candidates\n"; } else if (c == 1) { std::cout << "one candidate\n"; } else { std::cout << c << " candidates\n"; } } auto setup() { std::vector<std::pair<int, int>> candidates; for (int x = 2; x <= 98; x++) { for (int y = x + 1; y <= 98; y++) { if (x + y <= 100) { candidates.push_back(std::make_pair(x, y)); } } } return candidates; } void remove_by_sum(std::vector<std::pair<int, int>> &candidates, const int sum) { candidates.erase(std::remove_if( candidates.begin(), candidates.end(), [sum](const std::pair<int, int> &pair) { auto s = pair.first + pair.second; return s == sum; } ), candidates.end()); } void remove_by_prod(std::vector<std::pair<int, int>> &candidates, const int prod) { candidates.erase(std::remove_if( candidates.begin(), candidates.end(), [prod](const std::pair<int, int> &pair) { auto p = pair.first * pair.second; return p == prod; } ), candidates.end()); } void statement1(std::vector<std::pair<int, int>> &candidates) { std::map<int, int> uniqueMap; std::for_each( candidates.cbegin(), candidates.cend(), [&uniqueMap](const std::pair<int, int> &pair) { auto prod = pair.first * pair.second; uniqueMap[prod]++; } ); bool loop; do { loop = false; for (auto &pair : candidates) { auto prod = pair.first * pair.second; if (uniqueMap[prod] == 1) { auto sum = pair.first + pair.second; remove_by_sum(candidates, sum); loop = true; break; } } } while (loop); } void statement2(std::vector<std::pair<int, int>> &candidates) { std::map<int, int> uniqueMap; std::for_each( candidates.cbegin(), candidates.cend(), [&uniqueMap](const std::pair<int, int> &pair) { auto prod = pair.first * pair.second; uniqueMap[prod]++; } ); bool loop; do { loop = false; for (auto &pair : candidates) { auto prod = pair.first * pair.second; if (uniqueMap[prod] > 1) { remove_by_prod(candidates, prod); loop = true; break; } } } while (loop); } void statement3(std::vector<std::pair<int, int>> &candidates) { std::map<int, int> uniqueMap; std::for_each( candidates.cbegin(), candidates.cend(), [&uniqueMap](const std::pair<int, int> &pair) { auto sum = pair.first + pair.second; uniqueMap[sum]++; } ); bool loop; do { loop = false; for (auto &pair : candidates) { auto sum = pair.first + pair.second; if (uniqueMap[sum] > 1) { remove_by_sum(candidates, sum); loop = true; break; } } } while (loop); } int main() { auto candidates = setup(); print_count(candidates); statement1(candidates); print_count(candidates); statement2(candidates); print_count(candidates); statement3(candidates); print_count(candidates); std::cout << candidates; return 0; }
from collections import Counter def decompose_sum(s): return [(a,s-a) for a in range(2,int(s/2+1))] all_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100) product_counts = Counter(c*d for c,d in all_pairs) unique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1) s_pairs = [(a,b) for a,b in all_pairs if all((x,y) not in unique_products for (x,y) in decompose_sum(a+b))] product_counts = Counter(c*d for c,d in s_pairs) p_pairs = [(a,b) for a,b in s_pairs if product_counts[a*b]==1] sum_counts = Counter(c+d for c,d in p_pairs) final_pairs = [(a,b) for a,b in p_pairs if sum_counts[a+b]==1] print(final_pairs)
Write the same code in Python as shown below in C++.
#include <iostream> #include <vector> int turn(int base, int n) { int sum = 0; while (n != 0) { int rem = n % base; n = n / base; sum += rem; } return sum % base; } void fairshare(int base, int count) { printf("Base %2d:", base); for (int i = 0; i < count; i++) { int t = turn(base, i); printf(" %2d", t); } printf("\n"); } void turnCount(int base, int count) { std::vector<int> cnt(base, 0); for (int i = 0; i < count; i++) { int t = turn(base, i); cnt[t]++; } int minTurn = INT_MAX; int maxTurn = INT_MIN; int portion = 0; for (int i = 0; i < base; i++) { if (cnt[i] > 0) { portion++; } if (cnt[i] < minTurn) { minTurn = cnt[i]; } if (cnt[i] > maxTurn) { maxTurn = cnt[i]; } } printf(" With %d people: ", base); if (0 == minTurn) { printf("Only %d have a turn\n", portion); } else if (minTurn == maxTurn) { printf("%d\n", minTurn); } else { printf("%d or %d\n", minTurn, maxTurn); } } int main() { fairshare(2, 25); fairshare(3, 25); fairshare(5, 25); fairshare(11, 25); printf("How many times does each get a turn in 50000 iterations?\n"); turnCount(191, 50000); turnCount(1377, 50000); turnCount(49999, 50000); turnCount(50000, 50000); turnCount(50001, 50000); return 0; }
from itertools import count, islice def _basechange_int(num, b): if num == 0: return [0] result = [] while num != 0: num, d = divmod(num, b) result.append(d) return result[::-1] def fairshare(b=2): for i in count(): yield sum(_basechange_int(i, b)) % b if __name__ == '__main__': for b in (2, 3, 5, 11): print(f"{b:>2}: {str(list(islice(fairshare(b), 25)))[1:-1]}")
Convert the following code from C++ to Python, ensuring the logic remains intact.
#include <array> #include <iomanip> #include <iostream> #include <random> #include <sstream> class Roulette { private: std::array<bool, 6> cylinder; std::mt19937 gen; std::uniform_int_distribution<> distrib; int next_int() { return distrib(gen); } void rshift() { std::rotate(cylinder.begin(), cylinder.begin() + 1, cylinder.end()); } void unload() { std::fill(cylinder.begin(), cylinder.end(), false); } void load() { while (cylinder[0]) { rshift(); } cylinder[0] = true; rshift(); } void spin() { int lim = next_int(); for (int i = 1; i < lim; i++) { rshift(); } } bool fire() { auto shot = cylinder[0]; rshift(); return shot; } public: Roulette() { std::random_device rd; gen = std::mt19937(rd()); distrib = std::uniform_int_distribution<>(1, 6); unload(); } int method(const std::string &s) { unload(); for (auto c : s) { switch (c) { case 'L': load(); break; case 'S': spin(); break; case 'F': if (fire()) { return 1; } break; } } return 0; } }; std::string mstring(const std::string &s) { std::stringstream ss; bool first = true; auto append = [&ss, &first](const std::string s) { if (first) { first = false; } else { ss << ", "; } ss << s; }; for (auto c : s) { switch (c) { case 'L': append("load"); break; case 'S': append("spin"); break; case 'F': append("fire"); break; } } return ss.str(); } void test(const std::string &src) { const int tests = 100000; int sum = 0; Roulette r; for (int t = 0; t < tests; t++) { sum += r.method(src); } double pc = 100.0 * sum / tests; std::cout << std::left << std::setw(40) << mstring(src) << " produces " << pc << "% deaths.\n"; } int main() { test("LSLSFSF"); test("LSLSFF"); test("LLSFSF"); test("LLSFF"); return 0; }
import numpy as np class Revolver: def __init__(self): self.cylinder = np.array([False] * 6) def unload(self): self.cylinder[:] = False def load(self): while self.cylinder[1]: self.cylinder[:] = np.roll(self.cylinder, 1) self.cylinder[1] = True def spin(self): self.cylinder[:] = np.roll(self.cylinder, np.random.randint(1, high=7)) def fire(self): shot = self.cylinder[0] self.cylinder[:] = np.roll(self.cylinder, 1) return shot def LSLSFSF(self): self.unload() self.load() self.spin() self.load() self.spin() if self.fire(): return True self.spin() if self.fire(): return True return False def LSLSFF(self): self.unload() self.load() self.spin() self.load() self.spin() if self.fire(): return True if self.fire(): return True return False def LLSFSF(self): self.unload() self.load() self.load() self.spin() if self.fire(): return True self.spin() if self.fire(): return True return False def LLSFF(self): self.unload() self.load() self.load() self.spin() if self.fire(): return True if self.fire(): return True return False if __name__ == '__main__': REV = Revolver() TESTCOUNT = 100000 for (name, method) in [['load, spin, load, spin, fire, spin, fire', REV.LSLSFSF], ['load, spin, load, spin, fire, fire', REV.LSLSFF], ['load, load, spin, fire, spin, fire', REV.LLSFSF], ['load, load, spin, fire, fire', REV.LLSFF]]: percentage = 100 * sum([method() for _ in range(TESTCOUNT)]) / TESTCOUNT print("Method", name, "produces", percentage, "per cent deaths.")
Please provide an equivalent version of this C++ code in Python.
#include <ciso646> #include <iostream> #include <regex> #include <sstream> #include <string> #include <unordered_map> #include <utility> #include <vector> using std::vector; using std::string; #include <exception> #include <stdexcept> template <typename...Args> std::runtime_error error( Args...args ) { return std::runtime_error( (std::ostringstream{} << ... << args).str() ); }; template <typename T> struct stack : public std::vector <T> { using base_type = std::vector <T> ; T push ( const T& x ) { base_type::push_back( x ); return x; } const T& top () { return base_type::back(); } T pop () { T x = std::move( top() ); base_type::pop_back(); return x; } bool empty() { return base_type::empty(); } }; using Number = double; using Operator_Name = string; using Precedence = int; enum class Associates { none, left_to_right, right_to_left }; struct Operator_Info { Precedence precedence; Associates associativity; }; std::unordered_map <Operator_Name, Operator_Info> Operators = { { "^", { 4, Associates::right_to_left } }, { "*", { 3, Associates::left_to_right } }, { "/", { 3, Associates::left_to_right } }, { "+", { 2, Associates::left_to_right } }, { "-", { 2, Associates::left_to_right } }, }; Precedence precedence ( const Operator_Name& op ) { return Operators[ op ].precedence; } Associates associativity( const Operator_Name& op ) { return Operators[ op ].associativity; } using Token = string; bool is_number ( const Token& t ) { return regex_match( t, std::regex{ R"z((\d+(\.\d*)?|\.\d+)([Ee][\+\-]?\d+)?)z" } ); } bool is_operator ( const Token& t ) { return Operators.count( t ); } bool is_open_parenthesis ( const Token& t ) { return t == "("; } bool is_close_parenthesis( const Token& t ) { return t == ")"; } bool is_parenthesis ( const Token& t ) { return is_open_parenthesis( t ) or is_close_parenthesis( t ); } template <typename T> std::ostream& operator << ( std::ostream& outs, const std::vector <T> & xs ) { std::size_t n = 0; for (auto x : xs) outs << (n++ ? " " : "") << x; return outs; } #include <iomanip> struct Progressive_Display { string token_name; string token_type; Progressive_Display() { std::cout << "\n" " INPUT │ TYPE │ ACTION │ STACK │ OUTPUT\n" "────────┼──────┼──────────────────┼──────────────┼─────────────────────────────\n"; } Progressive_Display& operator () ( const Token& token ) { token_name = token; token_type = is_operator ( token ) ? "op" : is_parenthesis( token ) ? "()" : is_number ( token ) ? "num" : ""; return *this; } Progressive_Display& operator () ( const string & description, const stack <Token> & stack, const vector <Token> & output ) { std::cout << std::right << std::setw( 7 ) << token_name << " │ " << std::left << std::setw( 4 ) << token_type << " │ " << std::setw( 16 ) << description << " │ " << std::setw( 12 ) << (std::ostringstream{} << stack).str() << " │ " << output << "\n"; return operator () ( "" ); } }; vector <Token> parse( const vector <Token> & tokens ) { vector <Token> output; stack <Token> stack; Progressive_Display display; for (auto token : tokens) if (is_number( token )) { output.push_back( token ); display( token )( "num --> output", stack, output ); } else if (is_operator( token ) or is_parenthesis( token )) { display( token ); if (!is_open_parenthesis( token )) { while (!stack.empty() and ( (is_close_parenthesis( token ) and !is_open_parenthesis( stack.top() )) or (precedence( stack.top() ) > precedence( token )) or ( (precedence( stack.top() ) == precedence( token )) and (associativity( token ) == Associates::left_to_right)))) { output.push_back( stack.pop() ); display( "pop --> output", stack, output ); } if (is_close_parenthesis( token )) { stack.pop(); display( "pop", stack, output ); } } if (!is_close_parenthesis( token )) { stack.push( token ); display( "push op", stack, output ); } } else throw error( "unexpected token: ", token ); display( "END" ); while (!stack.empty()) { output.push_back( stack.pop() ); display( "pop --> output", stack, output ); } return output; } int main( int argc, char** argv ) try { auto tokens = vector <Token> ( argv+1, argv+argc ); auto rpn_expr = parse( tokens ); std::cout << "\nInfix = " << tokens << "\nRPN = " << rpn_expr << "\n"; } catch (std::exception e) { std::cerr << "error: " << e.what() << "\n"; return 1; }
from collections import namedtuple from pprint import pprint as pp OpInfo = namedtuple('OpInfo', 'prec assoc') L, R = 'Left Right'.split() ops = { '^': OpInfo(prec=4, assoc=R), '*': OpInfo(prec=3, assoc=L), '/': OpInfo(prec=3, assoc=L), '+': OpInfo(prec=2, assoc=L), '-': OpInfo(prec=2, assoc=L), '(': OpInfo(prec=9, assoc=L), ')': OpInfo(prec=0, assoc=L), } NUM, LPAREN, RPAREN = 'NUMBER ( )'.split() def get_input(inp = None): 'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)' if inp is None: inp = input('expression: ') tokens = inp.strip().split() tokenvals = [] for token in tokens: if token in ops: tokenvals.append((token, ops[token])) else: tokenvals.append((NUM, token)) return tokenvals def shunting(tokenvals): outq, stack = [], [] table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')] for token, val in tokenvals: note = action = '' if token is NUM: action = 'Add number to output' outq.append(val) table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) elif token in ops: t1, (p1, a1) = token, val v = t1 note = 'Pop ops from stack to output' while stack: t2, (p2, a2) = stack[-1] if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2): if t1 != RPAREN: if t2 != LPAREN: stack.pop() action = '(Pop op)' outq.append(t2) else: break else: if t2 != LPAREN: stack.pop() action = '(Pop op)' outq.append(t2) else: stack.pop() action = '(Pop & discard "(")' table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) break table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) v = note = '' else: note = '' break note = '' note = '' if t1 != RPAREN: stack.append((token, val)) action = 'Push op token to stack' else: action = 'Discard ")"' table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) note = 'Drain stack to output' while stack: v = '' t2, (p2, a2) = stack[-1] action = '(Pop op)' stack.pop() outq.append(t2) table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) v = note = '' return table if __name__ == '__main__': infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3' print( 'For infix expression: %r\n' % infix ) rp = shunting(get_input(infix)) maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)] row = rp[0] print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row))) for row in rp[1:]: print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row))) print('\n The final output RPN is: %r' % rp[-1][2])
Preserve the algorithm and functionality while converting the code from C++ to Python.
#include <iostream> #include <cmath> #include <vector> #include <algorithm> #include <iomanip> int main( ) { std::vector<double> input( 11 ) , results( 11 ) ; std::cout << "Please enter 11 numbers!\n" ; for ( int i = 0 ; i < input.size( ) ; i++ ) std::cin >> input[i]; std::transform( input.begin( ) , input.end( ) , results.begin( ) , [ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ; for ( int i = 10 ; i > -1 ; i-- ) { std::cout << "f( " << std::setw( 3 ) << input[ i ] << " ) : " ; if ( results[ i ] > 400 ) std::cout << "too large!" ; else std::cout << results[ i ] << " !" ; std::cout << std::endl ; } return 0 ; }
Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> def f(x): return abs(x) ** 0.5 + 5 * x**3 >>> print(', '.join('%s:%s' % (x, v if v<=400 else "TOO LARGE!") for x,v in ((y, f(float(y))) for y in input('\nnumbers: ').strip().split()[:11][::-1]))) 11 numbers: 1 2 3 4 5 6 7 8 9 10 11 11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0 >>>
Preserve the algorithm and functionality while converting the code from C++ to Python.
#include <iostream> std::string middleThreeDigits(int n) { auto number = std::to_string(std::abs(n)); auto length = number.size(); if (length < 3) { return "less than three digits"; } else if (length % 2 == 0) { return "even number of digits"; } else { return number.substr(length / 2 - 1, 3); } } int main() { auto values {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0}; for (auto&& v : values) { std::cout << "middleThreeDigits(" << v << "): " << middleThreeDigits(v) << "\n"; } }
>>> def middle_three_digits(i): s = str(abs(i)) length = len(s) assert length >= 3 and length % 2 == 1, "Need odd and >= 3 digits" mid = length // 2 return s[mid-1:mid+2] >>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345] >>> failing = [1, 2, -1, -10, 2002, -2002, 0] >>> for x in passing + failing: try: answer = middle_three_digits(x) except AssertionError as error: answer = error print("middle_three_digits(%s) returned: %r" % (x, answer)) middle_three_digits(123) returned: '123' middle_three_digits(12345) returned: '234' middle_three_digits(1234567) returned: '345' middle_three_digits(987654321) returned: '654' middle_three_digits(10001) returned: '000' middle_three_digits(-10001) returned: '000' middle_three_digits(-123) returned: '123' middle_three_digits(-100) returned: '100' middle_three_digits(100) returned: '100' middle_three_digits(-12345) returned: '234' middle_three_digits(1) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(2) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-1) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-10) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(2002) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(-2002) returned: AssertionError('Need odd and >= 3 digits',) middle_three_digits(0) returned: AssertionError('Need odd and >= 3 digits',) >>>
Keep all operations the same but rewrite the snippet in Python.
#include <iostream> #include <vector> std::vector<int> smallPrimes; bool is_prime(size_t test) { if (test < 2) { return false; } if (test % 2 == 0) { return test == 2; } for (size_t d = 3; d * d <= test; d += 2) { if (test % d == 0) { return false; } } return true; } void init_small_primes(size_t numPrimes) { smallPrimes.push_back(2); int count = 0; for (size_t n = 3; count < numPrimes; n += 2) { if (is_prime(n)) { smallPrimes.push_back(n); count++; } } } size_t divisor_count(size_t n) { size_t count = 1; while (n % 2 == 0) { n /= 2; count++; } for (size_t d = 3; d * d <= n; d += 2) { size_t q = n / d; size_t r = n % d; size_t dc = 0; while (r == 0) { dc += count; n = q; q = n / d; r = n % d; } count += dc; } if (n != 1) { count *= 2; } return count; } uint64_t OEISA073916(size_t n) { if (is_prime(n)) { return (uint64_t) pow(smallPrimes[n - 1], n - 1); } size_t count = 0; uint64_t result = 0; for (size_t i = 1; count < n; i++) { if (n % 2 == 1) { size_t root = (size_t) sqrt(i); if (root * root != i) { continue; } } if (divisor_count(i) == n) { count++; result = i; } } return result; } int main() { const int MAX = 15; init_small_primes(MAX); for (size_t n = 1; n <= MAX; n++) { if (n == 13) { std::cout << "A073916(" << n << ") = One more bit needed to represent result.\n"; } else { std::cout << "A073916(" << n << ") = " << OEISA073916(n) << '\n'; } } return 0; }
def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n % ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs)) def is_prime(n): return len(divisors(n)) == 2 def primes(): ii = 1 while True: ii += 1 if is_prime(ii): yield ii def prime(n): generator = primes() for ii in range(n - 1): generator.__next__() return generator.__next__() def n_divisors(n): ii = 0 while True: ii += 1 if len(divisors(ii)) == n: yield ii def sequence(max_n=None): if max_n is not None: for ii in range(1, max_n + 1): if is_prime(ii): yield prime(ii) ** (ii - 1) else: generator = n_divisors(ii) for jj, out in zip(range(ii - 1), generator): pass yield generator.__next__() else: ii = 1 while True: ii += 1 if is_prime(ii): yield prime(ii) ** (ii - 1) else: generator = n_divisors(ii) for jj, out in zip(range(ii - 1), generator): pass yield generator.__next__() if __name__ == '__main__': for item in sequence(15): print(item)
Please provide an equivalent version of this C++ code in Python.
#include <iostream> #define MAX 15 using namespace std; int count_divisors(int n) { int count = 0; for (int i = 1; i * i <= n; ++i) { if (!(n % i)) { if (i == n / i) count++; else count += 2; } } return count; } int main() { int i, k, n, seq[MAX]; for (i = 0; i < MAX; ++i) seq[i] = 0; cout << "The first " << MAX << " terms of the sequence are:" << endl; for (i = 1, n = 0; n < MAX; ++i) { k = count_divisors(i); if (k <= MAX && seq[k - 1] == 0) { seq[k - 1] = i; ++n; } } for (i = 0; i < MAX; ++i) cout << seq[i] << " "; cout << endl; return 0; }
def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n % ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs)) def sequence(max_n=None): n = 0 while True: n += 1 ii = 0 if max_n is not None: if n > max_n: break while True: ii += 1 if len(divisors(ii)) == n: yield ii break if __name__ == '__main__': for item in sequence(15): print(item)
Write the same algorithm in Python as shown in this C++ implementation.
#include <iomanip> #include <iostream> int pancake(int n) { int gap = 2, sum = 2, adj = -1; while (sum < n) { adj++; gap = gap * 2 - 1; sum += gap; } return n + adj; } int main() { for (int i = 0; i < 4; i++) { for (int j = 1; j < 6; j++) { int n = i * 5 + j; std::cout << "p(" << std::setw(2) << n << ") = " << std::setw(2) << pancake(n) << " "; } std::cout << '\n'; } return 0; }
import time from collections import deque from operator import itemgetter from typing import Tuple Pancakes = Tuple[int, ...] def flip(pancakes: Pancakes, position: int) -> Pancakes: return tuple([*reversed(pancakes[:position]), *pancakes[position:]]) def pancake(n: int) -> Tuple[Pancakes, int]: init_stack = tuple(range(1, n + 1)) stack_flips = {init_stack: 0} queue = deque([init_stack]) while queue: stack = queue.popleft() flips = stack_flips[stack] + 1 for i in range(2, n + 1): flipped = flip(stack, i) if flipped not in stack_flips: stack_flips[flipped] = flips queue.append(flipped) return max(stack_flips.items(), key=itemgetter(1)) if __name__ == "__main__": start = time.time() for n in range(1, 10): pancakes, p = pancake(n) print(f"pancake({n}) = {p:>2}. Example: {list(pancakes)}") print(f"\nTook {time.time() - start:.3} seconds.")
Convert this C++ block to Python, preserving its control flow and logic.
#include <ctime> #include <iostream> #include <string> #include <algorithm> class chessBoard { public: void generateRNDBoard( int brds ) { int a, b, i; char c; for( int cc = 0; cc < brds; cc++ ) { memset( brd, 0, 64 ); std::string pieces = "PPPPPPPPNNBBRRQKppppppppnnbbrrqk"; random_shuffle( pieces.begin(), pieces.end() ); while( pieces.length() ) { i = rand() % pieces.length(); c = pieces.at( i ); while( true ) { a = rand() % 8; b = rand() % 8; if( brd[a][b] == 0 ) { if( c == 'P' && !b || c == 'p' && b == 7 || ( ( c == 'K' || c == 'k' ) && search( c == 'k' ? 'K' : 'k', a, b ) ) ) continue; break; } } brd[a][b] = c; pieces = pieces.substr( 0, i ) + pieces.substr( i + 1 ); } print(); } } private: bool search( char c, int a, int b ) { for( int y = -1; y < 2; y++ ) { for( int x = -1; x < 2; x++ ) { if( !x && !y ) continue; if( a + x > -1 && a + x < 8 && b + y >-1 && b + y < 8 ) { if( brd[a + x][b + y] == c ) return true; } } } return false; } void print() { int e = 0; for( int y = 0; y < 8; y++ ) { for( int x = 0; x < 8; x++ ) { if( brd[x][y] == 0 ) e++; else { if( e > 0 ) { std::cout << e; e = 0; } std::cout << brd[x][y]; } } if( e > 0 ) { std::cout << e; e = 0; } if( y < 7 ) std::cout << "/"; } std::cout << " w - - 0 1\n\n"; for( int y = 0; y < 8; y++ ) { for( int x = 0; x < 8; x++ ) { if( brd[x][y] == 0 ) std::cout << "."; else std::cout << brd[x][y]; } std::cout << "\n"; } std::cout << "\n\n"; } char brd[8][8]; }; int main( int argc, char* argv[] ) { srand( ( unsigned )time( 0 ) ); chessBoard c; c.generateRNDBoard( 2 ); return 0; }
import random board = [[" " for x in range(8)] for y in range(8)] piece_list = ["R", "N", "B", "Q", "P"] def place_kings(brd): while True: rank_white, file_white, rank_black, file_black = random.randint(0,7), random.randint(0,7), random.randint(0,7), random.randint(0,7) diff_list = [abs(rank_white - rank_black), abs(file_white - file_black)] if sum(diff_list) > 2 or set(diff_list) == set([0, 2]): brd[rank_white][file_white], brd[rank_black][file_black] = "K", "k" break def populate_board(brd, wp, bp): for x in range(2): if x == 0: piece_amount = wp pieces = piece_list else: piece_amount = bp pieces = [s.lower() for s in piece_list] while piece_amount != 0: piece_rank, piece_file = random.randint(0, 7), random.randint(0, 7) piece = random.choice(pieces) if brd[piece_rank][piece_file] == " " and pawn_on_promotion_square(piece, piece_rank) == False: brd[piece_rank][piece_file] = piece piece_amount -= 1 def fen_from_board(brd): fen = "" for x in brd: n = 0 for y in x: if y == " ": n += 1 else: if n != 0: fen += str(n) fen += y n = 0 if n != 0: fen += str(n) fen += "/" if fen.count("/") < 7 else "" fen += " w - - 0 1\n" return fen def pawn_on_promotion_square(pc, pr): if pc == "P" and pr == 0: return True elif pc == "p" and pr == 7: return True return False def start(): piece_amount_white, piece_amount_black = random.randint(0, 15), random.randint(0, 15) place_kings(board) populate_board(board, piece_amount_white, piece_amount_black) print(fen_from_board(board)) for x in board: print(x) start()
Convert this C++ block to Python, preserving its control flow and logic.
#include <functional> #include <iostream> #include <sstream> #include <vector> std::string to(int n, int b) { static auto BASE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; std::stringstream ss; while (n > 0) { auto rem = n % b; n = n / b; ss << BASE[rem]; } auto fwd = ss.str(); return std::string(fwd.rbegin(), fwd.rend()); } uint64_t uabs(uint64_t a, uint64_t b) { if (a < b) { return b - a; } return a - b; } bool isEsthetic(uint64_t n, uint64_t b) { if (n == 0) { return false; } auto i = n % b; n /= b; while (n > 0) { auto j = n % b; if (uabs(i, j) != 1) { return false; } n /= b; i = j; } return true; } void listEsths(uint64_t n, uint64_t n2, uint64_t m, uint64_t m2, int perLine, bool all) { std::vector<uint64_t> esths; const auto dfs = [&esths](uint64_t n, uint64_t m, uint64_t i) { auto dfs_impl = [&esths](uint64_t n, uint64_t m, uint64_t i, auto &dfs_ref) { if (i >= n && i <= m) { esths.push_back(i); } if (i == 0 || i > m) { return; } auto d = i % 10; auto i1 = i * 10 + d - 1; auto i2 = i1 + 2; if (d == 0) { dfs_ref(n, m, i2, dfs_ref); } else if (d == 9) { dfs_ref(n, m, i1, dfs_ref); } else { dfs_ref(n, m, i1, dfs_ref); dfs_ref(n, m, i2, dfs_ref); } }; dfs_impl(n, m, i, dfs_impl); }; for (int i = 0; i < 10; i++) { dfs(n2, m2, i); } auto le = esths.size(); printf("Base 10: %d esthetic numbers between %llu and %llu:\n", le, n, m); if (all) { for (size_t c = 0; c < esths.size(); c++) { auto esth = esths[c]; printf("%llu ", esth); if ((c + 1) % perLine == 0) { printf("\n"); } } printf("\n"); } else { for (int c = 0; c < perLine; c++) { auto esth = esths[c]; printf("%llu ", esth); } printf("\n............\n"); for (size_t i = le - perLine; i < le; i++) { auto esth = esths[i]; printf("%llu ", esth); } printf("\n"); } printf("\n"); } int main() { for (int b = 2; b <= 16; b++) { printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4 * b, 6 * b); for (int n = 1, c = 0; c < 6 * b; n++) { if (isEsthetic(n, b)) { c++; if (c >= 4 * b) { std::cout << to(n, b) << ' '; } } } printf("\n"); } printf("\n"); listEsths(1000, 1010, 9999, 9898, 16, true); listEsths((uint64_t)1e8, 101'010'101, 13 * (uint64_t)1e7, 123'456'789, 9, true); listEsths((uint64_t)1e11, 101'010'101'010, 13 * (uint64_t)1e10, 123'456'789'898, 7, false); listEsths((uint64_t)1e14, 101'010'101'010'101, 13 * (uint64_t)1e13, 123'456'789'898'989, 5, false); listEsths((uint64_t)1e17, 101'010'101'010'101'010, 13 * (uint64_t)1e16, 123'456'789'898'989'898, 4, false); return 0; }
from collections import deque from itertools import dropwhile, islice, takewhile from textwrap import wrap from typing import Iterable, Iterator Digits = str def esthetic_nums(base: int) -> Iterator[int]: queue: deque[tuple[int, int]] = deque() queue.extendleft((d, d) for d in range(1, base)) while True: num, lsd = queue.pop() yield num new_lsds = (d for d in (lsd - 1, lsd + 1) if 0 <= d < base) num *= base queue.extendleft((num + d, d) for d in new_lsds) def to_digits(num: int, base: int) -> Digits: digits: list[str] = [] while num: num, d = divmod(num, base) digits.append("0123456789abcdef"[d]) return "".join(reversed(digits)) if digits else "0" def pprint_it(it: Iterable[str], indent: int = 4, width: int = 80) -> None: joined = ", ".join(it) lines = wrap(joined, width=width - indent) for line in lines: print(f"{indent*' '}{line}") print() def task_2() -> None: nums: Iterator[int] for base in range(2, 16 + 1): start, stop = 4 * base, 6 * base nums = esthetic_nums(base) nums = islice(nums, start - 1, stop) print( f"Base-{base} esthetic numbers from " f"index {start} through index {stop} inclusive:\n" ) pprint_it(to_digits(num, base) for num in nums) def task_3(lower: int, upper: int, base: int = 10) -> None: nums: Iterator[int] = esthetic_nums(base) nums = dropwhile(lambda num: num < lower, nums) nums = takewhile(lambda num: num <= upper, nums) print( f"Base-{base} esthetic numbers with " f"magnitude between {lower:,} and {upper:,}:\n" ) pprint_it(to_digits(num, base) for num in nums) if __name__ == "__main__": print("======\nTask 2\n======\n") task_2() print("======\nTask 3\n======\n") task_3(1_000, 9_999) print("======\nTask 4\n======\n") task_3(100_000_000, 130_000_000)
Change the programming language of this snippet from C++ to Python without modifying what it does.
#include <iostream> #include <vector> #include <numeric> #include <algorithm> int topswops(int n) { std::vector<int> list(n); std::iota(std::begin(list), std::end(list), 1); int max_steps = 0; do { auto temp_list = list; for (int steps = 1; temp_list[0] != 1; ++steps) { std::reverse(std::begin(temp_list), std::begin(temp_list) + temp_list[0]); if (steps > max_steps) max_steps = steps; } } while (std::next_permutation(std::begin(list), std::end(list))); return max_steps; } int main() { for (int i = 1; i <= 10; ++i) { std::cout << i << ": " << topswops(i) << std::endl; } return 0; }
>>> from itertools import permutations >>> def f1(p): i = 0 while True: p0 = p[0] if p0 == 1: break p[:p0] = p[:p0][::-1] i += 1 return i >>> def fannkuch(n): return max(f1(list(p)) for p in permutations(range(1, n+1))) >>> for n in range(1, 11): print(n,fannkuch(n)) 1 0 2 1 3 2 4 4 5 7 6 10 7 16 8 22 9 30 10 38 >>>
Convert this C++ block to Python, preserving its control flow and logic.
#include <iostream> #include <iomanip> using namespace std; class ormConverter { public: ormConverter() : AR( 0.7112f ), CE( 0.01f ), DI( 0.0254f ), FU( 0.3048f ), KI( 1000.0f ), LI( 0.00254f ), ME( 1.0f ), MI( 7467.6f ), PI( 0.1778f ), SA( 2.1336f ), TO( 0.000254f ), VE( 0.04445f ), VR( 1066.8f ) {} void convert( char c, float l ) { system( "cls" ); cout << endl << l; switch( c ) { case 'A': cout << " Arshin to:"; l *= AR; break; case 'C': cout << " Centimeter to:"; l *= CE; break; case 'D': cout << " Diuym to:"; l *= DI; break; case 'F': cout << " Fut to:"; l *= FU; break; case 'K': cout << " Kilometer to:"; l *= KI; break; case 'L': cout << " Liniya to:"; l *= LI; break; case 'M': cout << " Meter to:"; l *= ME; break; case 'I': cout << " Milia to:"; l *= MI; break; case 'P': cout << " Piad to:"; l *= PI; break; case 'S': cout << " Sazhen to:"; l *= SA; break; case 'T': cout << " Tochka to:"; l *= TO; break; case 'V': cout << " Vershok to:"; l *= VE; break; case 'E': cout << " Versta to:"; l *= VR; } float ar = l / AR, ce = l / CE, di = l / DI, fu = l / FU, ki = l / KI, li = l / LI, me = l / ME, mi = l / MI, pi = l / PI, sa = l / SA, to = l / TO, ve = l / VE, vr = l / VR; cout << left << endl << "=================" << endl << setw( 12 ) << "Arshin:" << ar << endl << setw( 12 ) << "Centimeter:" << ce << endl << setw( 12 ) << "Diuym:" << di << endl << setw( 12 ) << "Fut:" << fu << endl << setw( 12 ) << "Kilometer:" << ki << endl << setw( 12 ) << "Liniya:" << li << endl << setw( 12 ) << "Meter:" << me << endl << setw( 12 ) << "Milia:" << mi << endl << setw( 12 ) << "Piad:" << pi << endl << setw( 12 ) << "Sazhen:" << sa << endl << setw( 12 ) << "Tochka:" << to << endl << setw( 12 ) << "Vershok:" << ve << endl << setw( 12 ) << "Versta:" << vr << endl << endl << endl; } private: const float AR, CE, DI, FU, KI, LI, ME, MI, PI, SA, TO, VE, VR; }; int _tmain(int argc, _TCHAR* argv[]) { ormConverter c; char s; float l; while( true ) { cout << "What unit:\n(A)rshin, (C)entimeter, (D)iuym, (F)ut\n(K)ilometer, (L)iniya, (M)eter, m(I)lia, (P)iad\n(S)azhen, (T)ochka, (V)ershok, v(E)rsta, (Q)uit\n"; cin >> s; if( s & 32 ) s ^= 32; if( s == 'Q' ) return 0; cout << "Length (0 to Quit): "; cin >> l; if( l == 0 ) return 0; c.convert( s, l ); system( "pause" ); system( "cls" ); } return 0; }
from sys import argv unit2mult = {"arshin": 0.7112, "centimeter": 0.01, "diuym": 0.0254, "fut": 0.3048, "kilometer": 1000.0, "liniya": 0.00254, "meter": 1.0, "milia": 7467.6, "piad": 0.1778, "sazhen": 2.1336, "tochka": 0.000254, "vershok": 0.04445, "versta": 1066.8} if __name__ == '__main__': assert len(argv) == 3, 'ERROR. Need two arguments - number then units' try: value = float(argv[1]) except: print('ERROR. First argument must be a (float) number') raise unit = argv[2] assert unit in unit2mult, ( 'ERROR. Only know the following units: ' + ' '.join(unit2mult.keys()) ) print("%g %s to:" % (value, unit)) for unt, mlt in sorted(unit2mult.items()): print(' %10s: %g' % (unt, value * unit2mult[unit] / mlt))
Write the same code in Python as shown below in C++.
#include <iostream> #include <ctime> class CRateState { protected: time_t m_lastFlush; time_t m_period; size_t m_tickCount; public: CRateState(time_t period); void Tick(); }; CRateState::CRateState(time_t period) : m_lastFlush(std::time(NULL)), m_period(period), m_tickCount(0) { } void CRateState::Tick() { m_tickCount++; time_t now = std::time(NULL); if((now - m_lastFlush) >= m_period) { size_t tps = 0.0; if(m_tickCount > 0) tps = m_tickCount / (now - m_lastFlush); std::cout << tps << " tics per second" << std::endl; m_tickCount = 0; m_lastFlush = now; } } void something_we_do() { volatile size_t anchor = 0; for(size_t x = 0; x < 0xffff; ++x) { anchor = x; } } int main() { time_t start = std::time(NULL); CRateState rateWatch(5); for(time_t latest = start; (latest - start) < 20; latest = std::time(NULL)) { something_we_do(); rateWatch.Tick(); } return 0; }
import subprocess import time class Tlogger(object): def __init__(self): self.counts = 0 self.tottime = 0.0 self.laststart = 0.0 self.lastreport = time.time() def logstart(self): self.laststart = time.time() def logend(self): self.counts +=1 self.tottime += (time.time()-self.laststart) if (time.time()-self.lastreport)>5.0: self.report() def report(self): if ( self.counts > 4*self.tottime): print "Subtask execution rate: %f times/second"% (self.counts/self.tottime); else: print "Average execution time: %f seconds"%(self.tottime/self.counts); self.lastreport = time.time() def taskTimer( n, subproc_args ): logger = Tlogger() for x in range(n): logger.logstart() p = subprocess.Popen(subproc_args) p.wait() logger.logend() logger.report() import timeit import sys def main( ): s = timer = timeit.Timer(s) rzlts = timer.repeat(5, 5000) for t in rzlts: print "Time for 5000 executions of statement = ",t print " print "Command:",sys.argv[2:] print "" for k in range(3): taskTimer( int(sys.argv[1]), sys.argv[2:]) main()
Convert this C++ block to Python, preserving its control flow and logic.
#include <iostream> #define MAX 15 using namespace std; int count_divisors(int n) { int count = 0; for (int i = 1; i * i <= n; ++i) { if (!(n % i)) { if (i == n / i) count++; else count += 2; } } return count; } int main() { cout << "The first " << MAX << " terms of the sequence are:" << endl; for (int i = 1, next = 1; next <= MAX; ++i) { if (next == count_divisors(i)) { cout << i << " "; next++; } } cout << endl; return 0; }
def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n % ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs)) def sequence(max_n=None): previous = 0 n = 0 while True: n += 1 ii = previous if max_n is not None: if n > max_n: break while True: ii += 1 if len(divisors(ii)) == n: yield ii previous = ii break if __name__ == '__main__': for item in sequence(15): print(item)
Convert this C++ block to Python, preserving its control flow and logic.
#include <iostream> #include <map> #include <cmath> int pRec(int n) { static std::map<int,int> memo; auto it = memo.find(n); if (it != memo.end()) return it->second; if (n <= 2) memo[n] = 1; else memo[n] = pRec(n-2) + pRec(n-3); return memo[n]; } int pFloor(int n) { long const double p = 1.324717957244746025960908854; long const double s = 1.0453567932525329623; return std::pow(p, n-1)/s + 0.5; } std::string& lSystem(int n) { static std::map<int,std::string> memo; auto it = memo.find(n); if (it != memo.end()) return it->second; if (n == 0) memo[n] = "A"; else { memo[n] = ""; for (char ch : memo[n-1]) { switch(ch) { case 'A': memo[n].push_back('B'); break; case 'B': memo[n].push_back('C'); break; case 'C': memo[n].append("AB"); break; } } } return memo[n]; } using pFn = int(*)(int); void compare(pFn f1, pFn f2, const char* descr, int stop) { std::cout << "The " << descr << " functions "; int i; for (i=0; i<stop; i++) { int n1 = f1(i); int n2 = f2(i); if (n1 != n2) { std::cout << "do not match at " << i << ": " << n1 << " != " << n2 << ".\n"; break; } } if (i == stop) { std::cout << "match from P_0 to P_" << stop << ".\n"; } } int main() { std::cout << "P_0 .. P_19: "; for (int i=0; i<20; i++) std::cout << pRec(i) << " "; std::cout << "\n"; compare(pFloor, pRec, "floor- and recurrence-based", 64); std::cout << "\nThe first 10 L-system strings are:\n"; for (int i=0; i<10; i++) std::cout << lSystem(i) << "\n"; std::cout << "\n"; compare(pFloor, [](int n){return (int)lSystem(n).length();}, "floor- and L-system-based", 32); return 0; }
from math import floor from collections import deque from typing import Dict, Generator def padovan_r() -> Generator[int, None, None]: last = deque([1, 1, 1], 4) while True: last.append(last[-2] + last[-3]) yield last.popleft() _p, _s = 1.324717957244746025960908854, 1.0453567932525329623 def padovan_f(n: int) -> int: return floor(_p**(n-1) / _s + .5) def padovan_l(start: str='A', rules: Dict[str, str]=dict(A='B', B='C', C='AB') ) -> Generator[str, None, None]: axiom = start while True: yield axiom axiom = ''.join(rules[ch] for ch in axiom) if __name__ == "__main__": from itertools import islice print("The first twenty terms of the sequence.") print(str([padovan_f(n) for n in range(20)])[1:-1]) r_generator = padovan_r() if all(next(r_generator) == padovan_f(n) for n in range(64)): print("\nThe recurrence and floor based algorithms match to n=63 .") else: print("\nThe recurrence and floor based algorithms DIFFER!") print("\nThe first 10 L-system string-lengths and strings") l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB')) print('\n'.join(f" {len(string):3} {repr(string)}" for string in islice(l_generator, 10))) r_generator = padovan_r() l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB')) if all(len(next(l_generator)) == padovan_f(n) == next(r_generator) for n in range(32)): print("\nThe L-system, recurrence and floor based algorithms match to n=31 .") else: print("\nThe L-system, recurrence and floor based algorithms DIFFER!")
Change the following C++ code into Python without altering its purpose.
#include <windows.h> #include <string> #include <iostream> const int BMP_SIZE = 720, LINE_LEN = 120, BORDER = 100; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( std::string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb; GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class tree { public: tree() { bmp.create( BMP_SIZE, BMP_SIZE ); bmp.clear(); clr[0] = RGB( 90, 30, 0 ); clr[1] = RGB( 255, 255, 0 ); clr[2] = RGB( 0, 255, 255 ); clr[3] = RGB( 255, 255, 255 ); clr[4] = RGB( 255, 0, 0 ); clr[5] = RGB( 0, 100, 190 ); } void draw( int it, POINT a, POINT b ) { if( !it ) return; bmp.setPenColor( clr[it % 6] ); POINT df = { b.x - a.x, a.y - b.y }; POINT c = { b.x - df.y, b.y - df.x }; POINT d = { a.x - df.y, a.y - df.x }; POINT e = { d.x + ( ( df.x - df.y ) / 2 ), d.y - ( ( df.x + df.y ) / 2 )}; drawSqr( a, b, c, d ); draw( it - 1, d, e ); draw( it - 1, e, c ); } void save( std::string p ) { bmp.saveBitmap( p ); } private: void drawSqr( POINT a, POINT b, POINT c, POINT d ) { HDC dc = bmp.getDC(); MoveToEx( dc, a.x, a.y, NULL ); LineTo( dc, b.x, b.y ); LineTo( dc, c.x, c.y ); LineTo( dc, d.x, d.y ); LineTo( dc, a.x, a.y ); } myBitmap bmp; DWORD clr[6]; }; int main( int argc, char* argv[] ) { POINT ptA = { ( BMP_SIZE >> 1 ) - ( LINE_LEN >> 1 ), BMP_SIZE - BORDER }, ptB = { ptA.x + LINE_LEN, ptA.y }; tree t; t.draw( 12, ptA, ptB ); t.save( "?:/pt.bmp" ); return 0; }
def setup(): size(800, 400) background(255) stroke(0, 255, 0) tree(width / 2.3, height, width / 1.8, height, 10) def tree(x1, y1, x2, y2, depth): if depth <= 0: return dx = (x2 - x1) dy = (y1 - y2) x3 = (x2 - dy) y3 = (y2 - dx) x4 = (x1 - dy) y4 = (y1 - dx) x5 = (x4 + 0.5 * (dx - dy)) y5 = (y4 - 0.5 * (dx + dy)) beginShape() fill(0.0, 255.0 / depth, 0.0) vertex(x1, y1) vertex(x2, y2) vertex(x3, y3) vertex(x4, y4) vertex(x1, y1) endShape() beginShape() fill(0.0, 255.0 / depth, 0.0) vertex(x3, y3) vertex(x4, y4) vertex(x5, y5) vertex(x3, y3) endShape() tree(x4, y4, x5, y5, depth - 1) tree(x5, y5, x3, y3, depth - 1)
Translate the given C++ code snippet into Python without altering its behavior.
#include <iostream> #include <cctype> #include <functional> using namespace std; bool odd() { function<void ()> prev = []{}; while(true) { int c = cin.get(); if (!isalpha(c)) { prev(); cout.put(c); return c != '.'; } prev = [=] { cout.put(c); prev(); }; } } bool even() { while(true) { int c; cout.put(c = cin.get()); if (!isalpha(c)) return c != '.'; } } int main() { bool e = false; while( e ? odd() : even() ) e = !e; return 0; }
from sys import stdin, stdout def char_in(): return stdin.read(1) def char_out(c): stdout.write(c) def odd(prev = lambda: None): a = char_in() if not a.isalpha(): prev() char_out(a) return a != '.' def clos(): char_out(a) prev() return odd(clos) def even(): while True: c = char_in() char_out(c) if not c.isalpha(): return c != '.' e = False while odd() if e else even(): e = not e
Translate the given C++ code snippet into Python without altering its behavior.
#include <array> #include <iostream> int64_t mod(int64_t x, int64_t y) { int64_t m = x % y; if (m < 0) { if (y < 0) { return m - y; } else { return m + y; } } return m; } class RNG { private: const std::array<int64_t, 3> a1{ 0, 1403580, -810728 }; const int64_t m1 = (1LL << 32) - 209; std::array<int64_t, 3> x1; const std::array<int64_t, 3> a2{ 527612, 0, -1370589 }; const int64_t m2 = (1LL << 32) - 22853; std::array<int64_t, 3> x2; const int64_t d = (1LL << 32) - 209 + 1; public: void seed(int64_t state) { x1 = { state, 0, 0 }; x2 = { state, 0, 0 }; } int64_t next_int() { int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1); int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2); int64_t z = mod(x1i - x2i, m1); x1 = { x1i, x1[0], x1[1] }; x2 = { x2i, x2[0], x2[1] }; return z + 1; } double next_float() { return static_cast<double>(next_int()) / d; } }; int main() { RNG rng; 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 (size_t i = 0; i < 100000; i++) { auto value = floor(rng.next_float() * 5.0); counts[value]++; } for (size_t i = 0; i < counts.size(); i++) { std::cout << i << ": " << counts[i] << '\n'; } return 0; }
a1 = [0, 1403580, -810728] m1 = 2**32 - 209 a2 = [527612, 0, -1370589] m2 = 2**32 - 22853 d = m1 + 1 class MRG32k3a(): def __init__(self, seed_state=123): self.seed(seed_state) def seed(self, seed_state): assert 0 <seed_state < d, f"Out of Range 0 x < {d}" self.x1 = [seed_state, 0, 0] self.x2 = [seed_state, 0, 0] def next_int(self): "return random int in range 0..d" x1i = sum(aa * xx for aa, xx in zip(a1, self.x1)) % m1 x2i = sum(aa * xx for aa, xx in zip(a2, self.x2)) % m2 self.x1 = [x1i] + self.x1[:2] self.x2 = [x2i] + self.x2[:2] z = (x1i - x2i) % m1 answer = (z + 1) return answer def next_float(self): "return random float between 0 and 1" return self.next_int() / d if __name__ == '__main__': random_gen = MRG32k3a() 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)
Write the same code in Python as shown below in C++.
#include <iostream> #include <iomanip> #include <algorithm> #include <vector> unsigned gcd( unsigned i, unsigned j ) { return i ? i < j ? gcd( j % i, i ) : gcd( i % j, j ) : j; } void createSequence( std::vector<unsigned>& seq, int c ) { if( 1500 == seq.size() ) return; unsigned t = seq.at( c ) + seq.at( c + 1 ); seq.push_back( t ); seq.push_back( seq.at( c + 1 ) ); createSequence( seq, c + 1 ); } int main( int argc, char* argv[] ) { std::vector<unsigned> seq( 2, 1 ); createSequence( seq, 0 ); std::cout << "First fifteen members of the sequence:\n "; for( unsigned x = 0; x < 15; x++ ) { std::cout << seq[x] << " "; } std::cout << "\n\n"; for( unsigned x = 1; x < 11; x++ ) { std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), x ); if( i != seq.end() ) { std::cout << std::setw( 3 ) << x << " is at pos. #" << 1 + distance( seq.begin(), i ) << "\n"; } } std::cout << "\n"; std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), 100 ); if( i != seq.end() ) { std::cout << 100 << " is at pos. #" << 1 + distance( seq.begin(), i ) << "\n"; } std::cout << "\n"; unsigned g; bool f = false; for( int x = 0, y = 1; x < 1000; x++, y++ ) { g = gcd( seq[x], seq[y] ); if( g != 1 ) f = true; std::cout << std::setw( 4 ) << x + 1 << ": GCD (" << seq[x] << ", " << seq[y] << ") = " << g << ( g != 1 ? " <-- ERROR\n" : "\n" ); } std::cout << "\n" << ( f ? "THERE WERE ERRORS --- NOT ALL GCDs ARE '1'!" : "CORRECT: ALL GCDs ARE '1'!" ) << "\n\n"; return 0; }
def stern_brocot(predicate=lambda series: len(series) < 20): sb, i = [1, 1], 0 while predicate(sb): sb += [sum(sb[i:i + 2]), sb[i + 1]] i += 1 return sb if __name__ == '__main__': from fractions import gcd n_first = 15 print('The first %i values:\n ' % n_first, stern_brocot(lambda series: len(series) < n_first)[:n_first]) print() n_max = 10 for n_occur in list(range(1, n_max + 1)) + [100]: print('1-based index of the first occurrence of %3i in the series:' % n_occur, stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1) print() n_gcd = 1000 s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd] assert all(gcd(prev, this) == 1 for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'
Write the same code in Python as shown below in C++.
#include <iostream> #include <iomanip> #include <algorithm> #include <vector> unsigned gcd( unsigned i, unsigned j ) { return i ? i < j ? gcd( j % i, i ) : gcd( i % j, j ) : j; } void createSequence( std::vector<unsigned>& seq, int c ) { if( 1500 == seq.size() ) return; unsigned t = seq.at( c ) + seq.at( c + 1 ); seq.push_back( t ); seq.push_back( seq.at( c + 1 ) ); createSequence( seq, c + 1 ); } int main( int argc, char* argv[] ) { std::vector<unsigned> seq( 2, 1 ); createSequence( seq, 0 ); std::cout << "First fifteen members of the sequence:\n "; for( unsigned x = 0; x < 15; x++ ) { std::cout << seq[x] << " "; } std::cout << "\n\n"; for( unsigned x = 1; x < 11; x++ ) { std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), x ); if( i != seq.end() ) { std::cout << std::setw( 3 ) << x << " is at pos. #" << 1 + distance( seq.begin(), i ) << "\n"; } } std::cout << "\n"; std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), 100 ); if( i != seq.end() ) { std::cout << 100 << " is at pos. #" << 1 + distance( seq.begin(), i ) << "\n"; } std::cout << "\n"; unsigned g; bool f = false; for( int x = 0, y = 1; x < 1000; x++, y++ ) { g = gcd( seq[x], seq[y] ); if( g != 1 ) f = true; std::cout << std::setw( 4 ) << x + 1 << ": GCD (" << seq[x] << ", " << seq[y] << ") = " << g << ( g != 1 ? " <-- ERROR\n" : "\n" ); } std::cout << "\n" << ( f ? "THERE WERE ERRORS --- NOT ALL GCDs ARE '1'!" : "CORRECT: ALL GCDs ARE '1'!" ) << "\n\n"; return 0; }
def stern_brocot(predicate=lambda series: len(series) < 20): sb, i = [1, 1], 0 while predicate(sb): sb += [sum(sb[i:i + 2]), sb[i + 1]] i += 1 return sb if __name__ == '__main__': from fractions import gcd n_first = 15 print('The first %i values:\n ' % n_first, stern_brocot(lambda series: len(series) < n_first)[:n_first]) print() n_max = 10 for n_occur in list(range(1, n_max + 1)) + [100]: print('1-based index of the first occurrence of %3i in the series:' % n_occur, stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1) print() n_gcd = 1000 s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd] assert all(gcd(prev, this) == 1 for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'
Translate the given C++ code snippet into Python without altering its behavior.
#pragma once #include <cmath> #include <string> #include <sstream> #include <iomanip> class Approx { public: Approx(double _v, double _s = 0.0) : v(_v), s(_s) {} operator std::string() const { std::ostringstream os(""); os << std::setprecision(15) << v << " ±" << std::setprecision(15) << s << std::ends; return os.str(); } Approx operator +(const Approx& a) const { return Approx(v + a.v, sqrt(s * s + a.s * a.s)); } Approx operator +(double d) const { return Approx(v + d, s); } Approx operator -(const Approx& a) const { return Approx(v - a.v, sqrt(s * s + a.s * a.s)); } Approx operator -(double d) const { return Approx(v - d, s); } Approx operator *(const Approx& a) const { const double t = v * a.v; return Approx(v, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v))); } Approx operator *(double d) const { return Approx(v * d, fabs(d * s)); } Approx operator /(const Approx& a) const { const double t = v / a.v; return Approx(t, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v))); } Approx operator /(double d) const { return Approx(v / d, fabs(d * s)); } Approx pow(double d) const { const double t = ::pow(v, d); return Approx(t, fabs(t * d * s / v)); } private: double v, s; };
from collections import namedtuple import math class I(namedtuple('Imprecise', 'value, delta')): 'Imprecise type: I(value=0.0, delta=0.0)' __slots__ = () def __new__(_cls, value=0.0, delta=0.0): 'Defaults to 0.0 ± delta' return super().__new__(_cls, float(value), abs(float(delta))) def reciprocal(self): return I(1. / self.value, self.delta / (self.value**2)) def __str__(self): 'Shorter form of Imprecise as string' return 'I(%g, %g)' % self def __neg__(self): return I(-self.value, self.delta) def __add__(self, other): if type(other) == I: return I( self.value + other.value, (self.delta**2 + other.delta**2)**0.5 ) try: c = float(other) except: return NotImplemented return I(self.value + c, self.delta) def __sub__(self, other): return self + (-other) def __radd__(self, other): return I.__add__(self, other) def __mul__(self, other): if type(other) == I: a1,b1 = self a2,b2 = other f = a1 * a2 return I( f, f * ( (b1 / a1)**2 + (b2 / a2)**2 )**0.5 ) try: c = float(other) except: return NotImplemented return I(self.value * c, self.delta * c) def __pow__(self, other): if type(other) == I: return NotImplemented try: c = float(other) except: return NotImplemented f = self.value ** c return I(f, f * c * (self.delta / self.value)) def __rmul__(self, other): return I.__mul__(self, other) def __truediv__(self, other): if type(other) == I: return self.__mul__(other.reciprocal()) try: c = float(other) except: return NotImplemented return I(self.value / c, self.delta / c) def __rtruediv__(self, other): return other * self.reciprocal() __div__, __rdiv__ = __truediv__, __rtruediv__ Imprecise = I def distance(p1, p2): x1, y1 = p1 x2, y2 = p2 return ((x1 - x2)**2 + (y1 - y2)**2)**0.5 x1 = I(100, 1.1) x2 = I(200, 2.2) y1 = I( 50, 1.2) y2 = I(100, 2.3) p1, p2 = (x1, y1), (x2, y2) print("Distance between points\n p1: %s\n and p2: %s\n = %r" % ( p1, p2, distance(p1, p2)))
Rewrite the snippet below in Python so it works the same as the original C++ code.
#include <iostream> #include <vector> std::vector<long> TREE_LIST; std::vector<int> OFFSET; void init() { for (size_t i = 0; i < 32; i++) { if (i == 1) { OFFSET.push_back(1); } else { OFFSET.push_back(0); } } } void append(long t) { TREE_LIST.push_back(1 | (t << 1)); } void show(long t, int l) { while (l-- > 0) { if (t % 2 == 1) { std::cout << '('; } else { std::cout << ')'; } t = t >> 1; } } void listTrees(int n) { for (int i = OFFSET[n]; i < OFFSET[n + 1]; i++) { show(TREE_LIST[i], 2 * n); std::cout << '\n'; } } void assemble(int n, long t, int sl, int pos, int rem) { if (rem == 0) { append(t); return; } auto pp = pos; auto ss = sl; if (sl > rem) { ss = rem; pp = OFFSET[ss]; } else if (pp >= OFFSET[ss + 1]) { ss--; if (ss == 0) { return; } pp = OFFSET[ss]; } assemble(n, t << (2 * ss) | TREE_LIST[pp], ss, pp, rem - ss); assemble(n, t, ss, pp + 1, rem); } void makeTrees(int n) { if (OFFSET[n + 1] != 0) { return; } if (n > 0) { makeTrees(n - 1); } assemble(n, 0, n - 1, OFFSET[n - 1], n - 1); OFFSET[n + 1] = TREE_LIST.size(); } void test(int n) { if (n < 1 || n > 12) { throw std::runtime_error("Argument must be between 1 and 12"); } append(0); makeTrees(n); std::cout << "Number of " << n << "-trees: " << OFFSET[n + 1] - OFFSET[n] << '\n'; listTrees(n); } int main() { init(); test(5); return 0; }
def bags(n,cache={}): if not n: return [(0, "")] upto = sum([bags(x) for x in range(n-1, 0, -1)], []) return [(c+1, '('+s+')') for c,s in bagchain((0, ""), n-1, upto)] def bagchain(x, n, bb, start=0): if not n: return [x] out = [] for i in range(start, len(bb)): c,s = bb[i] if c <= n: out += bagchain((x[0] + c, x[1] + s), n-c, bb, i) return out def replace_brackets(s): depth,out = 0,[] for c in s: if c == '(': out.append("([{"[depth%3]) depth += 1 else: depth -= 1 out.append(")]}"[depth%3]) return "".join(out) for x in bags(5): print(replace_brackets(x[1]))
Rewrite this program in Python while keeping its functionality equivalent to the C++ version.
#include <iostream> #include <vector> std::vector<long> TREE_LIST; std::vector<int> OFFSET; void init() { for (size_t i = 0; i < 32; i++) { if (i == 1) { OFFSET.push_back(1); } else { OFFSET.push_back(0); } } } void append(long t) { TREE_LIST.push_back(1 | (t << 1)); } void show(long t, int l) { while (l-- > 0) { if (t % 2 == 1) { std::cout << '('; } else { std::cout << ')'; } t = t >> 1; } } void listTrees(int n) { for (int i = OFFSET[n]; i < OFFSET[n + 1]; i++) { show(TREE_LIST[i], 2 * n); std::cout << '\n'; } } void assemble(int n, long t, int sl, int pos, int rem) { if (rem == 0) { append(t); return; } auto pp = pos; auto ss = sl; if (sl > rem) { ss = rem; pp = OFFSET[ss]; } else if (pp >= OFFSET[ss + 1]) { ss--; if (ss == 0) { return; } pp = OFFSET[ss]; } assemble(n, t << (2 * ss) | TREE_LIST[pp], ss, pp, rem - ss); assemble(n, t, ss, pp + 1, rem); } void makeTrees(int n) { if (OFFSET[n + 1] != 0) { return; } if (n > 0) { makeTrees(n - 1); } assemble(n, 0, n - 1, OFFSET[n - 1], n - 1); OFFSET[n + 1] = TREE_LIST.size(); } void test(int n) { if (n < 1 || n > 12) { throw std::runtime_error("Argument must be between 1 and 12"); } append(0); makeTrees(n); std::cout << "Number of " << n << "-trees: " << OFFSET[n + 1] - OFFSET[n] << '\n'; listTrees(n); } int main() { init(); test(5); return 0; }
def bags(n,cache={}): if not n: return [(0, "")] upto = sum([bags(x) for x in range(n-1, 0, -1)], []) return [(c+1, '('+s+')') for c,s in bagchain((0, ""), n-1, upto)] def bagchain(x, n, bb, start=0): if not n: return [x] out = [] for i in range(start, len(bb)): c,s = bb[i] if c <= n: out += bagchain((x[0] + c, x[1] + s), n-c, bb, i) return out def replace_brackets(s): depth,out = 0,[] for c in s: if c == '(': out.append("([{"[depth%3]) depth += 1 else: depth -= 1 out.append(")]}"[depth%3]) return "".join(out) for x in bags(5): print(replace_brackets(x[1]))
Keep all operations the same but rewrite the snippet in Python.
#include <iostream> #include <string> #include <vector> #include <algorithm> std::string lcs(const std::vector<std::string>& strs) { std::vector<std::string::const_reverse_iterator> backs; std::string s; if (strs.size() == 0) return ""; if (strs.size() == 1) return strs[0]; for (auto& str : strs) backs.push_back(str.crbegin()); while (backs[0] != strs[0].crend()) { char ch = *backs[0]++; for (std::size_t i = 1; i<strs.size(); i++) { if (backs[i] == strs[i].crend()) goto done; if (*backs[i] != ch) goto done; backs[i]++; } s.push_back(ch); } done: reverse(s.begin(), s.end()); return s; } void test(const std::vector<std::string>& strs) { std::cout << "["; for (std::size_t i = 0; i<strs.size(); i++) { std::cout << '"' << strs[i] << '"'; if (i != strs.size()-1) std::cout << ", "; } std::cout << "] -> `" << lcs(strs) << "`\n"; } int main() { std::vector<std::string> t1 = {"baabababc", "baabc", "bbabc"}; std::vector<std::string> t2 = {"baabababc", "baabc", "bbazc"}; std::vector<std::string> t3 = {"Sunday", "Monday", "Tuesday", "Wednesday", "Friday", "Saturday"}; std::vector<std::string> t4 = {"longest", "common", "suffix"}; std::vector<std::string> t5 = {""}; std::vector<std::string> t6 = {}; std::vector<std::string> t7 = {"foo", "foo", "foo", "foo"}; std::vector<std::vector<std::string>> tests = {t1,t2,t3,t4,t5,t6,t7}; for (auto t : tests) test(t); return 0; }
from itertools import takewhile from functools import reduce def longestCommonSuffix(xs): def allSame(cs): h = cs[0] return all(h == c for c in cs[1:]) def firstCharPrepended(s, cs): return cs[0] + s return reduce( firstCharPrepended, takewhile( allSame, zip(*(reversed(x) for x in xs)) ), '' ) def main(): samples = [ [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], [ "Sondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrydag", "Saterdag" ] ] for xs in samples: print( longestCommonSuffix(xs) ) if __name__ == '__main__': main()