Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Maintain the same structure and functionality when rewriting this code in Python.
#include <iostream> #include <cstdint> struct Date { std::uint16_t year; std::uint8_t month; std::uint8_t day; }; constexpr bool leap(int year) { return year%4==0 && (year%100!=0 || year%400==0); } const std::string& weekday(const Date& date) { static const std::uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5}; static const std::uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5}; static const std::string days[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; unsigned const c = date.year/100, r = date.year%100; unsigned const s = r/12, t = r%12; unsigned const c_anchor = (5 * (c%4) + 2) % 7; unsigned const doom = (s + t + t/4 + c_anchor) % 7; unsigned const anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1]; return days[(doom+date.day-anchor+7)%7]; } int main(void) { const std::string months[] = {"", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; const Date dates[] = { {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14}, {2077,2,12}, {2101,4,2} }; for (const Date& d : dates) { std::cout << months[d.month] << " " << (int)d.day << ", " << d.year; std::cout << (d.year > 2021 ? " will be " : " was "); std::cout << "on a " << weekday(d) << std::endl; } return 0; }
from datetime import date from calendar import isleap def weekday(d): days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] dooms = [ [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5], [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] ] c = d.year // 100 r = d.year % 100 s = r // 12 t = r % 12 c_anchor = (5 * (c % 4) + 2) % 7 doomsday = (s + t + (t // 4) + c_anchor) % 7 anchorday = dooms[isleap(d.year)][d.month - 1] weekday = (doomsday + d.day - anchorday + 7) % 7 return days[weekday] dates = [date(*x) for x in [(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23), (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)] ] for d in dates: tense = "was" if d < date.today() else "is" if d == date.today() else "will be" print("{} {} a {}".format(d.strftime("%B %d, %Y"), tense, weekday(d)))
Produce a functionally identical Python code for the snippet given in C++.
#include <algorithm> #include <cassert> #include <iostream> #include <iterator> #include <vector> template <typename iterator> void cocktail_shaker_sort(iterator begin, iterator end) { if (begin == end) return; for (--end; begin < end; ) { iterator new_begin = end; iterator new_end = begin; for (iterator i = begin; i < end; ++i) { iterator j = i + 1; if (*j < *i) { std::iter_swap(i, j); new_end = i; } } end = new_end; for (iterator i = end; i > begin; --i) { iterator j = i - 1; if (*i < *j) { std::iter_swap(i, j); new_begin = i; } } begin = new_begin; } } template <typename iterator> void print(iterator begin, iterator end) { if (begin == end) return; std::cout << *begin++; while (begin != end) std::cout << ' ' << *begin++; std::cout << '\n'; } int main() { std::vector<int> v{5, 1, -6, 12, 3, 13, 2, 4, 0, 15}; std::cout << "before: "; print(v.begin(), v.end()); cocktail_shaker_sort(v.begin(), v.end()); assert(std::is_sorted(v.begin(), v.end())); std::cout << "after: "; print(v.begin(), v.end()); return 0; }
def cocktailshiftingbounds(A): beginIdx = 0 endIdx = len(A) - 1 while beginIdx <= endIdx: newBeginIdx = endIdx newEndIdx = beginIdx for ii in range(beginIdx,endIdx): if A[ii] > A[ii + 1]: A[ii+1], A[ii] = A[ii], A[ii+1] newEndIdx = ii endIdx = newEndIdx for ii in range(endIdx,beginIdx-1,-1): if A[ii] > A[ii + 1]: A[ii+1], A[ii] = A[ii], A[ii+1] newBeginIdx = ii beginIdx = newBeginIdx + 1 test1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0] cocktailshiftingbounds(test1) print(test1) test2=list('big fjords vex quick waltz nymph') cocktailshiftingbounds(test2) print(''.join(test2))
Please provide an equivalent version of this C++ code in Python.
#ifndef __wxPendulumDlg_h__ #define __wxPendulumDlg_h__ #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include <wx/wx.h> #include <wx/dialog.h> #else #include <wx/wxprec.h> #endif #include <wx/timer.h> #include <wx/dcbuffer.h> #include <cmath> class wxPendulumDlgApp : public wxApp { public: bool OnInit(); int OnExit(); }; class wxPendulumDlg : public wxDialog { public: wxPendulumDlg(wxWindow *parent, wxWindowID id = 1, const wxString &title = wxT("wxPendulum"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxSUNKEN_BORDER | wxCAPTION | wxRESIZE_BORDER | wxSYSTEM_MENU | wxDIALOG_NO_PARENT | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxCLOSE_BOX); virtual ~wxPendulumDlg(); void wxPendulumDlgPaint(wxPaintEvent& event); void wxPendulumDlgSize(wxSizeEvent& event); void OnTimer(wxTimerEvent& event); private: wxTimer *m_timer; unsigned int m_uiLength; double m_Angle; double m_AngleVelocity; enum wxIDs { ID_WXTIMER1 = 1001, ID_DUMMY_VALUE_ }; void OnClose(wxCloseEvent& event); void CreateGUIControls(); DECLARE_EVENT_TABLE() }; #endif
import pygame, sys from pygame.locals import * from math import sin, cos, radians pygame.init() WINDOWSIZE = 250 TIMETICK = 100 BOBSIZE = 15 window = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE)) pygame.display.set_caption("Pendulum") screen = pygame.display.get_surface() screen.fill((255,255,255)) PIVOT = (WINDOWSIZE/2, WINDOWSIZE/10) SWINGLENGTH = PIVOT[1]*4 class BobMass(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.theta = 45 self.dtheta = 0 self.rect = pygame.Rect(PIVOT[0]-SWINGLENGTH*cos(radians(self.theta)), PIVOT[1]+SWINGLENGTH*sin(radians(self.theta)), 1,1) self.draw() def recomputeAngle(self): scaling = 3000.0/(SWINGLENGTH**2) firstDDtheta = -sin(radians(self.theta))*scaling midDtheta = self.dtheta + firstDDtheta midtheta = self.theta + (self.dtheta + midDtheta)/2.0 midDDtheta = -sin(radians(midtheta))*scaling midDtheta = self.dtheta + (firstDDtheta + midDDtheta)/2 midtheta = self.theta + (self.dtheta + midDtheta)/2 midDDtheta = -sin(radians(midtheta)) * scaling lastDtheta = midDtheta + midDDtheta lasttheta = midtheta + (midDtheta + lastDtheta)/2.0 lastDDtheta = -sin(radians(lasttheta)) * scaling lastDtheta = midDtheta + (midDDtheta + lastDDtheta)/2.0 lasttheta = midtheta + (midDtheta + lastDtheta)/2.0 self.dtheta = lastDtheta self.theta = lasttheta self.rect = pygame.Rect(PIVOT[0]- SWINGLENGTH*sin(radians(self.theta)), PIVOT[1]+ SWINGLENGTH*cos(radians(self.theta)),1,1) def draw(self): pygame.draw.circle(screen, (0,0,0), PIVOT, 5, 0) pygame.draw.circle(screen, (0,0,0), self.rect.center, BOBSIZE, 0) pygame.draw.aaline(screen, (0,0,0), PIVOT, self.rect.center) pygame.draw.line(screen, (0,0,0), (0, PIVOT[1]), (WINDOWSIZE, PIVOT[1])) def update(self): self.recomputeAngle() screen.fill((255,255,255)) self.draw() bob = BobMass() TICK = USEREVENT + 2 pygame.time.set_timer(TICK, TIMETICK) def input(events): for event in events: if event.type == QUIT: sys.exit(0) elif event.type == TICK: bob.update() while True: input(pygame.event.get()) pygame.display.flip()
Ensure the translated Python code behaves exactly like the original C++ snippet.
#include <bitset> #include <iostream> #include <string> #include <assert.h> uint32_t gray_encode(uint32_t b) { return b ^ (b >> 1); } uint32_t gray_decode(uint32_t g) { for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1) { if (g & bit) g ^= bit >> 1; } return g; } std::string to_binary(int value) { const std::bitset<32> bs(value); const std::string str(bs.to_string()); const size_t pos(str.find('1')); return pos == std::string::npos ? "0" : str.substr(pos); } int main() { std::cout << "Number\tBinary\tGray\tDecoded\n"; for (uint32_t n = 0; n < 32; ++n) { uint32_t g = gray_encode(n); assert(gray_decode(g) == n); std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << g << "\n"; } }
>>> def int2bin(n): 'From positive integer to list of binary bits, msb at index 0' if n: bits = [] while n: n,remainder = divmod(n, 2) bits.insert(0, remainder) return bits else: return [0] >>> def bin2int(bits): 'From binary bits, msb at index 0 to integer' i = 0 for bit in bits: i = i * 2 + bit return i
Maintain the same structure and functionality when rewriting this code in Python.
#include <bitset> #include <iostream> #include <string> #include <assert.h> uint32_t gray_encode(uint32_t b) { return b ^ (b >> 1); } uint32_t gray_decode(uint32_t g) { for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1) { if (g & bit) g ^= bit >> 1; } return g; } std::string to_binary(int value) { const std::bitset<32> bs(value); const std::string str(bs.to_string()); const size_t pos(str.find('1')); return pos == std::string::npos ? "0" : str.substr(pos); } int main() { std::cout << "Number\tBinary\tGray\tDecoded\n"; for (uint32_t n = 0; n < 32; ++n) { uint32_t g = gray_encode(n); assert(gray_decode(g) == n); std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << g << "\n"; } }
>>> def int2bin(n): 'From positive integer to list of binary bits, msb at index 0' if n: bits = [] while n: n,remainder = divmod(n, 2) bits.insert(0, remainder) return bits else: return [0] >>> def bin2int(bits): 'From binary bits, msb at index 0 to integer' i = 0 for bit in bits: i = i * 2 + bit return i
Translate the given C++ code snippet into Python without altering its behavior.
#include <bitset> #include <iostream> #include <string> #include <assert.h> uint32_t gray_encode(uint32_t b) { return b ^ (b >> 1); } uint32_t gray_decode(uint32_t g) { for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1) { if (g & bit) g ^= bit >> 1; } return g; } std::string to_binary(int value) { const std::bitset<32> bs(value); const std::string str(bs.to_string()); const size_t pos(str.find('1')); return pos == std::string::npos ? "0" : str.substr(pos); } int main() { std::cout << "Number\tBinary\tGray\tDecoded\n"; for (uint32_t n = 0; n < 32; ++n) { uint32_t g = gray_encode(n); assert(gray_decode(g) == n); std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << g << "\n"; } }
>>> def int2bin(n): 'From positive integer to list of binary bits, msb at index 0' if n: bits = [] while n: n,remainder = divmod(n, 2) bits.insert(0, remainder) return bits else: return [0] >>> def bin2int(bits): 'From binary bits, msb at index 0 to integer' i = 0 for bit in bits: i = i * 2 + bit return i
Can you help me rewrite this code in Python instead of C++, keeping it the same logically?
#include <iostream> #include <fstream> #if defined(_WIN32) || defined(WIN32) constexpr auto FILENAME = "tape.file"; #else constexpr auto FILENAME = "/dev/tape"; #endif int main() { std::filebuf fb; fb.open(FILENAME,std::ios::out); std::ostream os(&fb); os << "Hello World\n"; fb.close(); return 0; }
>>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\n') ... >>>
Ensure the translated Python code behaves exactly like the original C++ snippet.
#include <algorithm> #include <iterator> #include <iostream> template<typename RandomAccessIterator> void heap_sort(RandomAccessIterator begin, RandomAccessIterator end) { std::make_heap(begin, end); std::sort_heap(begin, end); } int main() { int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; heap_sort(std::begin(a), std::end(a)); copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; }
def heapsort(lst): for start in range((len(lst)-2)/2, -1, -1): siftdown(lst, start, len(lst)-1) for end in range(len(lst)-1, 0, -1): lst[end], lst[0] = lst[0], lst[end] siftdown(lst, 0, end - 1) return lst def siftdown(lst, start, end): root = start while True: child = root * 2 + 1 if child > end: break if child + 1 <= end and lst[child] < lst[child + 1]: child += 1 if lst[root] < lst[child]: lst[root], lst[child] = lst[child], lst[root] root = child else: break
Generate a Python translation of this C++ snippet without changing its computational steps.
#include <deque> #include <algorithm> #include <ostream> #include <iterator> namespace cards { class card { public: enum pip_type { two, three, four, five, six, seven, eight, nine, ten, jack, queen, king, ace, pip_count }; enum suite_type { hearts, spades, diamonds, clubs, suite_count }; enum { unique_count = pip_count * suite_count }; card(suite_type s, pip_type p): value(s + suite_count * p) {} explicit card(unsigned char v = 0): value(v) {} pip_type pip() { return pip_type(value / suite_count); } suite_type suite() { return suite_type(value % suite_count); } private: unsigned char value; }; const char* const pip_names[] = { "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king", "ace" }; std::ostream& operator<<(std::ostream& os, card::pip_type pip) { return os << pip_names[pip]; } const char* const suite_names[] = { "hearts", "spades", "diamonds", "clubs" }; std::ostream& operator<<(std::ostream& os, card::suite_type suite) { return os << suite_names[suite]; } std::ostream& operator<<(std::ostream& os, card c) { return os << c.pip() << " of " << c.suite(); } class deck { public: deck() { for (int i = 0; i < card::unique_count; ++i) { cards.push_back(card(i)); } } void shuffle() { std::random_shuffle(cards.begin(), cards.end()); } card deal() { card c = cards.front(); cards.pop_front(); return c; } typedef std::deque<card>::const_iterator const_iterator; const_iterator begin() const { return cards.cbegin(); } const_iterator end() const { return cards.cend(); } private: std::deque<card> cards; }; inline std::ostream& operator<<(std::ostream& os, const deck& d) { std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, "\n")); return os; } }
import random class Card(object): suits = ("Clubs","Hearts","Spades","Diamonds") pips = ("2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace") def __init__(self, pip,suit): self.pip=pip self.suit=suit def __str__(self): return "%s %s"%(self.pip,self.suit) class Deck(object): def __init__(self): self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips] def __str__(self): return "[%s]"%", ".join( (str(card) for card in self.deck)) def shuffle(self): random.shuffle(self.deck) def deal(self): self.shuffle() return self.deck.pop(0)
Convert the following code from C++ to Python, ensuring the logic remains intact.
#include <deque> #include <algorithm> #include <ostream> #include <iterator> namespace cards { class card { public: enum pip_type { two, three, four, five, six, seven, eight, nine, ten, jack, queen, king, ace, pip_count }; enum suite_type { hearts, spades, diamonds, clubs, suite_count }; enum { unique_count = pip_count * suite_count }; card(suite_type s, pip_type p): value(s + suite_count * p) {} explicit card(unsigned char v = 0): value(v) {} pip_type pip() { return pip_type(value / suite_count); } suite_type suite() { return suite_type(value % suite_count); } private: unsigned char value; }; const char* const pip_names[] = { "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king", "ace" }; std::ostream& operator<<(std::ostream& os, card::pip_type pip) { return os << pip_names[pip]; } const char* const suite_names[] = { "hearts", "spades", "diamonds", "clubs" }; std::ostream& operator<<(std::ostream& os, card::suite_type suite) { return os << suite_names[suite]; } std::ostream& operator<<(std::ostream& os, card c) { return os << c.pip() << " of " << c.suite(); } class deck { public: deck() { for (int i = 0; i < card::unique_count; ++i) { cards.push_back(card(i)); } } void shuffle() { std::random_shuffle(cards.begin(), cards.end()); } card deal() { card c = cards.front(); cards.pop_front(); return c; } typedef std::deque<card>::const_iterator const_iterator; const_iterator begin() const { return cards.cbegin(); } const_iterator end() const { return cards.cend(); } private: std::deque<card> cards; }; inline std::ostream& operator<<(std::ostream& os, const deck& d) { std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, "\n")); return os; } }
import random class Card(object): suits = ("Clubs","Hearts","Spades","Diamonds") pips = ("2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace") def __init__(self, pip,suit): self.pip=pip self.suit=suit def __str__(self): return "%s %s"%(self.pip,self.suit) class Deck(object): def __init__(self): self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips] def __str__(self): return "[%s]"%", ".join( (str(card) for card in self.deck)) def shuffle(self): random.shuffle(self.deck) def deal(self): self.shuffle() return self.deck.pop(0)
Ensure the translated Python code behaves exactly like the original C++ snippet.
#include <array> #include <vector> #include <algorithm> #include <iostream> #include <iterator> #include <string> template <typename Array> void demonstrate(Array& array) { array[2] = "Three"; array.at(1) = "Two"; std::reverse(begin(array), end(array)); std::for_each(begin(array), end(array), [](typename Array::value_type const& element) { std::cout << element << ' '; }); std::cout << '\n'; } int main() { auto fixed_size_array = std::array<std::string, 3>{ "One", "Four", "Eight" }; auto dynamic_array = std::vector<std::string>{ "One", "Four" }; dynamic_array.push_back("Eight"); demonstrate(fixed_size_array); demonstrate(dynamic_array); }
array = [] array.append(1) array.append(3) array[0] = 2 print array[0]
Convert this C++ block to Python, preserving its control flow and logic.
#include <cstdint> #include <cstdlib> #include <cstdio> static constexpr int32_t bct_low_bits = 0x55555555; static int32_t bct_decrement(int32_t v) { --v; return v ^ (v & (v>>1) & bct_low_bits); } int main (int argc, char *argv[]) { const int32_t n = (1 < argc) ? std::atoi(argv[1]) : 3; if (n < 0 || 9 < n) { std::printf("N out of range (use 0..9): %ld\n", long(n)); return 1; } const int32_t size_bct = 1<<(n*2); int32_t y = size_bct; do { y = bct_decrement(y); int32_t x = size_bct; do { x = bct_decrement(x); std::putchar((x & y & bct_low_bits) ? ' ' : '#'); } while (0 < x); std::putchar('\n'); } while (0 < y); return 0; }
def setup(): size(729, 729) fill(0) background(255) noStroke() rect(width / 3, height / 3, width / 3, width / 3) rectangles(width / 3, height / 3, width / 3) def rectangles(x, y, s): if s < 1: return xc, yc = x - s, y - s for row in range(3): for col in range(3): if not (row == 1 and col == 1): xx, yy = xc + row * s, yc + col * s delta = s / 3 rect(xx + delta, yy + delta, delta, delta) rectangles(xx + s / 3, yy + s / 3, s / 3)
Produce a language-to-language conversion: from C++ to Python, same semantics.
#include <algorithm> #include <iostream> #include <iterator> #include <random> template <typename RandomAccessIterator, typename Predicate> void bogo_sort(RandomAccessIterator begin, RandomAccessIterator end, Predicate p) { std::random_device rd; std::mt19937 generator(rd()); while (!std::is_sorted(begin, end, p)) { std::shuffle(begin, end, generator); } } template <typename RandomAccessIterator> void bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) { bogo_sort( begin, end, std::less< typename std::iterator_traits<RandomAccessIterator>::value_type>()); } int main() { int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; bogo_sort(std::begin(a), std::end(a)); copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; }
import random def bogosort(l): while not in_order(l): random.shuffle(l) return l def in_order(l): if not l: return True last = l[0] for x in l[1:]: if x < last: return False last = x return True
Ensure the translated Python code behaves exactly like the original C++ snippet.
#include <iostream> #include <optional> #include <ranges> #include <string> #include <vector> using namespace std; struct Patient { string ID; string LastName; }; struct Visit { string PatientID; string Date; optional<float> Score; }; int main(void) { auto patients = vector<Patient> { {"1001", "Hopper"}, {"4004", "Wirth"}, {"3003", "Kemeny"}, {"2002", "Gosling"}, {"5005", "Kurtz"}}; auto visits = vector<Visit> { {"2002", "2020-09-10", 6.8}, {"1001", "2020-09-17", 5.5}, {"4004", "2020-09-24", 8.4}, {"2002", "2020-10-08", }, {"1001", "" , 6.6}, {"3003", "2020-11-12", }, {"4004", "2020-11-05", 7.0}, {"1001", "2020-11-19", 5.3}}; sort(patients.begin(), patients.end(), [](const auto& a, const auto&b){ return a.ID < b.ID;}); cout << "| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\n"; for(const auto& patient : patients) { string lastVisit; float sum = 0; int numScores = 0; auto patientFilter = [&patient](const Visit &v){return v.PatientID == patient.ID;}; for(const auto& visit : visits | views::filter( patientFilter )) { if(visit.Score) { sum += *visit.Score; numScores++; } lastVisit = max(lastVisit, visit.Date); } cout << "| " << patient.ID << " | "; cout.width(8); cout << patient.LastName << " | "; cout.width(10); cout << lastVisit << " | "; if(numScores > 0) { cout.width(9); cout << sum << " | "; cout.width(9); cout << (sum / float(numScores)); } else cout << " | "; cout << " |\n"; } }
import pandas as pd df_patients = pd.read_csv (r'patients.csv', sep = ",", decimal=".") df_visits = pd.read_csv (r'visits.csv', sep = ",", decimal=".") df_visits['VISIT_DATE'] = pd.to_datetime(df_visits['VISIT_DATE']) df_merge = df_patients.merge(df_visits, on='PATIENT_ID', how='left') df_group = df_merge.groupby(['PATIENT_ID','LASTNAME'], as_index=False) df_result = df_group.agg({'VISIT_DATE': 'max', 'SCORE': [lambda x: x.sum(min_count=1),'mean']}) print(df_result)
Write the same code in Python as shown below in C++.
#include <iomanip> #include <iostream> typedef double F(double,double); void euler(F f, double y0, double a, double b, double h) { double y = y0; for (double t = a; t < b; t += h) { std::cout << std::fixed << std::setprecision(3) << t << " " << y << "\n"; y += h * f(t, y); } std::cout << "done\n"; } double newtonCoolingLaw(double, double t) { return -0.07 * (t - 20); } int main() { euler(newtonCoolingLaw, 100, 0, 100, 2); euler(newtonCoolingLaw, 100, 0, 100, 5); euler(newtonCoolingLaw, 100, 0, 100, 10); }
def euler(f,y0,a,b,h): t,y = a,y0 while t <= b: print "%6.3f %6.3f" % (t,y) t += h y += h * f(t,y) def newtoncooling(time, temp): return -0.07 * (temp - 20) euler(newtoncooling,100,0,100,10)
Generate an equivalent Python version of this C++ code.
#include <iostream> #include <algorithm> #include <vector> #include <cmath> #include <boost/bind.hpp> #include <iterator> double nextNumber( double number ) { return number + floor( 0.5 + sqrt( number ) ) ; } int main( ) { std::vector<double> non_squares ; typedef std::vector<double>::iterator SVI ; non_squares.reserve( 1000000 ) ; for ( double i = 1.0 ; i < 100001.0 ; i += 1 ) non_squares.push_back( nextNumber( i ) ) ; std::copy( non_squares.begin( ) , non_squares.begin( ) + 22 , std::ostream_iterator<double>(std::cout, " " ) ) ; std::cout << '\n' ; SVI found = std::find_if ( non_squares.begin( ) , non_squares.end( ) , boost::bind( &floor, boost::bind( &sqrt, _1 ) ) == boost::bind( &sqrt, _1 ) ) ; if ( found != non_squares.end( ) ) { std::cout << "Found a square number in the sequence!\n" ; std::cout << "It is " << *found << " !\n" ; } else { std::cout << "Up to 1000000, found no square number in the sequence!\n" ; } return 0 ; }
>>> from math import floor, sqrt >>> def non_square(n): return n + floor(1/2 + sqrt(n)) >>> >>> print(*map(non_square, range(1, 23))) 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27 >>> >>> def is_square(n): return sqrt(n).is_integer() >>> non_squares = map(non_square, range(1, 10 ** 6)) >>> next(filter(is_square, non_squares)) StopIteration Traceback (most recent call last) <ipython-input-45-f32645fc1c0a> in <module>() 1 non_squares = map(non_square, range(1, 10 ** 6)) ----> 2 next(filter(is_square, non_squares)) StopIteration:
Please provide an equivalent version of this C++ code in Python.
#include <iostream> #include <string> int main() { std::string s = "0123456789"; int const n = 3; int const m = 4; char const c = '2'; std::string const sub = "456"; std::cout << s.substr(n, m)<< "\n"; std::cout << s.substr(n) << "\n"; std::cout << s.substr(0, s.size()-1) << "\n"; std::cout << s.substr(s.find(c), m) << "\n"; std::cout << s.substr(s.find(sub), m) << "\n"; }
>>> s = 'abcdefgh' >>> n, m, char, chars = 2, 3, 'd', 'cd' >>> >>> s[n-1:n+m-1] 'bcd' >>> >>> s[n-1:] 'bcdefgh' >>> >>> s[:-1] 'abcdefg' >>> >>> indx = s.index(char) >>> s[indx:indx+m] 'def' >>> >>> indx = s.index(chars) >>> s[indx:indx+m] 'cde' >>>
Ensure the translated Python code behaves exactly like the original C++ snippet.
#include <algorithm> #include <string> #include <iostream> #include <iterator> class jortSort { public: template<class T> bool jort_sort( T* o, size_t s ) { T* n = copy_array( o, s ); sort_array( n, s ); bool r = false; if( n ) { r = check( o, n, s ); delete [] n; } return r; } private: template<class T> T* copy_array( T* o, size_t s ) { T* z = new T[s]; memcpy( z, o, s * sizeof( T ) ); return z; } template<class T> void sort_array( T* n, size_t s ) { std::sort( n, n + s ); } template<class T> bool check( T* n, T* o, size_t s ) { for( size_t x = 0; x < s; x++ ) if( n[x] != o[x] ) return false; return true; } }; jortSort js; template<class T> void displayTest( T* o, size_t s ) { std::copy( o, o + s, std::ostream_iterator<T>( std::cout, " " ) ); std::cout << ": -> The array is " << ( js.jort_sort( o, s ) ? "sorted!" : "not sorted!" ) << "\n\n"; } int main( int argc, char* argv[] ) { const size_t s = 5; std::string oStr[] = { "5", "A", "D", "R", "S" }; displayTest( oStr, s ); std::swap( oStr[0], oStr[1] ); displayTest( oStr, s ); int oInt[] = { 1, 2, 3, 4, 5 }; displayTest( oInt, s ); std::swap( oInt[0], oInt[1] ); displayTest( oInt, s ); return 0; }
>>> def jortsort(sequence): return list(sequence) == sorted(sequence) >>> for data in [(1,2,4,3), (14,6,8), ['a', 'c'], ['s', 'u', 'x'], 'CVGH', 'PQRST']: print(f'jortsort({repr(data)}) is {jortsort(data)}') jortsort((1, 2, 4, 3)) is False jortsort((14, 6, 8)) is False jortsort(['a', 'c']) is True jortsort(['s', 'u', 'x']) is True jortsort('CVGH') is False jortsort('PQRST') is True >>>
Maintain the same structure and functionality when rewriting this code in Python.
#include <iostream> bool is_leap_year(int year) { return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); } int main() { for (auto year : {1900, 1994, 1996, 1997, 2000}) { std::cout << year << (is_leap_year(year) ? " is" : " is not") << " a leap year.\n"; } }
import calendar calendar.isleap(year)
Change the programming language of this snippet from C++ to Python without modifying what it does.
#include <boost/multiprecision/gmp.hpp> #include <iostream> using namespace boost::multiprecision; mpz_int p(uint n, uint p) { mpz_int r = 1; mpz_int k = n - p; while (n > k) r *= n--; return r; } mpz_int c(uint n, uint k) { mpz_int r = p(n, k); while (k) r /= k--; return r; } int main() { for (uint i = 1u; i < 12u; i++) std::cout << "P(12," << i << ") = " << p(12u, i) << std::endl; for (uint i = 10u; i < 60u; i += 10u) std::cout << "C(60," << i << ") = " << c(60u, i) << std::endl; return 0; }
from __future__ import print_function from scipy.misc import factorial as fact from scipy.misc import comb def perm(N, k, exact=0): return comb(N, k, exact) * fact(k, exact) exact=True print('Sample Perms 1..12') for N in range(1, 13): k = max(N-2, 1) print('%iP%i =' % (N, k), perm(N, k, exact), end=', ' if N % 5 else '\n') print('\n\nSample Combs 10..60') for N in range(10, 61, 10): k = N-2 print('%iC%i =' % (N, k), comb(N, k, exact), end=', ' if N % 50 else '\n') exact=False print('\n\nSample Perms 5..1500 Using FP approximations') for N in [5, 15, 150, 1500, 15000]: k = N-2 print('%iP%i =' % (N, k), perm(N, k, exact)) print('\nSample Combs 100..1000 Using FP approximations') for N in range(100, 1001, 100): k = N-2 print('%iC%i =' % (N, k), comb(N, k, exact))
Port the following code from C++ to Python with equivalent syntax and logic.
#include <algorithm> #include <iostream> #include <numeric> #include <string> #include <vector> void lexicographical_sort(std::vector<int>& numbers) { std::vector<std::string> strings(numbers.size()); std::transform(numbers.begin(), numbers.end(), strings.begin(), [](int i) { return std::to_string(i); }); std::sort(strings.begin(), strings.end()); std::transform(strings.begin(), strings.end(), numbers.begin(), [](const std::string& s) { return std::stoi(s); }); } std::vector<int> lexicographically_sorted_vector(int n) { std::vector<int> numbers(n >= 1 ? n : 2 - n); std::iota(numbers.begin(), numbers.end(), std::min(1, n)); lexicographical_sort(numbers); return numbers; } template <typename T> void print_vector(std::ostream& out, const std::vector<T>& v) { out << '['; if (!v.empty()) { auto i = v.begin(); out << *i++; for (; i != v.end(); ++i) out << ',' << *i; } out << "]\n"; } int main(int argc, char** argv) { for (int i : { 0, 5, 13, 21, -22 }) { std::cout << i << ": "; print_vector(std::cout, lexicographically_sorted_vector(i)); } return 0; }
n=13 print(sorted(range(1,n+1), key=str))
Can you help me rewrite this code in Python instead of C++, keeping it the same logically?
#include <string> #include <iostream> using std::string; const char* smallNumbers[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; string spellHundreds(unsigned n) { string res; if (n > 99) { res = smallNumbers[n/100]; res += " hundred"; n %= 100; if (n) res += " and "; } if (n >= 20) { static const char* Decades[] = { "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; res += Decades[n/10]; n %= 10; if (n) res += "-"; } if (n < 20 && n > 0) res += smallNumbers[n]; return res; } const char* thousandPowers[] = { " billion", " million", " thousand", "" }; typedef unsigned long Spellable; string spell(Spellable n) { if (n < 20) return smallNumbers[n]; string res; const char** pScaleName = thousandPowers; Spellable scaleFactor = 1000000000; while (scaleFactor > 0) { if (n >= scaleFactor) { Spellable h = n / scaleFactor; res += spellHundreds(h) + *pScaleName; n %= scaleFactor; if (n) res += ", "; } scaleFactor /= 1000; ++pScaleName; } return res; } int main() { #define SPELL_IT(x) std::cout << #x " " << spell(x) << std::endl; SPELL_IT( 99); SPELL_IT( 300); SPELL_IT( 310); SPELL_IT( 1501); SPELL_IT( 12609); SPELL_IT( 512609); SPELL_IT(43112609); SPELL_IT(1234567890); return 0; }
TENS = [None, None, "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] SMALL = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] HUGE = [None, None] + [h + "illion" for h in ("m", "b", "tr", "quadr", "quint", "sext", "sept", "oct", "non", "dec")] def nonzero(c, n, connect=''): return "" if n == 0 else connect + c + spell_integer(n) def last_and(num): if ',' in num: pre, last = num.rsplit(',', 1) if ' and ' not in last: last = ' and' + last num = ''.join([pre, ',', last]) return num def big(e, n): if e == 0: return spell_integer(n) elif e == 1: return spell_integer(n) + " thousand" else: return spell_integer(n) + " " + HUGE[e] def base1000_rev(n): while n != 0: n, r = divmod(n, 1000) yield r def spell_integer(n): if n < 0: return "minus " + spell_integer(-n) elif n < 20: return SMALL[n] elif n < 100: a, b = divmod(n, 10) return TENS[a] + nonzero("-", b) elif n < 1000: a, b = divmod(n, 100) return SMALL[a] + " hundred" + nonzero(" ", b, ' and') else: num = ", ".join([big(e, x) for e, x in enumerate(base1000_rev(n)) if x][::-1]) return last_and(num) if __name__ == '__main__': for n in (0, -3, 5, -7, 11, -13, 17, -19, 23, -29): print('%+4i -> %s' % (n, spell_integer(n))) print('') n = 201021002001 while n: print('%-12i -> %s' % (n, spell_integer(n))) n //= -10 print('%-12i -> %s' % (n, spell_integer(n))) print('')
Convert this C++ block to Python, preserving its control flow and logic.
#include <iostream> #include <algorithm> #include <string> #include <list> using namespace std; bool cmp(const string& a, const string& b) { return b.length() < a.length(); } void compareAndReportStringsLength(list<string> listOfStrings) { if (!listOfStrings.empty()) { char Q = '"'; string has_length(" has length "); string predicate_max(" and is the longest string"); string predicate_min(" and is the shortest string"); string predicate_ave(" and is neither the longest nor the shortest string"); list<string> ls(listOfStrings); ls.sort(cmp); int max = ls.front().length(); int min = ls.back().length(); for (list<string>::iterator s = ls.begin(); s != ls.end(); s++) { int length = s->length(); string* predicate; if (length == max) predicate = &predicate_max; else if (length == min) predicate = &predicate_min; else predicate = &predicate_ave; cout << Q << *s << Q << has_length << length << *predicate << endl; } } } int main(int argc, char* argv[]) { list<string> listOfStrings{ "abcd", "123456789", "abcdef", "1234567" }; compareAndReportStringsLength(listOfStrings); return EXIT_SUCCESS; }
A = 'I am string' B = 'I am string too' if len(A) > len(B): print('"' + A + '"', 'has length', len(A), 'and is the longest of the two strings') print('"' + B + '"', 'has length', len(B), 'and is the shortest of the two strings') elif len(A) < len(B): print('"' + B + '"', 'has length', len(B), 'and is the longest of the two strings') print('"' + A + '"', 'has length', len(A), 'and is the shortest of the two strings') else: print('"' + A + '"', 'has length', len(A), 'and it is as long as the second string') print('"' + B + '"', 'has length', len(B), 'and it is as long as the second string')
Rewrite the snippet below in Python so it works the same as the original C++ code.
#include <time.h> #include <iostream> using namespace std; const int MAX = 126; class shell { public: shell() { _gap[0] = 1750; _gap[1] = 701; _gap[2] = 301; _gap[3] = 132; _gap[4] = 57; _gap[5] = 23; _gap[6] = 10; _gap[7] = 4; _gap[8] = 1; } void sort( int* a, int count ) { _cnt = count; for( int x = 0; x < 9; x++ ) if( count > _gap[x] ) { _idx = x; break; } sortIt( a ); } private: void sortIt( int* arr ) { bool sorted = false; while( true ) { sorted = true; int st = 0; for( int x = _gap[_idx]; x < _cnt; x += _gap[_idx] ) { if( arr[st] > arr[x] ) { swap( arr[st], arr[x] ); sorted = false; } st = x; } if( ++_idx >= 8 ) _idx = 8; if( sorted && _idx == 8 ) break; } } void swap( int& a, int& b ) { int t = a; a = b; b = t; } int _gap[9], _idx, _cnt; }; int main( int argc, char* argv[] ) { srand( static_cast<unsigned int>( time( NULL ) ) ); int arr[MAX]; for( int x = 0; x < MAX; x++ ) arr[x] = rand() % MAX - rand() % MAX; cout << " Before: \n=========\n"; for( int x = 0; x < 7; x++ ) { for( int a = 0; a < 18; a++ ) { cout << arr[x * 18 + a] << " "; } cout << endl; } cout << endl; shell s; s.sort( arr, MAX ); cout << " After: \n========\n"; for( int x = 0; x < 7; x++ ) { for( int a = 0; a < 18; a++ ) { cout << arr[x * 18 + a] << " "; } cout << endl; } cout << endl << endl; return system( "pause" ); }
def shell(seq): inc = len(seq) // 2 while inc: for i, el in enumerate(seq[inc:], inc): while i >= inc and seq[i - inc] > el: seq[i] = seq[i - inc] i -= inc seq[i] = el inc = 1 if inc == 2 else inc * 5 // 11
Translate the given C++ code snippet into Python without altering its behavior.
#include <iostream> #include <list> int main () { std::list<int> numbers {1, 5, 7, 0, 3, 2}; numbers.insert(numbers.begin(), 9); numbers.insert(numbers.end(), 4); auto it = std::next(numbers.begin(), numbers.size() / 2); numbers.insert(it, 6); for(const auto& i: numbers) std::cout << i << ' '; std::cout << '\n'; }
from collections import deque some_list = deque(["a", "b", "c"]) print(some_list) some_list.appendleft("Z") print(some_list) for value in reversed(some_list): print(value)
Rewrite the snippet below in Python so it works the same as the original C++ code.
#include <fstream> #include <iostream> int main() { std::ifstream input("filename.txt", std::ios_base::binary); if (!input) { std::cerr << "error: can't open file\n"; return -1; } size_t count[256]; std::fill_n(count, 256, 0); for (char c; input.get(c); ++count[uint8_t(c)]) ; for (size_t i = 0; i < 256; ++i) { if (count[i] && isgraph(i)) { std::cout << char(i) << " = " << count[i] << '\n'; } } }
import collections, sys def filecharcount(openfile): return sorted(collections.Counter(c for l in openfile for c in l).items()) f = open(sys.argv[1]) print(filecharcount(f))
Change the programming language of this snippet from C++ to Python without modifying what it does.
#include<iostream> #include<vector> #include<numeric> #include<functional> class { public: int64_t operator()(int n, int k){ return partial_factorial(n, k) / factorial(n - k);} private: int64_t partial_factorial(int from, int to) { return from == to ? 1 : from * partial_factorial(from - 1, to); } int64_t factorial(int n) { return n == 0 ? 1 : n * factorial(n - 1);} }combinations; int main() { static constexpr int treatment = 9; const std::vector<int> data{ 85, 88, 75, 66, 25, 29, 83, 39, 97, 68, 41, 10, 49, 16, 65, 32, 92, 28, 98 }; int treated = std::accumulate(data.begin(), data.begin() + treatment, 0); std::function<int (int, int, int)> pick; pick = [&](int n, int from, int accumulated) { if(n == 0) return accumulated > treated ? 1 : 0; else return pick(n - 1, from - 1, accumulated + data[from - 1]) + (from > n ? pick(n, from - 1, accumulated) : 0); }; int total = combinations(data.size(), treatment); int greater = pick(treatment, data.size(), 0); int lesser = total - greater; std::cout << "<= : " << 100.0 * lesser / total << "% " << lesser << std::endl << " > : " << 100.0 * greater / total << "% " << greater << std::endl; }
from itertools import combinations as comb def statistic(ab, a): sumab, suma = sum(ab), sum(a) return ( suma / len(a) - (sumab -suma) / (len(ab) - len(a)) ) def permutationTest(a, b): ab = a + b Tobs = statistic(ab, a) under = 0 for count, perm in enumerate(comb(ab, len(a)), 1): if statistic(ab, perm) <= Tobs: under += 1 return under * 100. / count treatmentGroup = [85, 88, 75, 66, 25, 29, 83, 39, 97] controlGroup = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98] under = permutationTest(treatmentGroup, controlGroup) print("under=%.2f%%, over=%.2f%%" % (under, 100. - under))
Generate an equivalent Python version of this C++ code.
#include <iomanip> #include <iostream> #include <vector> constexpr int MU_MAX = 1'000'000; std::vector<int> MU; int mobiusFunction(int n) { if (!MU.empty()) { return MU[n]; } MU.resize(MU_MAX + 1, 1); int root = sqrt(MU_MAX); for (int i = 2; i <= root; i++) { if (MU[i] == 1) { for (int j = i; j <= MU_MAX; j += i) { MU[j] *= -i; } for (int j = i * i; j <= MU_MAX; j += i * i) { MU[j] = 0; } } } for (int i = 2; i <= MU_MAX; i++) { if (MU[i] == i) { MU[i] = 1; } else if (MU[i] == -i) { MU[i] = -1; } else if (MU[i] < 0) { MU[i] = 1; } else if (MU[i] > 0) { MU[i] = -1; } } return MU[n]; } int main() { std::cout << "First 199 terms of the möbius function are as follows:\n "; for (int n = 1; n < 200; n++) { std::cout << std::setw(2) << mobiusFunction(n) << " "; if ((n + 1) % 20 == 0) { std::cout << '\n'; } } return 0; }
def isPrime(n) : if (n < 2) : return False for i in range(2, n + 1) : if (i * i <= n and n % i == 0) : return False return True def mobius(N) : if (N == 1) : return 1 p = 0 for i in range(1, N + 1) : if (N % i == 0 and isPrime(i)) : if (N % (i * i) == 0) : return 0 else : p = p + 1 if(p % 2 != 0) : return -1 else : return 1 print("Mobius numbers from 1..99:") for i in range(1, 100): print(f"{mobius(i):>4}", end = '') if i % 20 == 0: print()
Write the same algorithm in Python as shown in this C++ implementation.
#include <cstdlib> #include <string> #include <sstream> std::string s = "12345"; int i; std::istringstream(s) >> i; i++; std::ostringstream oss; if (oss << i) s = oss.str();
next = str(int('123') + 1)
Please provide an equivalent version of this C++ code in Python.
#include <algorithm> #include <iostream> #include <string> std::string stripchars(std::string str, const std::string &chars) { str.erase( std::remove_if(str.begin(), str.end(), [&](char c){ return chars.find(c) != std::string::npos; }), str.end() ); return str; } int main() { std::cout << stripchars("She was a soul stripper. She took my heart!", "aei") << '\n'; return 0; }
>>> def stripchars(s, chars): ... return s.translate(None, chars) ... >>> stripchars("She was a soul stripper. She took my heart!", "aei") 'Sh ws soul strppr. Sh took my hrt!'
Produce a language-to-language conversion: from C++ to Python, same semantics.
#include <algorithm> template<typename ForwardIterator> void permutation_sort(ForwardIterator begin, ForwardIterator end) { while (std::next_permutation(begin, end)) { } }
from itertools import permutations in_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1])) perm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next()
Change the following C++ code into Python without altering its purpose.
#include <vector> double mean(const std::vector<double>& numbers) { if (numbers.size() == 0) return 0; double sum = 0; for (std::vector<double>::iterator i = numbers.begin(); i != numbers.end(); i++) sum += *i; return sum / numbers.size(); }
from math import fsum def average(x): return fsum(x)/float(len(x)) if x else 0 print (average([0,0,3,1,4,1,5,9,0,0])) print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))
Write the same algorithm in Python as shown in this C++ implementation.
#include <algorithm> #include <cctype> #include <iostream> #include <sstream> #include <string> #include <vector> const char* command_table = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1"; class command { public: command(const std::string&, size_t); const std::string& cmd() const { return cmd_; } size_t min_length() const { return min_len_; } bool match(const std::string&) const; private: std::string cmd_; size_t min_len_; }; command::command(const std::string& cmd, size_t min_len) : cmd_(cmd), min_len_(min_len) {} bool command::match(const std::string& str) const { size_t olen = str.length(); return olen >= min_len_ && olen <= cmd_.length() && cmd_.compare(0, olen, str) == 0; } bool parse_integer(const std::string& word, int& value) { try { size_t pos; int i = std::stoi(word, &pos, 10); if (pos < word.length()) return false; value = i; return true; } catch (const std::exception& ex) { return false; } } void uppercase(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) -> unsigned char { return std::toupper(c); }); } class command_list { public: explicit command_list(const char*); const command* find_command(const std::string&) const; private: std::vector<command> commands_; }; command_list::command_list(const char* table) { std::istringstream is(table); std::string word; std::vector<std::string> words; while (is >> word) { uppercase(word); words.push_back(word); } for (size_t i = 0, n = words.size(); i < n; ++i) { word = words[i]; int len = word.length(); if (i + 1 < n && parse_integer(words[i + 1], len)) ++i; commands_.push_back(command(word, len)); } } const command* command_list::find_command(const std::string& word) const { auto iter = std::find_if(commands_.begin(), commands_.end(), [&word](const command& cmd) { return cmd.match(word); }); return (iter != commands_.end()) ? &*iter : nullptr; } std::string test(const command_list& commands, const std::string& input) { std::string output; std::istringstream is(input); std::string word; while (is >> word) { if (!output.empty()) output += ' '; uppercase(word); const command* cmd_ptr = commands.find_command(word); if (cmd_ptr) output += cmd_ptr->cmd(); else output += "*error*"; } return output; } int main() { command_list commands(command_table); std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin"); std::string output(test(commands, input)); std::cout << " input: " << input << '\n'; std::cout << "output: " << output << '\n'; return 0; }
command_table_text = user_words = "riG rePEAT copies put mo rest types fup. 6 poweRin" def find_abbreviations_length(command_table_text): command_table = dict() input_iter = iter(command_table_text.split()) word = None try: while True: if word is None: word = next(input_iter) abbr_len = next(input_iter, len(word)) try: command_table[word] = int(abbr_len) word = None except ValueError: command_table[word] = len(word) word = abbr_len except StopIteration: pass return command_table def find_abbreviations(command_table): abbreviations = dict() for command, min_abbr_len in command_table.items(): for l in range(min_abbr_len, len(command)+1): abbr = command[:l].lower() abbreviations[abbr] = command.upper() return abbreviations def parse_user_string(user_string, abbreviations): user_words = [word.lower() for word in user_string.split()] commands = [abbreviations.get(user_word, "*error*") for user_word in user_words] return " ".join(commands) command_table = find_abbreviations_length(command_table_text) abbreviations_table = find_abbreviations(command_table) full_words = parse_user_string(user_words, abbreviations_table) print("user words:", user_words) print("full words:", full_words)
Maintain the same structure and functionality when rewriting this code in Python.
#include <algorithm> #include <cctype> #include <iostream> #include <sstream> #include <string> #include <vector> const char* command_table = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1"; class command { public: command(const std::string&, size_t); const std::string& cmd() const { return cmd_; } size_t min_length() const { return min_len_; } bool match(const std::string&) const; private: std::string cmd_; size_t min_len_; }; command::command(const std::string& cmd, size_t min_len) : cmd_(cmd), min_len_(min_len) {} bool command::match(const std::string& str) const { size_t olen = str.length(); return olen >= min_len_ && olen <= cmd_.length() && cmd_.compare(0, olen, str) == 0; } bool parse_integer(const std::string& word, int& value) { try { size_t pos; int i = std::stoi(word, &pos, 10); if (pos < word.length()) return false; value = i; return true; } catch (const std::exception& ex) { return false; } } void uppercase(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) -> unsigned char { return std::toupper(c); }); } class command_list { public: explicit command_list(const char*); const command* find_command(const std::string&) const; private: std::vector<command> commands_; }; command_list::command_list(const char* table) { std::istringstream is(table); std::string word; std::vector<std::string> words; while (is >> word) { uppercase(word); words.push_back(word); } for (size_t i = 0, n = words.size(); i < n; ++i) { word = words[i]; int len = word.length(); if (i + 1 < n && parse_integer(words[i + 1], len)) ++i; commands_.push_back(command(word, len)); } } const command* command_list::find_command(const std::string& word) const { auto iter = std::find_if(commands_.begin(), commands_.end(), [&word](const command& cmd) { return cmd.match(word); }); return (iter != commands_.end()) ? &*iter : nullptr; } std::string test(const command_list& commands, const std::string& input) { std::string output; std::istringstream is(input); std::string word; while (is >> word) { if (!output.empty()) output += ' '; uppercase(word); const command* cmd_ptr = commands.find_command(word); if (cmd_ptr) output += cmd_ptr->cmd(); else output += "*error*"; } return output; } int main() { command_list commands(command_table); std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin"); std::string output(test(commands, input)); std::cout << " input: " << input << '\n'; std::cout << "output: " << output << '\n'; return 0; }
command_table_text = user_words = "riG rePEAT copies put mo rest types fup. 6 poweRin" def find_abbreviations_length(command_table_text): command_table = dict() input_iter = iter(command_table_text.split()) word = None try: while True: if word is None: word = next(input_iter) abbr_len = next(input_iter, len(word)) try: command_table[word] = int(abbr_len) word = None except ValueError: command_table[word] = len(word) word = abbr_len except StopIteration: pass return command_table def find_abbreviations(command_table): abbreviations = dict() for command, min_abbr_len in command_table.items(): for l in range(min_abbr_len, len(command)+1): abbr = command[:l].lower() abbreviations[abbr] = command.upper() return abbreviations def parse_user_string(user_string, abbreviations): user_words = [word.lower() for word in user_string.split()] commands = [abbreviations.get(user_word, "*error*") for user_word in user_words] return " ".join(commands) command_table = find_abbreviations_length(command_table_text) abbreviations_table = find_abbreviations(command_table) full_words = parse_user_string(user_words, abbreviations_table) print("user words:", user_words) print("full words:", full_words)
Convert the following code from C++ to Python, ensuring the logic remains intact.
#include <string> #include <map> #include <iostream> #include <algorithm> #include <cmath> double log2( double number ) { return log( number ) / log( 2 ) ; } int main( int argc , char *argv[ ] ) { std::string teststring( argv[ 1 ] ) ; std::map<char , int> frequencies ; for ( char c : teststring ) frequencies[ c ] ++ ; int numlen = teststring.length( ) ; double infocontent = 0 ; for ( std::pair<char , int> p : frequencies ) { double freq = static_cast<double>( p.second ) / numlen ; infocontent -= freq * log2( freq ) ; } std::cout << "The information content of " << teststring << " is " << infocontent << std::endl ; return 0 ; }
from __future__ import division import math def hist(source): hist = {}; l = 0; for e in source: l += 1 if e not in hist: hist[e] = 0 hist[e] += 1 return (l,hist) def entropy(hist,l): elist = [] for v in hist.values(): c = v / l elist.append(-c * math.log(c ,2)) return sum(elist) def printHist(h): flip = lambda (k,v) : (v,k) h = sorted(h.iteritems(), key = flip) print 'Sym\thi\tfi\tInf' for (k,v) in h: print '%s\t%f\t%f\t%f'%(k,v,v/l,-math.log(v/l, 2)) source = "1223334444" (l,h) = hist(source); print '.[Results].' print 'Length',l print 'Entropy:', entropy(h, l) printHist(h)
Translate this program into Python but keep the logic exactly as in C++.
#include <iostream> #include <stdexcept> #include <string> #include <vector> using namespace std; vector<string> tokenize(const string& input, char seperator, char escape) { vector<string> output; string token; bool inEsc = false; for (char ch : input) { if (inEsc) { inEsc = false; } else if (ch == escape) { inEsc = true; continue; } else if (ch == seperator) { output.push_back(token); token = ""; continue; } token += ch; } if (inEsc) throw new invalid_argument("Invalid terminal escape"); output.push_back(token); return output; } int main() { string sample = "one^|uno||three^^^^|four^^^|^cuatro|"; cout << sample << endl; cout << '['; for (auto t : tokenize(sample, '|', '^')) { cout << '"' << t << "\", "; } cout << ']' << endl; return 0; }
def token_with_escape(a, escape = '^', separator = '|'): result = [] token = '' state = 0 for c in a: if state == 0: if c == escape: state = 1 elif c == separator: result.append(token) token = '' else: token += c elif state == 1: token += c state = 0 result.append(token) return result
Maintain the same structure and functionality when rewriting this code in Python.
#include <iostream> int main () { std::cout << "Hello world!" << std::endl; }
print "Hello world!"
Generate an equivalent Python version of this C++ code.
#include <array> #include <iostream> #include <vector> #include <boost/circular_buffer.hpp> #include "prime_sieve.hpp" int main() { using std::cout; using std::vector; using boost::circular_buffer; using group_buffer = circular_buffer<vector<int>>; const int max = 1000035; const int max_group_size = 5; const int diff = 6; const int array_size = max + diff; const int max_groups = 5; const int max_unsexy = 10; prime_sieve sieve(array_size); std::array<int, max_group_size> group_count{0}; vector<group_buffer> groups(max_group_size, group_buffer(max_groups)); int unsexy_count = 0; circular_buffer<int> unsexy_primes(max_unsexy); vector<int> group; for (int p = 2; p < max; ++p) { if (!sieve.is_prime(p)) continue; if (!sieve.is_prime(p + diff) && (p - diff < 2 || !sieve.is_prime(p - diff))) { ++unsexy_count; unsexy_primes.push_back(p); } else { group.clear(); group.push_back(p); for (int group_size = 1; group_size < max_group_size; group_size++) { int next_p = p + group_size * diff; if (next_p >= max || !sieve.is_prime(next_p)) break; group.push_back(next_p); ++group_count[group_size]; groups[group_size].push_back(group); } } } for (int size = 1; size < max_group_size; ++size) { cout << "number of groups of size " << size + 1 << " is " << group_count[size] << '\n'; cout << "last " << groups[size].size() << " groups of size " << size + 1 << ":"; for (const vector<int>& group : groups[size]) { cout << " ("; for (size_t i = 0; i < group.size(); ++i) { if (i > 0) cout << ' '; cout << group[i]; } cout << ")"; } cout << "\n\n"; } cout << "number of unsexy primes is " << unsexy_count << '\n'; cout << "last " << unsexy_primes.size() << " unsexy primes:"; for (int prime : unsexy_primes) cout << ' ' << prime; cout << '\n'; return 0; }
LIMIT = 1_000_035 def primes2(limit=LIMIT): if limit < 2: return [] if limit < 3: return [2] lmtbf = (limit - 3) // 2 buf = [True] * (lmtbf + 1) for i in range((int(limit ** 0.5) - 3) // 2 + 1): if buf[i]: p = i + i + 3 s = p * (i + 1) + i buf[s::p] = [False] * ((lmtbf - s) // p + 1) return [2] + [i + i + 3 for i, v in enumerate(buf) if v] primes = primes2(LIMIT +6) primeset = set(primes) primearray = [n in primeset for n in range(LIMIT)] s = [[] for x in range(4)] unsexy = [] for p in primes: if p > LIMIT: break if p + 6 in primeset and p + 6 < LIMIT: s[0].append((p, p+6)) elif p + 6 in primeset: break else: if p - 6 not in primeset: unsexy.append(p) continue if p + 12 in primeset and p + 12 < LIMIT: s[1].append((p, p+6, p+12)) else: continue if p + 18 in primeset and p + 18 < LIMIT: s[2].append((p, p+6, p+12, p+18)) else: continue if p + 24 in primeset and p + 24 < LIMIT: s[3].append((p, p+6, p+12, p+18, p+24)) print('"SEXY" PRIME GROUPINGS:') for sexy, name in zip(s, 'pairs triplets quadruplets quintuplets'.split()): print(f' {len(sexy)} {na (not isPrime(n-6))))) |> Array.ofSeq printfn "There are %d unsexy primes less than 1,000,035. The last 10 are:" n.Length Array.skip (n.Length-10) n |> Array.iter(fun n->printf "%d " n); printfn "" let ni=pCache |> Seq.takeWhile(fun n->nme} ending with ...') for sx in sexy[-5:]: print(' ',sx) print(f'\nThere are {len(unsexy)} unsexy primes ending with ...') for usx in unsexy[-10:]: print(' ',usx)
Maintain the same structure and functionality when rewriting this code in Python.
#include <vector> #include <iterator> #include <algorithm> template<typename InputIterator, typename OutputIterator> OutputIterator forward_difference(InputIterator first, InputIterator last, OutputIterator dest) { if (first == last) return dest; typedef typename std::iterator_traits<InputIterator>::value_type value_type; value_type temp = *first++; while (first != last) { value_type temp2 = *first++; *dest++ = temp2 - temp; temp = temp2; } return dest; } template<typename InputIterator, typename OutputIterator> OutputIterator nth_forward_difference(int order, InputIterator first, InputIterator last, OutputIterator dest) { if (order == 0) return std::copy(first, last, dest); if (order == 1) return forward_difference(first, last, dest); typedef typename std::iterator_traits<InputIterator>::value_type value_type; std::vector<value_type> temp_storage; forward_difference(first, last, std::back_inserter(temp_storage)); typename std::vector<value_type>::iterator begin = temp_storage.begin(), end = temp_storage.end(); for (int i = 1; i < order-1; ++i) end = forward_difference(begin, end, begin); return forward_difference(begin, end, dest); } #include <iostream> int main() { double array[10] = { 90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0 }; std::vector<double> dest; nth_forward_difference(1, array, array+10, std::back_inserter(dest)); std::copy(dest.begin(), dest.end(), std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(2, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(9, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(10, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(0, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; double* end = nth_forward_difference(3, array, array+10, array); for (double* p = array; p < end; ++p) std::cout << *p << " "; std::cout << std::endl; return 0; }
>>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])] >>> >>> difn = lambda s, n: difn(dif(s), n-1) if n else s >>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] >>> difn(s, 0) [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] >>> difn(s, 1) [-43, 11, -29, -7, 10, 23, -50, 50, 18] >>> difn(s, 2) [54, -40, 22, 17, 13, -73, 100, -32] >>> from pprint import pprint >>> pprint( [difn(s, i) for i in xrange(10)] ) [[90, 47, 58, 29, 22, 32, 55, 5, 55, 73], [-43, 11, -29, -7, 10, 23, -50, 50, 18], [54, -40, 22, 17, 13, -73, 100, -32], [-94, 62, -5, -4, -86, 173, -132], [156, -67, 1, -82, 259, -305], [-223, 68, -83, 341, -564], [291, -151, 424, -905], [-442, 575, -1329], [1017, -1904], [-2921]]
Produce a functionally identical Python code for the snippet given in C++.
#include <cmath> bool is_prime(unsigned int n) { if (n <= 1) return false; if (n == 2) return true; for (unsigned int i = 2; i <= sqrt(n); ++i) if (n % i == 0) return false; return true; }
def prime(a): return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))
Write a version of this C++ function in Python with identical behavior.
double Factorial(double nValue) { double result = nValue; double result_next; double pc = nValue; do { result_next = result*(pc-1); result = result_next; pc--; }while(pc>2); nValue = result; return nValue; } double binomialCoefficient(double n, double k) { if (abs(n - k) < 1e-7 || k < 1e-7) return 1.0; if( abs(k-1.0) < 1e-7 || abs(k - (n-1)) < 1e-7)return n; return Factorial(n) /(Factorial(k)*Factorial((n - k))); }
def binomialCoeff(n, k): result = 1 for i in range(1, k+1): result = result * (n-i+1) / i return result if __name__ == "__main__": print(binomialCoeff(5, 3))
Ensure the translated Python code behaves exactly like the original C++ snippet.
int a[5]; a[0] = 1; int primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; #include <string> std::string strings[4];
collection = [0, '1'] x = collection[0] collection.append(2) collection.insert(0, '-1') y = collection[0] collection.extend([2,'3']) collection += [2,'3'] collection[2:6] len(collection) collection = (0, 1) collection[:] collection[-4:-1] collection[::2] collection="some string" x = collection[::-1] collection[::2] == "some string"[::2] collection.__getitem__(slice(0,len(collection),2)) collection = {0: "zero", 1: "one"} collection['zero'] = 2 collection = set([0, '1'])
Generate a Python translation of this C++ snippet without changing its computational steps.
#include <iostream> #include <forward_list> int main() { std::forward_list<int> list{1, 2, 3, 4, 5}; for (int e : list) std::cout << e << std::endl; }
for node in lst: print node.value
Write a version of this C++ function in Python with identical behavior.
#include <fstream> #include <cstdio> int main() { constexpr auto dimx = 800u, dimy = 800u; using namespace std; ofstream ofs("first.ppm", ios_base::out | ios_base::binary); ofs << "P6" << endl << dimx << ' ' << dimy << endl << "255" << endl; for (auto j = 0u; j < dimy; ++j) for (auto i = 0u; i < dimx; ++i) ofs << (char) (i % 256) << (char) (j % 256) << (char) ((i * j) % 256); ofs.close(); return EXIT_SUCCESS; }
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
Change the programming language of this snippet from C++ to Python without modifying what it does.
#include <cstdio> #include <direct.h> int main() { remove( "input.txt" ); remove( "/input.txt" ); _rmdir( "docs" ); _rmdir( "/docs" ); return 0; }
import os os.remove("output.txt") os.rmdir("docs") os.remove("/output.txt") os.rmdir("/docs")
Port the provided C++ code into Python while preserving the original functionality.
#include <iostream> #include <algorithm> #include <vector> #include <sstream> #include <iterator> using namespace std; class myTuple { public: void set( int a, int b, string c ) { t.first.first = a; t.first.second = b; t.second = c; } bool operator == ( pair<int, int> p ) { return p.first == t.first.first && p.second == t.first.second; } string second() { return t.second; } private: pair<pair<int, int>, string> t; }; class discordian { public: discordian() { myTuple t; t.set( 5, 1, "Mungday" ); holyday.push_back( t ); t.set( 19, 2, "Chaoflux" ); holyday.push_back( t ); t.set( 29, 2, "St. Tib's Day" ); holyday.push_back( t ); t.set( 19, 3, "Mojoday" ); holyday.push_back( t ); t.set( 3, 5, "Discoflux" ); holyday.push_back( t ); t.set( 31, 5, "Syaday" ); holyday.push_back( t ); t.set( 15, 7, "Confuflux" ); holyday.push_back( t ); t.set( 12, 8, "Zaraday" ); holyday.push_back( t ); t.set( 26, 9, "Bureflux" ); holyday.push_back( t ); t.set( 24, 10, "Maladay" ); holyday.push_back( t ); t.set( 8, 12, "Afflux" ); holyday.push_back( t ); seasons.push_back( "Chaos" ); seasons.push_back( "Discord" ); seasons.push_back( "Confusion" ); seasons.push_back( "Bureaucracy" ); seasons.push_back( "The Aftermath" ); wdays.push_back( "Setting Orange" ); wdays.push_back( "Sweetmorn" ); wdays.push_back( "Boomtime" ); wdays.push_back( "Pungenday" ); wdays.push_back( "Prickle-Prickle" ); } void convert( int d, int m, int y ) { if( d == 0 || m == 0 || m > 12 || d > getMaxDay( m, y ) ) { cout << "\nThis is not a date!"; return; } vector<myTuple>::iterator f = find( holyday.begin(), holyday.end(), make_pair( d, m ) ); int dd = d, day, wday, sea, yr = y + 1166; for( int x = 1; x < m; x++ ) dd += getMaxDay( x, 1 ); day = dd % 73; if( !day ) day = 73; wday = dd % 5; sea = ( dd - 1 ) / 73; if( d == 29 && m == 2 && isLeap( y ) ) { cout << ( *f ).second() << " " << seasons[sea] << ", Year of Our Lady of Discord " << yr; return; } cout << wdays[wday] << " " << seasons[sea] << " " << day; if( day > 10 && day < 14 ) cout << "th"; else switch( day % 10) { case 1: cout << "st"; break; case 2: cout << "nd"; break; case 3: cout << "rd"; break; default: cout << "th"; } cout << ", Year of Our Lady of Discord " << yr; if( f != holyday.end() ) cout << " - " << ( *f ).second(); } private: int getMaxDay( int m, int y ) { int dd[] = { 0, 31, isLeap( y ) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; return dd[m]; } bool isLeap( int y ) { bool l = false; if( !( y % 4 ) ) { if( y % 100 ) l = true; else if( !( y % 400 ) ) l = true; } return l; } vector<myTuple> holyday; vector<string> seasons, wdays; }; int main( int argc, char* argv[] ) { string date; discordian disc; while( true ) { cout << "Enter a date (dd mm yyyy) or 0 to quit: "; getline( cin, date ); if( date == "0" ) break; if( date.length() == 10 ) { istringstream iss( date ); vector<string> vc; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( vc ) ); disc.convert( atoi( vc[0].c_str() ), atoi( vc[1].c_str() ), atoi( vc[2].c_str() ) ); cout << "\n\n\n"; } else cout << "\nIs this a date?!\n\n"; } return 0; }
import datetime, calendar DISCORDIAN_SEASONS = ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"] def ddate(year, month, day): today = datetime.date(year, month, day) is_leap_year = calendar.isleap(year) if is_leap_year and month == 2 and day == 29: return "St. Tib's Day, YOLD " + (year + 1166) day_of_year = today.timetuple().tm_yday - 1 if is_leap_year and day_of_year >= 60: day_of_year -= 1 season, dday = divmod(day_of_year, 73) return "%s %d, YOLD %d" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)
Convert the following code from C++ to Python, ensuring the logic remains intact.
#include <time.h> #include <iostream> #include <string> typedef unsigned char byte; using namespace std; class flip { public: flip() { field = 0; target = 0; } void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); } private: void gameLoop() { int moves = 0; while( !solved() ) { display(); string r; cout << "Enter rows letters and/or column numbers: "; cin >> r; for( string::iterator i = r.begin(); i != r.end(); i++ ) { byte ii = ( *i ); if( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; } else if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; } } } cout << endl << endl << "** Well done! **" << endl << "Used " << moves << " moves." << endl << endl; } void display() { system( "cls" ); output( "TARGET:", target ); output( "YOU:", field ); } void output( string t, byte* f ) { cout << t << endl; cout << " "; for( int x = 0; x < wid; x++ ) cout << " " << static_cast<char>( x + '1' ); cout << endl; for( int y = 0; y < hei; y++ ) { cout << static_cast<char>( y + 'a' ) << " "; for( int x = 0; x < wid; x++ ) cout << static_cast<char>( f[x + y * wid] + 48 ) << " "; cout << endl; } cout << endl << endl; } bool solved() { for( int y = 0; y < hei; y++ ) for( int x = 0; x < wid; x++ ) if( target[x + y * wid] != field[x + y * wid] ) return false; return true; } void createTarget() { for( int y = 0; y < hei; y++ ) for( int x = 0; x < wid; x++ ) if( frnd() < .5f ) target[x + y * wid] = 1; else target[x + y * wid] = 0; memcpy( field, target, wid * hei ); } void flipCol( int c ) { for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; } void flipRow( int r ) { for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; } void calcStartPos() { int flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1; for( int x = 0; x < flips; x++ ) { if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); } } void createField() { if( field ){ delete [] field; delete [] target; } int t = wid * hei; field = new byte[t]; target = new byte[t]; memset( field, 0, t ); memset( target, 0, t ); createTarget(); while( true ) { calcStartPos(); if( !solved() ) break; } } float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); } byte* field, *target; int wid, hei; }; int main( int argc, char* argv[] ) { srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( "pause" ); }
from random import randrange from copy import deepcopy from string import ascii_lowercase try: input = raw_input except: pass N = 3 board = [[0]* N for i in range(N)] def setbits(board, count=1): for i in range(count): board[randrange(N)][randrange(N)] ^= 1 def shuffle(board, count=1): for i in range(count): if randrange(0, 2): fliprow(randrange(N)) else: flipcol(randrange(N)) def pr(board, comment=''): print(str(comment)) print(' ' + ' '.join(ascii_lowercase[i] for i in range(N))) print(' ' + '\n '.join(' '.join(['%2s' % j] + [str(i) for i in line]) for j, line in enumerate(board, 1))) def init(board): setbits(board, count=randrange(N)+1) target = deepcopy(board) while board == target: shuffle(board, count=2 * N) prompt = ' X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0], ascii_lowercase[N-1]) return target, prompt def fliprow(i): board[i-1][:] = [x ^ 1 for x in board[i-1] ] def flipcol(i): for row in board: row[i] ^= 1 if __name__ == '__main__': print(__doc__ % (N, N)) target, prompt = init(board) pr(target, 'Target configuration is:') print('') turns = 0 while board != target: turns += 1 pr(board, '%i:' % turns) ans = input(prompt).strip() if (len(ans) == 1 and ans in ascii_lowercase and ascii_lowercase.index(ans) < N): flipcol(ascii_lowercase.index(ans)) elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N: fliprow(int(ans)) elif ans == 'T': pr(target, 'Target configuration is:') turns -= 1 elif ans == 'X': break else: print(" I don't understand %r... Try again. " "(X to exit or T to show target)\n" % ans[:9]) turns -= 1 else: print('\nWell done!\nBye.')
Write the same code in Python as shown below in C++.
#include <time.h> #include <iostream> #include <string> typedef unsigned char byte; using namespace std; class flip { public: flip() { field = 0; target = 0; } void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); } private: void gameLoop() { int moves = 0; while( !solved() ) { display(); string r; cout << "Enter rows letters and/or column numbers: "; cin >> r; for( string::iterator i = r.begin(); i != r.end(); i++ ) { byte ii = ( *i ); if( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; } else if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; } } } cout << endl << endl << "** Well done! **" << endl << "Used " << moves << " moves." << endl << endl; } void display() { system( "cls" ); output( "TARGET:", target ); output( "YOU:", field ); } void output( string t, byte* f ) { cout << t << endl; cout << " "; for( int x = 0; x < wid; x++ ) cout << " " << static_cast<char>( x + '1' ); cout << endl; for( int y = 0; y < hei; y++ ) { cout << static_cast<char>( y + 'a' ) << " "; for( int x = 0; x < wid; x++ ) cout << static_cast<char>( f[x + y * wid] + 48 ) << " "; cout << endl; } cout << endl << endl; } bool solved() { for( int y = 0; y < hei; y++ ) for( int x = 0; x < wid; x++ ) if( target[x + y * wid] != field[x + y * wid] ) return false; return true; } void createTarget() { for( int y = 0; y < hei; y++ ) for( int x = 0; x < wid; x++ ) if( frnd() < .5f ) target[x + y * wid] = 1; else target[x + y * wid] = 0; memcpy( field, target, wid * hei ); } void flipCol( int c ) { for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; } void flipRow( int r ) { for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; } void calcStartPos() { int flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1; for( int x = 0; x < flips; x++ ) { if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); } } void createField() { if( field ){ delete [] field; delete [] target; } int t = wid * hei; field = new byte[t]; target = new byte[t]; memset( field, 0, t ); memset( target, 0, t ); createTarget(); while( true ) { calcStartPos(); if( !solved() ) break; } } float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); } byte* field, *target; int wid, hei; }; int main( int argc, char* argv[] ) { srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( "pause" ); }
from random import randrange from copy import deepcopy from string import ascii_lowercase try: input = raw_input except: pass N = 3 board = [[0]* N for i in range(N)] def setbits(board, count=1): for i in range(count): board[randrange(N)][randrange(N)] ^= 1 def shuffle(board, count=1): for i in range(count): if randrange(0, 2): fliprow(randrange(N)) else: flipcol(randrange(N)) def pr(board, comment=''): print(str(comment)) print(' ' + ' '.join(ascii_lowercase[i] for i in range(N))) print(' ' + '\n '.join(' '.join(['%2s' % j] + [str(i) for i in line]) for j, line in enumerate(board, 1))) def init(board): setbits(board, count=randrange(N)+1) target = deepcopy(board) while board == target: shuffle(board, count=2 * N) prompt = ' X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0], ascii_lowercase[N-1]) return target, prompt def fliprow(i): board[i-1][:] = [x ^ 1 for x in board[i-1] ] def flipcol(i): for row in board: row[i] ^= 1 if __name__ == '__main__': print(__doc__ % (N, N)) target, prompt = init(board) pr(target, 'Target configuration is:') print('') turns = 0 while board != target: turns += 1 pr(board, '%i:' % turns) ans = input(prompt).strip() if (len(ans) == 1 and ans in ascii_lowercase and ascii_lowercase.index(ans) < N): flipcol(ascii_lowercase.index(ans)) elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N: fliprow(int(ans)) elif ans == 'T': pr(target, 'Target configuration is:') turns -= 1 elif ans == 'X': break else: print(" I don't understand %r... Try again. " "(X to exit or T to show target)\n" % ans[:9]) turns -= 1 else: print('\nWell done!\nBye.')
Produce a functionally identical Python code for the snippet given in C++.
#include <time.h> #include <iostream> #include <string> typedef unsigned char byte; using namespace std; class flip { public: flip() { field = 0; target = 0; } void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); } private: void gameLoop() { int moves = 0; while( !solved() ) { display(); string r; cout << "Enter rows letters and/or column numbers: "; cin >> r; for( string::iterator i = r.begin(); i != r.end(); i++ ) { byte ii = ( *i ); if( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; } else if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; } } } cout << endl << endl << "** Well done! **" << endl << "Used " << moves << " moves." << endl << endl; } void display() { system( "cls" ); output( "TARGET:", target ); output( "YOU:", field ); } void output( string t, byte* f ) { cout << t << endl; cout << " "; for( int x = 0; x < wid; x++ ) cout << " " << static_cast<char>( x + '1' ); cout << endl; for( int y = 0; y < hei; y++ ) { cout << static_cast<char>( y + 'a' ) << " "; for( int x = 0; x < wid; x++ ) cout << static_cast<char>( f[x + y * wid] + 48 ) << " "; cout << endl; } cout << endl << endl; } bool solved() { for( int y = 0; y < hei; y++ ) for( int x = 0; x < wid; x++ ) if( target[x + y * wid] != field[x + y * wid] ) return false; return true; } void createTarget() { for( int y = 0; y < hei; y++ ) for( int x = 0; x < wid; x++ ) if( frnd() < .5f ) target[x + y * wid] = 1; else target[x + y * wid] = 0; memcpy( field, target, wid * hei ); } void flipCol( int c ) { for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; } void flipRow( int r ) { for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; } void calcStartPos() { int flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1; for( int x = 0; x < flips; x++ ) { if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); } } void createField() { if( field ){ delete [] field; delete [] target; } int t = wid * hei; field = new byte[t]; target = new byte[t]; memset( field, 0, t ); memset( target, 0, t ); createTarget(); while( true ) { calcStartPos(); if( !solved() ) break; } } float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); } byte* field, *target; int wid, hei; }; int main( int argc, char* argv[] ) { srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( "pause" ); }
from random import randrange from copy import deepcopy from string import ascii_lowercase try: input = raw_input except: pass N = 3 board = [[0]* N for i in range(N)] def setbits(board, count=1): for i in range(count): board[randrange(N)][randrange(N)] ^= 1 def shuffle(board, count=1): for i in range(count): if randrange(0, 2): fliprow(randrange(N)) else: flipcol(randrange(N)) def pr(board, comment=''): print(str(comment)) print(' ' + ' '.join(ascii_lowercase[i] for i in range(N))) print(' ' + '\n '.join(' '.join(['%2s' % j] + [str(i) for i in line]) for j, line in enumerate(board, 1))) def init(board): setbits(board, count=randrange(N)+1) target = deepcopy(board) while board == target: shuffle(board, count=2 * N) prompt = ' X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0], ascii_lowercase[N-1]) return target, prompt def fliprow(i): board[i-1][:] = [x ^ 1 for x in board[i-1] ] def flipcol(i): for row in board: row[i] ^= 1 if __name__ == '__main__': print(__doc__ % (N, N)) target, prompt = init(board) pr(target, 'Target configuration is:') print('') turns = 0 while board != target: turns += 1 pr(board, '%i:' % turns) ans = input(prompt).strip() if (len(ans) == 1 and ans in ascii_lowercase and ascii_lowercase.index(ans) < N): flipcol(ascii_lowercase.index(ans)) elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N: fliprow(int(ans)) elif ans == 'T': pr(target, 'Target configuration is:') turns -= 1 elif ans == 'X': break else: print(" I don't understand %r... Try again. " "(X to exit or T to show target)\n" % ans[:9]) turns -= 1 else: print('\nWell done!\nBye.')
Write the same algorithm in Python as shown in this C++ implementation.
#include <iostream> #include <iomanip> #include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/math/constants/constants.hpp> typedef boost::multiprecision::cpp_dec_float_50 decfloat; int main() { const decfloat ln_two = boost::math::constants::ln_two<decfloat>(); decfloat numerator = 1, denominator = ln_two; for(int n = 1; n <= 17; n++) { decfloat h = (numerator *= n) / (denominator *= ln_two) / 2; decfloat tenths_dig = floor((h - floor(h)) * 10); std::cout << "h(" << std::setw(2) << n << ") = " << std::setw(25) << std::fixed << h << (tenths_dig == 0 || tenths_dig == 9 ? " is " : " is NOT ") << "an almost-integer.\n"; } }
from decimal import Decimal import math def h(n): 'Simple, reduced precision calculation' return math.factorial(n) / (2 * math.log(2) ** (n + 1)) def h2(n): 'Extended precision Hickerson function' return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1)) for n in range(18): x = h2(n) norm = str(x.normalize()) almostinteger = (' Nearly integer' if 'E' not in norm and ('.0' in norm or '.9' in norm) else ' NOT nearly integer!') print('n:%2i h:%s%s' % (n, norm, almostinteger))
Convert the following code from C++ to Python, ensuring the logic remains intact.
#include <iostream> #include <iomanip> #include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/math/constants/constants.hpp> typedef boost::multiprecision::cpp_dec_float_50 decfloat; int main() { const decfloat ln_two = boost::math::constants::ln_two<decfloat>(); decfloat numerator = 1, denominator = ln_two; for(int n = 1; n <= 17; n++) { decfloat h = (numerator *= n) / (denominator *= ln_two) / 2; decfloat tenths_dig = floor((h - floor(h)) * 10); std::cout << "h(" << std::setw(2) << n << ") = " << std::setw(25) << std::fixed << h << (tenths_dig == 0 || tenths_dig == 9 ? " is " : " is NOT ") << "an almost-integer.\n"; } }
from decimal import Decimal import math def h(n): 'Simple, reduced precision calculation' return math.factorial(n) / (2 * math.log(2) ** (n + 1)) def h2(n): 'Extended precision Hickerson function' return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1)) for n in range(18): x = h2(n) norm = str(x.normalize()) almostinteger = (' Nearly integer' if 'E' not in norm and ('.0' in norm or '.9' in norm) else ' NOT nearly integer!') print('n:%2i h:%s%s' % (n, norm, almostinteger))
Ensure the translated Python code behaves exactly like the original C++ snippet.
#include <random> #include <random> #include <vector> #include <iostream> #define MAX_N 20 #define TIMES 1000000 static std::random_device rd; static std::mt19937 gen(rd()); static std::uniform_int_distribution<> dis; int randint(int n) { int r, rmax = RAND_MAX / n * n; dis=std::uniform_int_distribution<int>(0,rmax) ; r = dis(gen); return r / (RAND_MAX / n); } unsigned long long factorial(size_t n) { static std::vector<unsigned long long>factorials{1,1,2}; for (;factorials.size() <= n;) factorials.push_back(((unsigned long long) factorials.back())*factorials.size()); return factorials[n]; } long double expected(size_t n) { long double sum = 0; for (size_t i = 1; i <= n; i++) sum += factorial(n) / pow(n, i) / factorial(n - i); return sum; } int test(int n, int times) { int i, count = 0; for (i = 0; i < times; i++) { unsigned int x = 1, bits = 0; while (!(bits & x)) { count++; bits |= x; x = static_cast<unsigned int>(1 << randint(n)); } } return count; } int main() { puts(" n\tavg\texp.\tdiff\n-------------------------------"); int n; for (n = 1; n <= MAX_N; n++) { int cnt = test(n, TIMES); long double avg = (double)cnt / TIMES; long double theory = expected(static_cast<size_t>(n)); long double diff = (avg / theory - 1) * 100; printf("%2d %8.4f %8.4f %6.3f%%\n", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff)); } return 0; }
from __future__ import division from math import factorial from random import randrange MAX_N = 20 TIMES = 1000000 def analytical(n): return sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1)) def test(n, times): count = 0 for i in range(times): x, bits = 1, 0 while not (bits & x): count += 1 bits |= x x = 1 << randrange(n) return count / times if __name__ == '__main__': print(" n\tavg\texp.\tdiff\n-------------------------------") for n in range(1, MAX_N+1): avg = test(n, TIMES) theory = analytical(n) diff = (avg / theory - 1) * 100 print("%2d %8.4f %8.4f %6.3f%%" % (n, avg, theory, diff))
Write the same code in Python as shown below in C++.
#include <random> #include <random> #include <vector> #include <iostream> #define MAX_N 20 #define TIMES 1000000 static std::random_device rd; static std::mt19937 gen(rd()); static std::uniform_int_distribution<> dis; int randint(int n) { int r, rmax = RAND_MAX / n * n; dis=std::uniform_int_distribution<int>(0,rmax) ; r = dis(gen); return r / (RAND_MAX / n); } unsigned long long factorial(size_t n) { static std::vector<unsigned long long>factorials{1,1,2}; for (;factorials.size() <= n;) factorials.push_back(((unsigned long long) factorials.back())*factorials.size()); return factorials[n]; } long double expected(size_t n) { long double sum = 0; for (size_t i = 1; i <= n; i++) sum += factorial(n) / pow(n, i) / factorial(n - i); return sum; } int test(int n, int times) { int i, count = 0; for (i = 0; i < times; i++) { unsigned int x = 1, bits = 0; while (!(bits & x)) { count++; bits |= x; x = static_cast<unsigned int>(1 << randint(n)); } } return count; } int main() { puts(" n\tavg\texp.\tdiff\n-------------------------------"); int n; for (n = 1; n <= MAX_N; n++) { int cnt = test(n, TIMES); long double avg = (double)cnt / TIMES; long double theory = expected(static_cast<size_t>(n)); long double diff = (avg / theory - 1) * 100; printf("%2d %8.4f %8.4f %6.3f%%\n", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff)); } return 0; }
from __future__ import division from math import factorial from random import randrange MAX_N = 20 TIMES = 1000000 def analytical(n): return sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1)) def test(n, times): count = 0 for i in range(times): x, bits = 1, 0 while not (bits & x): count += 1 bits |= x x = 1 << randrange(n) return count / times if __name__ == '__main__': print(" n\tavg\texp.\tdiff\n-------------------------------") for n in range(1, MAX_N+1): avg = test(n, TIMES) theory = analytical(n) diff = (avg / theory - 1) * 100 print("%2d %8.4f %8.4f %6.3f%%" % (n, avg, theory, diff))
Translate the given C++ code snippet into Python without altering its behavior.
#include <string> #include <iostream> int main( ) { std::string original( "Mary had a X lamb." ) , toBeReplaced( "X" ) , replacement ( "little" ) ; std::string newString = original.replace( original.find( "X" ) , toBeReplaced.length( ) , replacement ) ; std::cout << "String after replacement: " << newString << " \n" ; return 0 ; }
>>> original = 'Mary had a %s lamb.' >>> extra = 'little' >>> original % extra 'Mary had a little lamb.'
Translate the given C++ code snippet into Python without altering its behavior.
#include <string> #include <iostream> int main( ) { std::string original( "Mary had a X lamb." ) , toBeReplaced( "X" ) , replacement ( "little" ) ; std::string newString = original.replace( original.find( "X" ) , toBeReplaced.length( ) , replacement ) ; std::cout << "String after replacement: " << newString << " \n" ; return 0 ; }
>>> original = 'Mary had a %s lamb.' >>> extra = 'little' >>> original % extra 'Mary had a little lamb.'
Port the following code from C++ to Python with equivalent syntax and logic.
#include <iostream> #include <vector> #include <stack> #include <iterator> #include <algorithm> #include <cassert> template <class E> struct pile_less { bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const { return pile1.top() < pile2.top(); } }; template <class E> struct pile_greater { bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const { return pile1.top() > pile2.top(); } }; template <class Iterator> void patience_sort(Iterator first, Iterator last) { typedef typename std::iterator_traits<Iterator>::value_type E; typedef std::stack<E> Pile; std::vector<Pile> piles; for (Iterator it = first; it != last; it++) { E& x = *it; Pile newPile; newPile.push(x); typename std::vector<Pile>::iterator i = std::lower_bound(piles.begin(), piles.end(), newPile, pile_less<E>()); if (i != piles.end()) i->push(x); else piles.push_back(newPile); } std::make_heap(piles.begin(), piles.end(), pile_greater<E>()); for (Iterator it = first; it != last; it++) { std::pop_heap(piles.begin(), piles.end(), pile_greater<E>()); Pile &smallPile = piles.back(); *it = smallPile.top(); smallPile.pop(); if (smallPile.empty()) piles.pop_back(); else std::push_heap(piles.begin(), piles.end(), pile_greater<E>()); } assert(piles.empty()); } int main() { int a[] = {4, 65, 2, -31, 0, 99, 83, 782, 1}; patience_sort(a, a+sizeof(a)/sizeof(*a)); std::copy(a, a+sizeof(a)/sizeof(*a), std::ostream_iterator<int>(std::cout, ", ")); std::cout << std::endl; return 0; }
from functools import total_ordering from bisect import bisect_left from heapq import merge @total_ordering class Pile(list): def __lt__(self, other): return self[-1] < other[-1] def __eq__(self, other): return self[-1] == other[-1] def patience_sort(n): piles = [] for x in n: new_pile = Pile([x]) i = bisect_left(piles, new_pile) if i != len(piles): piles[i].append(x) else: piles.append(new_pile) n[:] = merge(*[reversed(pile) for pile in piles]) if __name__ == "__main__": a = [4, 65, 2, -31, 0, 99, 83, 782, 1] patience_sort(a) print a
Translate the given C++ code snippet into Python without altering its behavior.
#include <array> #include <iomanip> #include <iostream> #include <random> #include <string> class sequence_generator { public: sequence_generator(); std::string generate_sequence(size_t length); void mutate_sequence(std::string&); static void print_sequence(std::ostream&, const std::string&); enum class operation { change, erase, insert }; void set_weight(operation, unsigned int); private: char get_random_base() { return bases_[base_dist_(engine_)]; } operation get_random_operation(); static const std::array<char, 4> bases_; std::mt19937 engine_; std::uniform_int_distribution<size_t> base_dist_; std::array<unsigned int, 3> operation_weight_; unsigned int total_weight_; }; const std::array<char, 4> sequence_generator::bases_{ 'A', 'C', 'G', 'T' }; sequence_generator::sequence_generator() : engine_(std::random_device()()), base_dist_(0, bases_.size() - 1), total_weight_(operation_weight_.size()) { operation_weight_.fill(1); } sequence_generator::operation sequence_generator::get_random_operation() { std::uniform_int_distribution<unsigned int> op_dist(0, total_weight_ - 1); unsigned int n = op_dist(engine_), op = 0, weight = 0; for (; op < operation_weight_.size(); ++op) { weight += operation_weight_[op]; if (n < weight) break; } return static_cast<operation>(op); } void sequence_generator::set_weight(operation op, unsigned int weight) { total_weight_ -= operation_weight_[static_cast<size_t>(op)]; operation_weight_[static_cast<size_t>(op)] = weight; total_weight_ += weight; } std::string sequence_generator::generate_sequence(size_t length) { std::string sequence; sequence.reserve(length); for (size_t i = 0; i < length; ++i) sequence += get_random_base(); return sequence; } void sequence_generator::mutate_sequence(std::string& sequence) { std::uniform_int_distribution<size_t> dist(0, sequence.length() - 1); size_t pos = dist(engine_); char b; switch (get_random_operation()) { case operation::change: b = get_random_base(); std::cout << "Change base at position " << pos << " from " << sequence[pos] << " to " << b << '\n'; sequence[pos] = b; break; case operation::erase: std::cout << "Erase base " << sequence[pos] << " at position " << pos << '\n'; sequence.erase(pos, 1); break; case operation::insert: b = get_random_base(); std::cout << "Insert base " << b << " at position " << pos << '\n'; sequence.insert(pos, 1, b); break; } } void sequence_generator::print_sequence(std::ostream& out, const std::string& sequence) { constexpr size_t base_count = bases_.size(); std::array<size_t, base_count> count = { 0 }; for (size_t i = 0, n = sequence.length(); i < n; ++i) { if (i % 50 == 0) { if (i != 0) out << '\n'; out << std::setw(3) << i << ": "; } out << sequence[i]; for (size_t j = 0; j < base_count; ++j) { if (bases_[j] == sequence[i]) { ++count[j]; break; } } } out << '\n'; out << "Base counts:\n"; size_t total = 0; for (size_t j = 0; j < base_count; ++j) { total += count[j]; out << bases_[j] << ": " << count[j] << ", "; } out << "Total: " << total << '\n'; } int main() { sequence_generator gen; gen.set_weight(sequence_generator::operation::change, 2); std::string sequence = gen.generate_sequence(250); std::cout << "Initial sequence:\n"; sequence_generator::print_sequence(std::cout, sequence); constexpr int count = 10; for (int i = 0; i < count; ++i) gen.mutate_sequence(sequence); std::cout << "After " << count << " mutations:\n"; sequence_generator::print_sequence(std::cout, sequence); return 0; }
import random from collections import Counter def basecount(dna): return sorted(Counter(dna).items()) def seq_split(dna, n=50): return [dna[i: i+n] for i in range(0, len(dna), n)] def seq_pp(dna, n=50): for i, part in enumerate(seq_split(dna, n)): print(f"{i*n:>5}: {part}") print("\n BASECOUNT:") tot = 0 for base, count in basecount(dna): print(f" {base:>3}: {count}") tot += count base, count = 'TOT', tot print(f" {base:>3}= {count}") def seq_mutate(dna, count=1, kinds="IDSSSS", choice="ATCG" ): mutation = [] k2txt = dict(I='Insert', D='Delete', S='Substitute') for _ in range(count): kind = random.choice(kinds) index = random.randint(0, len(dna)) if kind == 'I': dna = dna[:index] + random.choice(choice) + dna[index:] elif kind == 'D' and dna: dna = dna[:index] + dna[index+1:] elif kind == 'S' and dna: dna = dna[:index] + random.choice(choice) + dna[index+1:] mutation.append((k2txt[kind], index)) return dna, mutation if __name__ == '__main__': length = 250 print("SEQUENCE:") sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length)) seq_pp(sequence) print("\n\nMUTATIONS:") mseq, m = seq_mutate(sequence, 10) for kind, index in m: print(f" {kind:>10} @{index}") print() seq_pp(mseq)
Can you help me rewrite this code in Python instead of C++, keeping it the same logically?
#include <array> #include <iomanip> #include <iostream> #include <random> #include <string> class sequence_generator { public: sequence_generator(); std::string generate_sequence(size_t length); void mutate_sequence(std::string&); static void print_sequence(std::ostream&, const std::string&); enum class operation { change, erase, insert }; void set_weight(operation, unsigned int); private: char get_random_base() { return bases_[base_dist_(engine_)]; } operation get_random_operation(); static const std::array<char, 4> bases_; std::mt19937 engine_; std::uniform_int_distribution<size_t> base_dist_; std::array<unsigned int, 3> operation_weight_; unsigned int total_weight_; }; const std::array<char, 4> sequence_generator::bases_{ 'A', 'C', 'G', 'T' }; sequence_generator::sequence_generator() : engine_(std::random_device()()), base_dist_(0, bases_.size() - 1), total_weight_(operation_weight_.size()) { operation_weight_.fill(1); } sequence_generator::operation sequence_generator::get_random_operation() { std::uniform_int_distribution<unsigned int> op_dist(0, total_weight_ - 1); unsigned int n = op_dist(engine_), op = 0, weight = 0; for (; op < operation_weight_.size(); ++op) { weight += operation_weight_[op]; if (n < weight) break; } return static_cast<operation>(op); } void sequence_generator::set_weight(operation op, unsigned int weight) { total_weight_ -= operation_weight_[static_cast<size_t>(op)]; operation_weight_[static_cast<size_t>(op)] = weight; total_weight_ += weight; } std::string sequence_generator::generate_sequence(size_t length) { std::string sequence; sequence.reserve(length); for (size_t i = 0; i < length; ++i) sequence += get_random_base(); return sequence; } void sequence_generator::mutate_sequence(std::string& sequence) { std::uniform_int_distribution<size_t> dist(0, sequence.length() - 1); size_t pos = dist(engine_); char b; switch (get_random_operation()) { case operation::change: b = get_random_base(); std::cout << "Change base at position " << pos << " from " << sequence[pos] << " to " << b << '\n'; sequence[pos] = b; break; case operation::erase: std::cout << "Erase base " << sequence[pos] << " at position " << pos << '\n'; sequence.erase(pos, 1); break; case operation::insert: b = get_random_base(); std::cout << "Insert base " << b << " at position " << pos << '\n'; sequence.insert(pos, 1, b); break; } } void sequence_generator::print_sequence(std::ostream& out, const std::string& sequence) { constexpr size_t base_count = bases_.size(); std::array<size_t, base_count> count = { 0 }; for (size_t i = 0, n = sequence.length(); i < n; ++i) { if (i % 50 == 0) { if (i != 0) out << '\n'; out << std::setw(3) << i << ": "; } out << sequence[i]; for (size_t j = 0; j < base_count; ++j) { if (bases_[j] == sequence[i]) { ++count[j]; break; } } } out << '\n'; out << "Base counts:\n"; size_t total = 0; for (size_t j = 0; j < base_count; ++j) { total += count[j]; out << bases_[j] << ": " << count[j] << ", "; } out << "Total: " << total << '\n'; } int main() { sequence_generator gen; gen.set_weight(sequence_generator::operation::change, 2); std::string sequence = gen.generate_sequence(250); std::cout << "Initial sequence:\n"; sequence_generator::print_sequence(std::cout, sequence); constexpr int count = 10; for (int i = 0; i < count; ++i) gen.mutate_sequence(sequence); std::cout << "After " << count << " mutations:\n"; sequence_generator::print_sequence(std::cout, sequence); return 0; }
import random from collections import Counter def basecount(dna): return sorted(Counter(dna).items()) def seq_split(dna, n=50): return [dna[i: i+n] for i in range(0, len(dna), n)] def seq_pp(dna, n=50): for i, part in enumerate(seq_split(dna, n)): print(f"{i*n:>5}: {part}") print("\n BASECOUNT:") tot = 0 for base, count in basecount(dna): print(f" {base:>3}: {count}") tot += count base, count = 'TOT', tot print(f" {base:>3}= {count}") def seq_mutate(dna, count=1, kinds="IDSSSS", choice="ATCG" ): mutation = [] k2txt = dict(I='Insert', D='Delete', S='Substitute') for _ in range(count): kind = random.choice(kinds) index = random.randint(0, len(dna)) if kind == 'I': dna = dna[:index] + random.choice(choice) + dna[index:] elif kind == 'D' and dna: dna = dna[:index] + dna[index+1:] elif kind == 'S' and dna: dna = dna[:index] + random.choice(choice) + dna[index+1:] mutation.append((k2txt[kind], index)) return dna, mutation if __name__ == '__main__': length = 250 print("SEQUENCE:") sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length)) seq_pp(sequence) print("\n\nMUTATIONS:") mseq, m = seq_mutate(sequence, 10) for kind, index in m: print(f" {kind:>10} @{index}") print() seq_pp(mseq)
Change the following C++ code into Python without altering its purpose.
#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; } int main() { const unsigned int limit = 100; std::cout << "The first " << limit << " tau numbers are:\n"; unsigned int count = 0; for (unsigned int n = 1; count < limit; ++n) { if (n % divisor_count(n) == 0) { std::cout << std::setw(6) << n; ++count; if (count % 10 == 0) std::cout << '\n'; } } }
def tau(n): assert(isinstance(n, int) and 0 < n) ans, i, j = 0, 1, 1 while i*i <= n: if 0 == n%i: ans += 1 j = n//i if j != i: ans += 1 i += 1 return ans def is_tau_number(n): assert(isinstance(n, int)) if n <= 0: return False return 0 == n%tau(n) if __name__ == "__main__": n = 1 ans = [] while len(ans) < 100: if is_tau_number(n): ans.append(n) n += 1 print(ans)
Rewrite this program in Python while keeping its functionality equivalent to the C++ version.
#include <iostream> #include <vector> template <typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *it; it = std::next(it); } return os << ']'; } using Matrix = std::vector<std::vector<double>>; Matrix squareMatrix(size_t n) { Matrix m; for (size_t i = 0; i < n; i++) { std::vector<double> inner; for (size_t j = 0; j < n; j++) { inner.push_back(nan("")); } m.push_back(inner); } return m; } Matrix minor(const Matrix &a, int x, int y) { auto length = a.size() - 1; auto result = squareMatrix(length); for (int i = 0; i < length; i++) { for (int j = 0; j < length; j++) { if (i < x && j < y) { result[i][j] = a[i][j]; } else if (i >= x && j < y) { result[i][j] = a[i + 1][j]; } else if (i < x && j >= y) { result[i][j] = a[i][j + 1]; } else { result[i][j] = a[i + 1][j + 1]; } } } return result; } double det(const Matrix &a) { if (a.size() == 1) { return a[0][0]; } int sign = 1; double sum = 0; for (size_t i = 0; i < a.size(); i++) { sum += sign * a[0][i] * det(minor(a, 0, i)); sign *= -1; } return sum; } double perm(const Matrix &a) { if (a.size() == 1) { return a[0][0]; } double sum = 0; for (size_t i = 0; i < a.size(); i++) { sum += a[0][i] * perm(minor(a, 0, i)); } return sum; } void test(const Matrix &m) { auto p = perm(m); auto d = det(m); std::cout << m << '\n'; std::cout << "Permanent: " << p << ", determinant: " << d << "\n\n"; } int main() { test({ {1, 2}, {3, 4} }); test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} }); test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} }); return 0; }
from itertools import permutations from operator import mul from math import fsum from spermutations import spermutations def prod(lst): return reduce(mul, lst, 1) def perm(a): n = len(a) r = range(n) s = permutations(r) return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s) def det(a): n = len(a) r = range(n) s = spermutations(n) return fsum(sign * prod(a[i][sigma[i]] for i in r) for sigma, sign in s) if __name__ == '__main__': from pprint import pprint as pp for a in ( [ [1, 2], [3, 4]], [ [1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10], [10, 11, 12, 13]], [ [ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]], ): print('') pp(a) print('Perm: %s Det: %s' % (perm(a), det(a)))
Please provide an equivalent version of this C++ code in Python.
#include <iostream> #include <vector> template <typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *it; it = std::next(it); } return os << ']'; } using Matrix = std::vector<std::vector<double>>; Matrix squareMatrix(size_t n) { Matrix m; for (size_t i = 0; i < n; i++) { std::vector<double> inner; for (size_t j = 0; j < n; j++) { inner.push_back(nan("")); } m.push_back(inner); } return m; } Matrix minor(const Matrix &a, int x, int y) { auto length = a.size() - 1; auto result = squareMatrix(length); for (int i = 0; i < length; i++) { for (int j = 0; j < length; j++) { if (i < x && j < y) { result[i][j] = a[i][j]; } else if (i >= x && j < y) { result[i][j] = a[i + 1][j]; } else if (i < x && j >= y) { result[i][j] = a[i][j + 1]; } else { result[i][j] = a[i + 1][j + 1]; } } } return result; } double det(const Matrix &a) { if (a.size() == 1) { return a[0][0]; } int sign = 1; double sum = 0; for (size_t i = 0; i < a.size(); i++) { sum += sign * a[0][i] * det(minor(a, 0, i)); sign *= -1; } return sum; } double perm(const Matrix &a) { if (a.size() == 1) { return a[0][0]; } double sum = 0; for (size_t i = 0; i < a.size(); i++) { sum += a[0][i] * perm(minor(a, 0, i)); } return sum; } void test(const Matrix &m) { auto p = perm(m); auto d = det(m); std::cout << m << '\n'; std::cout << "Permanent: " << p << ", determinant: " << d << "\n\n"; } int main() { test({ {1, 2}, {3, 4} }); test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} }); test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} }); return 0; }
from itertools import permutations from operator import mul from math import fsum from spermutations import spermutations def prod(lst): return reduce(mul, lst, 1) def perm(a): n = len(a) r = range(n) s = permutations(r) return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s) def det(a): n = len(a) r = range(n) s = spermutations(n) return fsum(sign * prod(a[i][sigma[i]] for i in r) for sigma, sign in s) if __name__ == '__main__': from pprint import pprint as pp for a in ( [ [1, 2], [3, 4]], [ [1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10], [10, 11, 12, 13]], [ [ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]], ): print('') pp(a) print('Perm: %s Det: %s' % (perm(a), det(a)))
Change the programming language of this snippet from C++ to Python without modifying what it does.
#include <chrono> #include <iostream> #include <vector> #include <gmpxx.h> using big_int = mpz_class; big_int partitions(int n) { std::vector<big_int> p(n + 1); p[0] = 1; for (int i = 1; i <= n; ++i) { for (int k = 1;; ++k) { int j = (k * (3*k - 1))/2; if (j > i) break; if (k & 1) p[i] += p[i - j]; else p[i] -= p[i - j]; j = (k * (3*k + 1))/2; if (j > i) break; if (k & 1) p[i] += p[i - j]; else p[i] -= p[i - j]; } } return p[n]; } int main() { auto start = std::chrono::steady_clock::now(); auto result = partitions(6666); auto end = std::chrono::steady_clock::now(); std::chrono::duration<double, std::milli> ms(end - start); std::cout << result << '\n'; std::cout << "elapsed time: " << ms.count() << " milliseconds\n"; }
from itertools import islice def posd(): "diff between position numbers. 1, 2, 3... interleaved with 3, 5, 7..." count, odd = 1, 3 while True: yield count yield odd count, odd = count + 1, odd + 2 def pos_gen(): "position numbers. 1 3 2 5 7 4 9 ..." val = 1 diff = posd() while True: yield val val += next(diff) def plus_minus(): "yield (list_offset, sign) or zero for Partition calc" n, sign = 0, [1, 1] p_gen = pos_gen() out_on = next(p_gen) while True: n += 1 if n == out_on: next_sign = sign.pop(0) if not sign: sign = [-next_sign] * 2 yield -n, next_sign out_on = next(p_gen) else: yield 0 def part(n): "Partition numbers" p = [1] p_m = plus_minus() mods = [] for _ in range(n): next_plus_minus = next(p_m) if next_plus_minus: mods.append(next_plus_minus) p.append(sum(p[offset] * sign for offset, sign in mods)) return p[-1] print("(Intermediaries):") print(" posd:", list(islice(posd(), 10))) print(" pos_gen:", list(islice(pos_gen(), 10))) print(" plus_minus:", list(islice(plus_minus(), 15))) print("\nPartitions:", [part(x) for x in range(15)])
Produce a language-to-language conversion: from C++ to Python, same semantics.
#include <ggi/ggi.h> #include <set> #include <map> #include <utility> #include <iostream> #include <fstream> #include <string> #include <unistd.h> enum cell_type { none, wire, head, tail }; class display { public: display(int sizex, int sizey, int pixsizex, int pixsizey, ggi_color* colors); ~display() { ggiClose(visual); ggiExit(); } void flush(); bool keypressed() { return ggiKbhit(visual); } void clear(); void putpixel(int x, int y, cell_type c); private: ggi_visual_t visual; int size_x, size_y; int pixel_size_x, pixel_size_y; ggi_pixel pixels[4]; }; display::display(int sizex, int sizey, int pixsizex, int pixsizey, ggi_color* colors): pixel_size_x(pixsizex), pixel_size_y(pixsizey) { if (ggiInit() < 0) { std::cerr << "couldn't open ggi\n"; exit(1); } visual = ggiOpen(NULL); if (!visual) { ggiPanic("couldn't open visual\n"); } ggi_mode mode; if (ggiCheckGraphMode(visual, sizex, sizey, GGI_AUTO, GGI_AUTO, GT_4BIT, &mode) != 0) { if (GT_DEPTH(mode.graphtype) < 2) ggiPanic("low-color displays are not supported!\n"); } if (ggiSetMode(visual, &mode) != 0) { ggiPanic("couldn't set graph mode\n"); } ggiAddFlags(visual, GGIFLAG_ASYNC); size_x = mode.virt.x; size_y = mode.virt.y; for (int i = 0; i < 4; ++i) pixels[i] = ggiMapColor(visual, colors+i); } void display::flush() { ggiSetDisplayFrame(visual, ggiGetWriteFrame(visual)); ggiFlush(visual); ggiSetWriteFrame(visual, 1-ggiGetDisplayFrame(visual)); } void display::clear() { ggiSetGCForeground(visual, pixels[0]); ggiDrawBox(visual, 0, 0, size_x, size_y); } void display::putpixel(int x, int y, cell_type cell) { ggiSetGCForeground(visual, pixels[cell]); ggiDrawBox(visual, x*pixel_size_x, y*pixel_size_y, pixel_size_x, pixel_size_y); } class wireworld { public: void set(int posx, int posy, cell_type type); void draw(display& destination); void step(); private: typedef std::pair<int, int> position; typedef std::set<position> position_set; typedef position_set::iterator positer; position_set wires, heads, tails; }; void wireworld::set(int posx, int posy, cell_type type) { position p(posx, posy); wires.erase(p); heads.erase(p); tails.erase(p); switch(type) { case head: heads.insert(p); break; case tail: tails.insert(p); break; case wire: wires.insert(p); break; } } void wireworld::draw(display& destination) { destination.clear(); for (positer i = heads.begin(); i != heads.end(); ++i) destination.putpixel(i->first, i->second, head); for (positer i = tails.begin(); i != tails.end(); ++i) destination.putpixel(i->first, i->second, tail); for (positer i = wires.begin(); i != wires.end(); ++i) destination.putpixel(i->first, i->second, wire); destination.flush(); } void wireworld::step() { std::map<position, int> new_heads; for (positer i = heads.begin(); i != heads.end(); ++i) for (int dx = -1; dx <= 1; ++dx) for (int dy = -1; dy <= 1; ++dy) { position pos(i->first + dx, i->second + dy); if (wires.count(pos)) new_heads[pos]++; } wires.insert(tails.begin(), tails.end()); tails.swap(heads); heads.clear(); for (std::map<position, int>::iterator i = new_heads.begin(); i != new_heads.end(); ++i) { if (i->second < 3) { wires.erase(i->first); heads.insert(i->first); } } } ggi_color colors[4] = {{ 0x0000, 0x0000, 0x0000 }, { 0x8000, 0x8000, 0x8000 }, { 0xffff, 0xffff, 0x0000 }, { 0xffff, 0x0000, 0x0000 }}; int main(int argc, char* argv[]) { int display_x = 800; int display_y = 600; int pixel_x = 5; int pixel_y = 5; if (argc < 2) { std::cerr << "No file name given!\n"; return 1; } std::ifstream f(argv[1]); wireworld w; std::string line; int line_number = 0; while (std::getline(f, line)) { for (int col = 0; col < line.size(); ++col) { switch (line[col]) { case 'h': case 'H': w.set(col, line_number, head); break; case 't': case 'T': w.set(col, line_number, tail); break; case 'w': case 'W': case '.': w.set(col, line_number, wire); break; default: std::cerr << "unrecognized character: " << line[col] << "\n"; return 1; case ' ': ; } } ++line_number; } display d(display_x, display_y, pixel_x, pixel_y, colors); w.draw(d); while (!d.keypressed()) { usleep(100000); w.step(); w.draw(d); } std::cout << std::endl; }
from io import StringIO from collections import namedtuple from pprint import pprint as pp import copy WW = namedtuple('WW', 'world, w, h') head, tail, conductor, empty = allstates = 'Ht. ' infile = StringIO() def readfile(f): world = [row.rstrip('\r\n') for row in f] height = len(world) width = max(len(row) for row in world) nonrow = [ " %*s " % (-width, "") ] world = nonrow + \ [ " %*s " % (-width, row) for row in world ] + \ nonrow world = [list(row) for row in world] return WW(world, width, height) def newcell(currentworld, x, y): istate = currentworld[y][x] assert istate in allstates, 'Wireworld cell set to unknown value "%s"' % istate if istate == head: ostate = tail elif istate == tail: ostate = conductor elif istate == empty: ostate = empty else: n = sum( currentworld[y+dy][x+dx] == head for dx,dy in ( (-1,-1), (-1,+0), (-1,+1), (+0,-1), (+0,+1), (+1,-1), (+1,+0), (+1,+1) ) ) ostate = head if 1 <= n <= 2 else conductor return ostate def nextgen(ww): 'compute next generation of wireworld' world, width, height = ww newworld = copy.deepcopy(world) for x in range(1, width+1): for y in range(1, height+1): newworld[y][x] = newcell(world, x, y) return WW(newworld, width, height) def world2string(ww): return '\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] ) ww = readfile(infile) infile.close() for gen in range(10): print ( ("\n%3i " % gen) + '=' * (ww.w-4) + '\n' ) print ( world2string(ww) ) ww = nextgen(ww)
Generate a Python translation of this C++ snippet without changing its computational steps.
#include <ggi/ggi.h> #include <set> #include <map> #include <utility> #include <iostream> #include <fstream> #include <string> #include <unistd.h> enum cell_type { none, wire, head, tail }; class display { public: display(int sizex, int sizey, int pixsizex, int pixsizey, ggi_color* colors); ~display() { ggiClose(visual); ggiExit(); } void flush(); bool keypressed() { return ggiKbhit(visual); } void clear(); void putpixel(int x, int y, cell_type c); private: ggi_visual_t visual; int size_x, size_y; int pixel_size_x, pixel_size_y; ggi_pixel pixels[4]; }; display::display(int sizex, int sizey, int pixsizex, int pixsizey, ggi_color* colors): pixel_size_x(pixsizex), pixel_size_y(pixsizey) { if (ggiInit() < 0) { std::cerr << "couldn't open ggi\n"; exit(1); } visual = ggiOpen(NULL); if (!visual) { ggiPanic("couldn't open visual\n"); } ggi_mode mode; if (ggiCheckGraphMode(visual, sizex, sizey, GGI_AUTO, GGI_AUTO, GT_4BIT, &mode) != 0) { if (GT_DEPTH(mode.graphtype) < 2) ggiPanic("low-color displays are not supported!\n"); } if (ggiSetMode(visual, &mode) != 0) { ggiPanic("couldn't set graph mode\n"); } ggiAddFlags(visual, GGIFLAG_ASYNC); size_x = mode.virt.x; size_y = mode.virt.y; for (int i = 0; i < 4; ++i) pixels[i] = ggiMapColor(visual, colors+i); } void display::flush() { ggiSetDisplayFrame(visual, ggiGetWriteFrame(visual)); ggiFlush(visual); ggiSetWriteFrame(visual, 1-ggiGetDisplayFrame(visual)); } void display::clear() { ggiSetGCForeground(visual, pixels[0]); ggiDrawBox(visual, 0, 0, size_x, size_y); } void display::putpixel(int x, int y, cell_type cell) { ggiSetGCForeground(visual, pixels[cell]); ggiDrawBox(visual, x*pixel_size_x, y*pixel_size_y, pixel_size_x, pixel_size_y); } class wireworld { public: void set(int posx, int posy, cell_type type); void draw(display& destination); void step(); private: typedef std::pair<int, int> position; typedef std::set<position> position_set; typedef position_set::iterator positer; position_set wires, heads, tails; }; void wireworld::set(int posx, int posy, cell_type type) { position p(posx, posy); wires.erase(p); heads.erase(p); tails.erase(p); switch(type) { case head: heads.insert(p); break; case tail: tails.insert(p); break; case wire: wires.insert(p); break; } } void wireworld::draw(display& destination) { destination.clear(); for (positer i = heads.begin(); i != heads.end(); ++i) destination.putpixel(i->first, i->second, head); for (positer i = tails.begin(); i != tails.end(); ++i) destination.putpixel(i->first, i->second, tail); for (positer i = wires.begin(); i != wires.end(); ++i) destination.putpixel(i->first, i->second, wire); destination.flush(); } void wireworld::step() { std::map<position, int> new_heads; for (positer i = heads.begin(); i != heads.end(); ++i) for (int dx = -1; dx <= 1; ++dx) for (int dy = -1; dy <= 1; ++dy) { position pos(i->first + dx, i->second + dy); if (wires.count(pos)) new_heads[pos]++; } wires.insert(tails.begin(), tails.end()); tails.swap(heads); heads.clear(); for (std::map<position, int>::iterator i = new_heads.begin(); i != new_heads.end(); ++i) { if (i->second < 3) { wires.erase(i->first); heads.insert(i->first); } } } ggi_color colors[4] = {{ 0x0000, 0x0000, 0x0000 }, { 0x8000, 0x8000, 0x8000 }, { 0xffff, 0xffff, 0x0000 }, { 0xffff, 0x0000, 0x0000 }}; int main(int argc, char* argv[]) { int display_x = 800; int display_y = 600; int pixel_x = 5; int pixel_y = 5; if (argc < 2) { std::cerr << "No file name given!\n"; return 1; } std::ifstream f(argv[1]); wireworld w; std::string line; int line_number = 0; while (std::getline(f, line)) { for (int col = 0; col < line.size(); ++col) { switch (line[col]) { case 'h': case 'H': w.set(col, line_number, head); break; case 't': case 'T': w.set(col, line_number, tail); break; case 'w': case 'W': case '.': w.set(col, line_number, wire); break; default: std::cerr << "unrecognized character: " << line[col] << "\n"; return 1; case ' ': ; } } ++line_number; } display d(display_x, display_y, pixel_x, pixel_y, colors); w.draw(d); while (!d.keypressed()) { usleep(100000); w.step(); w.draw(d); } std::cout << std::endl; }
from io import StringIO from collections import namedtuple from pprint import pprint as pp import copy WW = namedtuple('WW', 'world, w, h') head, tail, conductor, empty = allstates = 'Ht. ' infile = StringIO() def readfile(f): world = [row.rstrip('\r\n') for row in f] height = len(world) width = max(len(row) for row in world) nonrow = [ " %*s " % (-width, "") ] world = nonrow + \ [ " %*s " % (-width, row) for row in world ] + \ nonrow world = [list(row) for row in world] return WW(world, width, height) def newcell(currentworld, x, y): istate = currentworld[y][x] assert istate in allstates, 'Wireworld cell set to unknown value "%s"' % istate if istate == head: ostate = tail elif istate == tail: ostate = conductor elif istate == empty: ostate = empty else: n = sum( currentworld[y+dy][x+dx] == head for dx,dy in ( (-1,-1), (-1,+0), (-1,+1), (+0,-1), (+0,+1), (+1,-1), (+1,+0), (+1,+1) ) ) ostate = head if 1 <= n <= 2 else conductor return ostate def nextgen(ww): 'compute next generation of wireworld' world, width, height = ww newworld = copy.deepcopy(world) for x in range(1, width+1): for y in range(1, height+1): newworld[y][x] = newcell(world, x, y) return WW(newworld, width, height) def world2string(ww): return '\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] ) ww = readfile(infile) infile.close() for gen in range(10): print ( ("\n%3i " % gen) + '=' * (ww.w-4) + '\n' ) print ( world2string(ww) ) ww = nextgen(ww)
Rewrite this program in Python while keeping its functionality equivalent to the C++ version.
#include <algorithm> #include <cstdlib> #include <iomanip> #include <iostream> #include <limits> using namespace std; const double epsilon = numeric_limits<float>().epsilon(); const numeric_limits<double> DOUBLE; const double MIN = DOUBLE.min(); const double MAX = DOUBLE.max(); struct Point { const double x, y; }; struct Edge { const Point a, b; bool operator()(const Point& p) const { if (a.y > b.y) return Edge{ b, a }(p); if (p.y == a.y || p.y == b.y) return operator()({ p.x, p.y + epsilon }); if (p.y > b.y || p.y < a.y || p.x > max(a.x, b.x)) return false; if (p.x < min(a.x, b.x)) return true; auto blue = abs(a.x - p.x) > MIN ? (p.y - a.y) / (p.x - a.x) : MAX; auto red = abs(a.x - b.x) > MIN ? (b.y - a.y) / (b.x - a.x) : MAX; return blue >= red; } }; struct Figure { const string name; const initializer_list<Edge> edges; bool contains(const Point& p) const { auto c = 0; for (auto e : edges) if (e(p)) c++; return c % 2 != 0; } template<unsigned char W = 3> void check(const initializer_list<Point>& points, ostream& os) const { os << "Is point inside figure " << name << '?' << endl; for (auto p : points) os << " (" << setw(W) << p.x << ',' << setw(W) << p.y << "): " << boolalpha << contains(p) << endl; os << endl; } }; int main() { const initializer_list<Point> points = { { 5.0, 5.0}, {5.0, 8.0}, {-10.0, 5.0}, {0.0, 5.0}, {10.0, 5.0}, {8.0, 5.0}, {10.0, 10.0} }; const Figure square = { "Square", { {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}} } }; const Figure square_hole = { "Square hole", { {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}}, {{2.5, 2.5}, {7.5, 2.5}}, {{7.5, 2.5}, {7.5, 7.5}}, {{7.5, 7.5}, {2.5, 7.5}}, {{2.5, 7.5}, {2.5, 2.5}} } }; const Figure strange = { "Strange", { {{0.0, 0.0}, {2.5, 2.5}}, {{2.5, 2.5}, {0.0, 10.0}}, {{0.0, 10.0}, {2.5, 7.5}}, {{2.5, 7.5}, {7.5, 7.5}}, {{7.5, 7.5}, {10.0, 10.0}}, {{10.0, 10.0}, {10.0, 0.0}}, {{10.0, 0}, {2.5, 2.5}} } }; const Figure exagon = { "Exagon", { {{3.0, 0.0}, {7.0, 0.0}}, {{7.0, 0.0}, {10.0, 5.0}}, {{10.0, 5.0}, {7.0, 10.0}}, {{7.0, 10.0}, {3.0, 10.0}}, {{3.0, 10.0}, {0.0, 5.0}}, {{0.0, 5.0}, {3.0, 0.0}} } }; for(auto f : {square, square_hole, strange, exagon}) f.check(points, cout); return EXIT_SUCCESS; }
from collections import namedtuple from pprint import pprint as pp import sys Pt = namedtuple('Pt', 'x, y') Edge = namedtuple('Edge', 'a, b') Poly = namedtuple('Poly', 'name, edges') _eps = 0.00001 _huge = sys.float_info.max _tiny = sys.float_info.min def rayintersectseg(p, edge): a,b = edge if a.y > b.y: a,b = b,a if p.y == a.y or p.y == b.y: p = Pt(p.x, p.y + _eps) intersect = False if (p.y > b.y or p.y < a.y) or ( p.x > max(a.x, b.x)): return False if p.x < min(a.x, b.x): intersect = True else: if abs(a.x - b.x) > _tiny: m_red = (b.y - a.y) / float(b.x - a.x) else: m_red = _huge if abs(a.x - p.x) > _tiny: m_blue = (p.y - a.y) / float(p.x - a.x) else: m_blue = _huge intersect = m_blue >= m_red return intersect def _odd(x): return x%2 == 1 def ispointinside(p, poly): ln = len(poly) return _odd(sum(rayintersectseg(p, edge) for edge in poly.edges )) def polypp(poly): print ("\n Polygon(name='%s', edges=(" % poly.name) print (' ', ',\n '.join(str(e) for e in poly.edges) + '\n ))') if __name__ == '__main__': polys = [ Poly(name='square', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)) )), Poly(name='square_hole', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)), Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)), Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)), Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)), Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5)) )), Poly(name='strange', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)), Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)), Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)), Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5)) )), Poly(name='exagon', edges=( Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)), Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)), Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)), Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)), Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)), Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0)) )), ] testpoints = (Pt(x=5, y=5), Pt(x=5, y=8), Pt(x=-10, y=5), Pt(x=0, y=5), Pt(x=10, y=5), Pt(x=8, y=5), Pt(x=10, y=10)) print ("\n TESTING WHETHER POINTS ARE WITHIN POLYGONS") for poly in polys: polypp(poly) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[:3])) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[3:6])) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[6:]))
Port the provided C++ code into Python while preserving the original functionality.
#include <cmath> #include <iostream> using namespace std; class EllipticPoint { double m_x, m_y; static constexpr double ZeroThreshold = 1e20; static constexpr double B = 7; void Double() noexcept { if(IsZero()) { return; } if(m_y == 0) { *this = EllipticPoint(); } else { double L = (3 * m_x * m_x) / (2 * m_y); double newX = L * L - 2 * m_x; m_y = L * (m_x - newX) - m_y; m_x = newX; } } public: friend std::ostream& operator<<(std::ostream&, const EllipticPoint&); constexpr EllipticPoint() noexcept : m_x(0), m_y(ZeroThreshold * 1.01) {} explicit EllipticPoint(double yCoordinate) noexcept { m_y = yCoordinate; m_x = cbrt(m_y * m_y - B); } bool IsZero() const noexcept { bool isNotZero = abs(m_y) < ZeroThreshold; return !isNotZero; } EllipticPoint operator-() const noexcept { EllipticPoint negPt; negPt.m_x = m_x; negPt.m_y = -m_y; return negPt; } EllipticPoint& operator+=(const EllipticPoint& rhs) noexcept { if(IsZero()) { *this = rhs; } else if (rhs.IsZero()) { } else { double L = (rhs.m_y - m_y) / (rhs.m_x - m_x); if(isfinite(L)) { double newX = L * L - m_x - rhs.m_x; m_y = L * (m_x - newX) - m_y; m_x = newX; } else { if(signbit(m_y) != signbit(rhs.m_y)) { *this = EllipticPoint(); } else { Double(); } } } return *this; } EllipticPoint& operator-=(const EllipticPoint& rhs) noexcept { *this+= -rhs; return *this; } EllipticPoint& operator*=(int rhs) noexcept { EllipticPoint r; EllipticPoint p = *this; if(rhs < 0) { rhs = -rhs; p = -p; } for (int i = 1; i <= rhs; i <<= 1) { if (i & rhs) r += p; p.Double(); } *this = r; return *this; } }; inline EllipticPoint operator+(EllipticPoint lhs, const EllipticPoint& rhs) noexcept { lhs += rhs; return lhs; } inline EllipticPoint operator-(EllipticPoint lhs, const EllipticPoint& rhs) noexcept { lhs += -rhs; return lhs; } inline EllipticPoint operator*(EllipticPoint lhs, const int rhs) noexcept { lhs *= rhs; return lhs; } inline EllipticPoint operator*(const int lhs, EllipticPoint rhs) noexcept { rhs *= lhs; return rhs; } ostream& operator<<(ostream& os, const EllipticPoint& pt) { if(pt.IsZero()) cout << "(Zero)\n"; else cout << "(" << pt.m_x << ", " << pt.m_y << ")\n"; return os; } int main(void) { const EllipticPoint a(1), b(2); cout << "a = " << a; cout << "b = " << b; const EllipticPoint c = a + b; cout << "c = a + b = " << c; cout << "a + b - c = " << a + b - c; cout << "a + b - (b + a) = " << a + b - (b + a) << "\n"; cout << "a + a + a + a + a - 5 * a = " << a + a + a + a + a - 5 * a; cout << "a * 12345 = " << a * 12345; cout << "a * -12345 = " << a * -12345; cout << "a * 12345 + a * -12345 = " << a * 12345 + a * -12345; cout << "a * 12345 - (a * 12000 + a * 345) = " << a * 12345 - (a * 12000 + a * 345); cout << "a * 12345 - (a * 12001 + a * 345) = " << a * 12345 - (a * 12000 + a * 344) << "\n"; const EllipticPoint zero; EllipticPoint g; cout << "g = zero = " << g; cout << "g += a = " << (g+=a); cout << "g += zero = " << (g+=zero); cout << "g += b = " << (g+=b); cout << "b + b - b * 2 = " << (b + b - b * 2) << "\n"; EllipticPoint special(0); cout << "special = " << special; cout << "special *= 2 = " << (special*=2); return 0; }
class Point: b = 7 def __init__(self, x=float('inf'), y=float('inf')): self.x = x self.y = y def copy(self): return Point(self.x, self.y) def is_zero(self): return self.x > 1e20 or self.x < -1e20 def neg(self): return Point(self.x, -self.y) def dbl(self): if self.is_zero(): return self.copy() try: L = (3 * self.x * self.x) / (2 * self.y) except ZeroDivisionError: return Point() x = L * L - 2 * self.x return Point(x, L * (self.x - x) - self.y) def add(self, q): if self.x == q.x and self.y == q.y: return self.dbl() if self.is_zero(): return q.copy() if q.is_zero(): return self.copy() try: L = (q.y - self.y) / (q.x - self.x) except ZeroDivisionError: return Point() x = L * L - self.x - q.x return Point(x, L * (self.x - x) - self.y) def mul(self, n): p = self.copy() r = Point() i = 1 while i <= n: if i&n: r = r.add(p) p = p.dbl() i <<= 1 return r def __str__(self): return "({:.3f}, {:.3f})".format(self.x, self.y) def show(s, p): print(s, "Zero" if p.is_zero() else p) def from_y(y): n = y * y - Point.b x = n**(1./3) if n>=0 else -((-n)**(1./3)) return Point(x, y) a = from_y(1) b = from_y(2) show("a =", a) show("b =", b) c = a.add(b) show("c = a + b =", c) d = c.neg() show("d = -c =", d) show("c + d =", c.add(d)) show("a + b + d =", a.add(b.add(d))) show("a * 12345 =", a.mul(12345))
Convert this C++ snippet to Python and keep its semantics consistent.
#include <cmath> #include <iostream> using namespace std; class EllipticPoint { double m_x, m_y; static constexpr double ZeroThreshold = 1e20; static constexpr double B = 7; void Double() noexcept { if(IsZero()) { return; } if(m_y == 0) { *this = EllipticPoint(); } else { double L = (3 * m_x * m_x) / (2 * m_y); double newX = L * L - 2 * m_x; m_y = L * (m_x - newX) - m_y; m_x = newX; } } public: friend std::ostream& operator<<(std::ostream&, const EllipticPoint&); constexpr EllipticPoint() noexcept : m_x(0), m_y(ZeroThreshold * 1.01) {} explicit EllipticPoint(double yCoordinate) noexcept { m_y = yCoordinate; m_x = cbrt(m_y * m_y - B); } bool IsZero() const noexcept { bool isNotZero = abs(m_y) < ZeroThreshold; return !isNotZero; } EllipticPoint operator-() const noexcept { EllipticPoint negPt; negPt.m_x = m_x; negPt.m_y = -m_y; return negPt; } EllipticPoint& operator+=(const EllipticPoint& rhs) noexcept { if(IsZero()) { *this = rhs; } else if (rhs.IsZero()) { } else { double L = (rhs.m_y - m_y) / (rhs.m_x - m_x); if(isfinite(L)) { double newX = L * L - m_x - rhs.m_x; m_y = L * (m_x - newX) - m_y; m_x = newX; } else { if(signbit(m_y) != signbit(rhs.m_y)) { *this = EllipticPoint(); } else { Double(); } } } return *this; } EllipticPoint& operator-=(const EllipticPoint& rhs) noexcept { *this+= -rhs; return *this; } EllipticPoint& operator*=(int rhs) noexcept { EllipticPoint r; EllipticPoint p = *this; if(rhs < 0) { rhs = -rhs; p = -p; } for (int i = 1; i <= rhs; i <<= 1) { if (i & rhs) r += p; p.Double(); } *this = r; return *this; } }; inline EllipticPoint operator+(EllipticPoint lhs, const EllipticPoint& rhs) noexcept { lhs += rhs; return lhs; } inline EllipticPoint operator-(EllipticPoint lhs, const EllipticPoint& rhs) noexcept { lhs += -rhs; return lhs; } inline EllipticPoint operator*(EllipticPoint lhs, const int rhs) noexcept { lhs *= rhs; return lhs; } inline EllipticPoint operator*(const int lhs, EllipticPoint rhs) noexcept { rhs *= lhs; return rhs; } ostream& operator<<(ostream& os, const EllipticPoint& pt) { if(pt.IsZero()) cout << "(Zero)\n"; else cout << "(" << pt.m_x << ", " << pt.m_y << ")\n"; return os; } int main(void) { const EllipticPoint a(1), b(2); cout << "a = " << a; cout << "b = " << b; const EllipticPoint c = a + b; cout << "c = a + b = " << c; cout << "a + b - c = " << a + b - c; cout << "a + b - (b + a) = " << a + b - (b + a) << "\n"; cout << "a + a + a + a + a - 5 * a = " << a + a + a + a + a - 5 * a; cout << "a * 12345 = " << a * 12345; cout << "a * -12345 = " << a * -12345; cout << "a * 12345 + a * -12345 = " << a * 12345 + a * -12345; cout << "a * 12345 - (a * 12000 + a * 345) = " << a * 12345 - (a * 12000 + a * 345); cout << "a * 12345 - (a * 12001 + a * 345) = " << a * 12345 - (a * 12000 + a * 344) << "\n"; const EllipticPoint zero; EllipticPoint g; cout << "g = zero = " << g; cout << "g += a = " << (g+=a); cout << "g += zero = " << (g+=zero); cout << "g += b = " << (g+=b); cout << "b + b - b * 2 = " << (b + b - b * 2) << "\n"; EllipticPoint special(0); cout << "special = " << special; cout << "special *= 2 = " << (special*=2); return 0; }
class Point: b = 7 def __init__(self, x=float('inf'), y=float('inf')): self.x = x self.y = y def copy(self): return Point(self.x, self.y) def is_zero(self): return self.x > 1e20 or self.x < -1e20 def neg(self): return Point(self.x, -self.y) def dbl(self): if self.is_zero(): return self.copy() try: L = (3 * self.x * self.x) / (2 * self.y) except ZeroDivisionError: return Point() x = L * L - 2 * self.x return Point(x, L * (self.x - x) - self.y) def add(self, q): if self.x == q.x and self.y == q.y: return self.dbl() if self.is_zero(): return q.copy() if q.is_zero(): return self.copy() try: L = (q.y - self.y) / (q.x - self.x) except ZeroDivisionError: return Point() x = L * L - self.x - q.x return Point(x, L * (self.x - x) - self.y) def mul(self, n): p = self.copy() r = Point() i = 1 while i <= n: if i&n: r = r.add(p) p = p.dbl() i <<= 1 return r def __str__(self): return "({:.3f}, {:.3f})".format(self.x, self.y) def show(s, p): print(s, "Zero" if p.is_zero() else p) def from_y(y): n = y * y - Point.b x = n**(1./3) if n>=0 else -((-n)**(1./3)) return Point(x, y) a = from_y(1) b = from_y(2) show("a =", a) show("b =", b) c = a.add(b) show("c = a + b =", c) d = c.neg() show("d = -c =", d) show("c + d =", c.add(d)) show("a + b + d =", a.add(b.add(d))) show("a * 12345 =", a.mul(12345))
Write a version of this C++ function in Python with identical behavior.
#include <iostream> #include <string> int countSubstring(const std::string& str, const std::string& sub) { if (sub.length() == 0) return 0; int count = 0; for (size_t offset = str.find(sub); offset != std::string::npos; offset = str.find(sub, offset + sub.length())) { ++count; } return count; } int main() { std::cout << countSubstring("the three truths", "th") << '\n'; std::cout << countSubstring("ababababab", "abab") << '\n'; std::cout << countSubstring("abaabba*bbaba*bbab", "a*b") << '\n'; return 0; }
>>> "the three truths".count("th") 3 >>> "ababababab".count("abab") 2
Rewrite this program in Python while keeping its functionality equivalent to the C++ version.
#include <cstdio> #include <vector> #include <bits/stdc++.h> using namespace std; int main() { vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum; for (int x : lst) w.push_back({x, x}); while (w.size() > 0) { auto i = w[0]; w.erase(w.begin()); for (int x : lst) if ((sum = get<1>(i) + x) == 13) printf("%d%d ", get<0>(i), x); else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); } return 0; }
from collections import deque def prime_digits_sum(r): q = deque([(r, 0)]) while q: r, n = q.popleft() for d in 2, 3, 5, 7: if d >= r: if d == r: yield n + d break q.append((r - d, (n + d) * 10)) print(*prime_digits_sum(13))
Write the same algorithm in Python as shown in this C++ implementation.
#include <cstdio> #include <vector> #include <bits/stdc++.h> using namespace std; int main() { vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum; for (int x : lst) w.push_back({x, x}); while (w.size() > 0) { auto i = w[0]; w.erase(w.begin()); for (int x : lst) if ((sum = get<1>(i) + x) == 13) printf("%d%d ", get<0>(i), x); else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); } return 0; }
from collections import deque def prime_digits_sum(r): q = deque([(r, 0)]) while q: r, n = q.popleft() for d in 2, 3, 5, 7: if d >= r: if d == r: yield n + d break q.append((r - d, (n + d) * 10)) print(*prime_digits_sum(13))
Rewrite this program in Python while keeping its functionality equivalent to the C++ version.
#include <algorithm> #include <iostream> #include <sstream> #include <string> template <typename T> void demo_compare(const T &a, const T &b, const std::string &semantically) { std::cout << a << " and " << b << " are " << ((a == b) ? "" : "not ") << "exactly " << semantically << " equal." << std::endl; std::cout << a << " and " << b << " are " << ((a != b) ? "" : "not ") << semantically << "inequal." << std::endl; std::cout << a << " is " << ((a < b) ? "" : "not ") << semantically << " ordered before " << b << '.' << std::endl; std::cout << a << " is " << ((a > b) ? "" : "not ") << semantically << " ordered after " << b << '.' << std::endl; } int main(int argc, char *argv[]) { std::string a((argc > 1) ? argv[1] : "1.2.Foo"); std::string b((argc > 2) ? argv[2] : "1.3.Bar"); demo_compare<std::string>(a, b, "lexically"); std::transform(a.begin(), a.end(), a.begin(), ::tolower); std::transform(b.begin(), b.end(), b.begin(), ::tolower); demo_compare<std::string>(a, b, "lexically"); double numA, numB; std::istringstream(a) >> numA; std::istringstream(b) >> numB; demo_compare<double>(numA, numB, "numerically"); return (a == b); }
fun compare(a, b): print("\n$a is of type ${typeof(a)} and $b is of type ${typeof(b)}") if a < b: print("$a is strictly less than $b") if a <= b: print("$a is less than or equal to $b") if a > b: print("$a is strictly greater than $b") if a >= b: print("$a is greater than or equal to $b") if a == b: print("$a is equal to $b") if a != b: print("$a is not equal to $b") if a is b: print("$a has object identity with $b") if a is not b: print("$a has negated object identity with $b") compare("YUP", "YUP") compare('a', 'z') compare("24", "123") compare(24, 123) compare(5.0, 5)
Transform the following C++ implementation into Python, maintaining the same output and logic.
#include <fstream> #include <iostream> #include <ctime> using namespace std; #define note_file "NOTES.TXT" int main(int argc, char **argv) { if(argc>1) { ofstream Notes(note_file, ios::app); time_t timer = time(NULL); if(Notes.is_open()) { Notes << asctime(localtime(&timer)) << '\t'; for(int i=1;i<argc;i++) Notes << argv[i] << ' '; Notes << endl; Notes.close(); } } else { ifstream Notes(note_file, ios::in); string line; if(Notes.is_open()) { while(!Notes.eof()) { getline(Notes, line); cout << line << endl; } Notes.close(); } } }
import sys, datetime, shutil if len(sys.argv) == 1: try: with open('notes.txt', 'r') as f: shutil.copyfileobj(f, sys.stdout) except IOError: pass else: with open('notes.txt', 'a') as f: f.write(datetime.datetime.now().isoformat() + '\n') f.write("\t%s\n" % ' '.join(sys.argv[1:]))
Translate this program into Python but keep the logic exactly as in C++.
#include <cmath> #include <iostream> #include <iomanip> #include <string.h> constexpr unsigned int N = 32u; double xval[N], t_sin[N], t_cos[N], t_tan[N]; constexpr unsigned int N2 = N * (N - 1u) / 2u; double r_sin[N2], r_cos[N2], r_tan[N2]; double ρ(double *x, double *y, double *r, int i, int n) { if (n < 0) return 0; if (!n) return y[i]; unsigned int idx = (N - 1 - n) * (N - n) / 2 + i; if (r[idx] != r[idx]) r[idx] = (x[i] - x[i + n]) / (ρ(x, y, r, i, n - 1) - ρ(x, y, r, i + 1, n - 1)) + ρ(x, y, r, i + 1, n - 2); return r[idx]; } double thiele(double *x, double *y, double *r, double xin, unsigned int n) { return n > N - 1 ? 1. : ρ(x, y, r, 0, n) - ρ(x, y, r, 0, n - 2) + (xin - x[n]) / thiele(x, y, r, xin, n + 1); } inline auto i_sin(double x) { return thiele(t_sin, xval, r_sin, x, 0); } inline auto i_cos(double x) { return thiele(t_cos, xval, r_cos, x, 0); } inline auto i_tan(double x) { return thiele(t_tan, xval, r_tan, x, 0); } int main() { constexpr double step = .05; for (auto i = 0u; i < N; i++) { xval[i] = i * step; t_sin[i] = sin(xval[i]); t_cos[i] = cos(xval[i]); t_tan[i] = t_sin[i] / t_cos[i]; } for (auto i = 0u; i < N2; i++) r_sin[i] = r_cos[i] = r_tan[i] = NAN; std::cout << std::setw(16) << std::setprecision(25) << 6 * i_sin(.5) << std::endl << 3 * i_cos(.5) << std::endl << 4 * i_tan(1.) << std::endl; return 0; }
import math def thieleInterpolator(x, y): ρ = [[yi]*(len(y)-i) for i, yi in enumerate(y)] for i in range(len(ρ)-1): ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0]) for i in range(2, len(ρ)): for j in range(len(ρ)-i): ρ[j][i] = (x[j]-x[j+i]) / (ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2] ρ0 = ρ[0] def t(xin): a = 0 for i in range(len(ρ0)-1, 1, -1): a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a) return y[0] + (xin-x[0]) / (ρ0[1]+a) return t xVal = [i*.05 for i in range(32)] tSin = [math.sin(x) for x in xVal] tCos = [math.cos(x) for x in xVal] tTan = [math.tan(x) for x in xVal] iSin = thieleInterpolator(tSin, xVal) iCos = thieleInterpolator(tCos, xVal) iTan = thieleInterpolator(tTan, xVal) print('{:16.14f}'.format(6*iSin(.5))) print('{:16.14f}'.format(3*iCos(.5))) print('{:16.14f}'.format(4*iTan(1)))
Can you help me rewrite this code in Python instead of C++, keeping it the same logically?
#include <string> #include <map> #include <iostream> #include <algorithm> #include <cmath> #include <iomanip> double log2( double number ) { return ( log( number ) / log( 2 ) ) ; } double find_entropy( std::string & fiboword ) { std::map<char , int> frequencies ; std::for_each( fiboword.begin( ) , fiboword.end( ) , [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; int numlen = fiboword.length( ) ; double infocontent = 0 ; for ( std::pair<char , int> p : frequencies ) { double freq = static_cast<double>( p.second ) / numlen ; infocontent += freq * log2( freq ) ; } infocontent *= -1 ; return infocontent ; } void printLine( std::string &fiboword , int n ) { std::cout << std::setw( 5 ) << std::left << n ; std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ; std::cout << " " << std::setw( 16 ) << std::setprecision( 13 ) << std::left << find_entropy( fiboword ) ; std::cout << "\n" ; } int main( ) { std::cout << std::setw( 5 ) << std::left << "N" ; std::cout << std::setw( 12 ) << std::right << "length" ; std::cout << " " << std::setw( 16 ) << std::left << "entropy" ; std::cout << "\n" ; std::string firststring ( "1" ) ; int n = 1 ; printLine( firststring , n ) ; std::string secondstring( "0" ) ; n++ ; printLine( secondstring , n ) ; while ( n < 37 ) { std::string resultstring = firststring + secondstring ; firststring.assign( secondstring ) ; secondstring.assign( resultstring ) ; n++ ; printLine( resultstring , n ) ; } return 0 ; }
>>> import math >>> from collections import Counter >>> >>> def entropy(s): ... p, lns = Counter(s), float(len(s)) ... return -sum( count/lns * math.log(count/lns, 2) for count in p.values()) ... >>> >>> def fibword(nmax=37): ... fwords = ['1', '0'] ... print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split())) ... def pr(n, fwords): ... while len(fwords) < n: ... fwords += [''.join(fwords[-2:][::-1])] ... v = fwords[n-1] ... print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>')) ... for n in range(1, nmax+1): pr(n, fwords) ... >>> fibword() N Length Entropy Fibword 1 1 -0 1 2 1 -0 0 3 2 1 01 4 3 0.9182958 010 5 5 0.9709506 01001 6 8 0.954434 01001010 7 13 0.9612366 0100101001001 8 21 0.9587119 <too long> 9 34 0.9596869 <too long> 10 55 0.959316 <too long> 11 89 0.9594579 <too long> 12 144 0.9594038 <too long> 13 233 0.9594244 <too long> 14 377 0.9594165 <too long> 15 610 0.9594196 <too long> 16 987 0.9594184 <too long> 17 1597 0.9594188 <too long> 18 2584 0.9594187 <too long> 19 4181 0.9594187 <too long> 20 6765 0.9594187 <too long> 21 10946 0.9594187 <too long> 22 17711 0.9594187 <too long> 23 28657 0.9594187 <too long> 24 46368 0.9594187 <too long> 25 75025 0.9594187 <too long> 26 121393 0.9594187 <too long> 27 196418 0.9594187 <too long> 28 317811 0.9594187 <too long> 29 514229 0.9594187 <too long> 30 832040 0.9594187 <too long> 31 1346269 0.9594187 <too long> 32 2178309 0.9594187 <too long> 33 3524578 0.9594187 <too long> 34 5702887 0.9594187 <too long> 35 9227465 0.9594187 <too long> 36 14930352 0.9594187 <too long> 37 24157817 0.9594187 <too long> >>>
Change the following C++ code into Python without altering its purpose.
#include <string> #include <map> #include <iostream> #include <algorithm> #include <cmath> #include <iomanip> double log2( double number ) { return ( log( number ) / log( 2 ) ) ; } double find_entropy( std::string & fiboword ) { std::map<char , int> frequencies ; std::for_each( fiboword.begin( ) , fiboword.end( ) , [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; int numlen = fiboword.length( ) ; double infocontent = 0 ; for ( std::pair<char , int> p : frequencies ) { double freq = static_cast<double>( p.second ) / numlen ; infocontent += freq * log2( freq ) ; } infocontent *= -1 ; return infocontent ; } void printLine( std::string &fiboword , int n ) { std::cout << std::setw( 5 ) << std::left << n ; std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ; std::cout << " " << std::setw( 16 ) << std::setprecision( 13 ) << std::left << find_entropy( fiboword ) ; std::cout << "\n" ; } int main( ) { std::cout << std::setw( 5 ) << std::left << "N" ; std::cout << std::setw( 12 ) << std::right << "length" ; std::cout << " " << std::setw( 16 ) << std::left << "entropy" ; std::cout << "\n" ; std::string firststring ( "1" ) ; int n = 1 ; printLine( firststring , n ) ; std::string secondstring( "0" ) ; n++ ; printLine( secondstring , n ) ; while ( n < 37 ) { std::string resultstring = firststring + secondstring ; firststring.assign( secondstring ) ; secondstring.assign( resultstring ) ; n++ ; printLine( resultstring , n ) ; } return 0 ; }
>>> import math >>> from collections import Counter >>> >>> def entropy(s): ... p, lns = Counter(s), float(len(s)) ... return -sum( count/lns * math.log(count/lns, 2) for count in p.values()) ... >>> >>> def fibword(nmax=37): ... fwords = ['1', '0'] ... print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split())) ... def pr(n, fwords): ... while len(fwords) < n: ... fwords += [''.join(fwords[-2:][::-1])] ... v = fwords[n-1] ... print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>')) ... for n in range(1, nmax+1): pr(n, fwords) ... >>> fibword() N Length Entropy Fibword 1 1 -0 1 2 1 -0 0 3 2 1 01 4 3 0.9182958 010 5 5 0.9709506 01001 6 8 0.954434 01001010 7 13 0.9612366 0100101001001 8 21 0.9587119 <too long> 9 34 0.9596869 <too long> 10 55 0.959316 <too long> 11 89 0.9594579 <too long> 12 144 0.9594038 <too long> 13 233 0.9594244 <too long> 14 377 0.9594165 <too long> 15 610 0.9594196 <too long> 16 987 0.9594184 <too long> 17 1597 0.9594188 <too long> 18 2584 0.9594187 <too long> 19 4181 0.9594187 <too long> 20 6765 0.9594187 <too long> 21 10946 0.9594187 <too long> 22 17711 0.9594187 <too long> 23 28657 0.9594187 <too long> 24 46368 0.9594187 <too long> 25 75025 0.9594187 <too long> 26 121393 0.9594187 <too long> 27 196418 0.9594187 <too long> 28 317811 0.9594187 <too long> 29 514229 0.9594187 <too long> 30 832040 0.9594187 <too long> 31 1346269 0.9594187 <too long> 32 2178309 0.9594187 <too long> 33 3524578 0.9594187 <too long> 34 5702887 0.9594187 <too long> 35 9227465 0.9594187 <too long> 36 14930352 0.9594187 <too long> 37 24157817 0.9594187 <too long> >>>
Maintain the same structure and functionality when rewriting this code in Python.
#include <string> #include <map> #include <iostream> #include <algorithm> #include <cmath> #include <iomanip> double log2( double number ) { return ( log( number ) / log( 2 ) ) ; } double find_entropy( std::string & fiboword ) { std::map<char , int> frequencies ; std::for_each( fiboword.begin( ) , fiboword.end( ) , [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; int numlen = fiboword.length( ) ; double infocontent = 0 ; for ( std::pair<char , int> p : frequencies ) { double freq = static_cast<double>( p.second ) / numlen ; infocontent += freq * log2( freq ) ; } infocontent *= -1 ; return infocontent ; } void printLine( std::string &fiboword , int n ) { std::cout << std::setw( 5 ) << std::left << n ; std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ; std::cout << " " << std::setw( 16 ) << std::setprecision( 13 ) << std::left << find_entropy( fiboword ) ; std::cout << "\n" ; } int main( ) { std::cout << std::setw( 5 ) << std::left << "N" ; std::cout << std::setw( 12 ) << std::right << "length" ; std::cout << " " << std::setw( 16 ) << std::left << "entropy" ; std::cout << "\n" ; std::string firststring ( "1" ) ; int n = 1 ; printLine( firststring , n ) ; std::string secondstring( "0" ) ; n++ ; printLine( secondstring , n ) ; while ( n < 37 ) { std::string resultstring = firststring + secondstring ; firststring.assign( secondstring ) ; secondstring.assign( resultstring ) ; n++ ; printLine( resultstring , n ) ; } return 0 ; }
>>> import math >>> from collections import Counter >>> >>> def entropy(s): ... p, lns = Counter(s), float(len(s)) ... return -sum( count/lns * math.log(count/lns, 2) for count in p.values()) ... >>> >>> def fibword(nmax=37): ... fwords = ['1', '0'] ... print('%-3s %10s %-10s %s' % tuple('N Length Entropy Fibword'.split())) ... def pr(n, fwords): ... while len(fwords) < n: ... fwords += [''.join(fwords[-2:][::-1])] ... v = fwords[n-1] ... print('%3i %10i %10.7g %s' % (n, len(v), entropy(v), v if len(v) < 20 else '<too long>')) ... for n in range(1, nmax+1): pr(n, fwords) ... >>> fibword() N Length Entropy Fibword 1 1 -0 1 2 1 -0 0 3 2 1 01 4 3 0.9182958 010 5 5 0.9709506 01001 6 8 0.954434 01001010 7 13 0.9612366 0100101001001 8 21 0.9587119 <too long> 9 34 0.9596869 <too long> 10 55 0.959316 <too long> 11 89 0.9594579 <too long> 12 144 0.9594038 <too long> 13 233 0.9594244 <too long> 14 377 0.9594165 <too long> 15 610 0.9594196 <too long> 16 987 0.9594184 <too long> 17 1597 0.9594188 <too long> 18 2584 0.9594187 <too long> 19 4181 0.9594187 <too long> 20 6765 0.9594187 <too long> 21 10946 0.9594187 <too long> 22 17711 0.9594187 <too long> 23 28657 0.9594187 <too long> 24 46368 0.9594187 <too long> 25 75025 0.9594187 <too long> 26 121393 0.9594187 <too long> 27 196418 0.9594187 <too long> 28 317811 0.9594187 <too long> 29 514229 0.9594187 <too long> 30 832040 0.9594187 <too long> 31 1346269 0.9594187 <too long> 32 2178309 0.9594187 <too long> 33 3524578 0.9594187 <too long> 34 5702887 0.9594187 <too long> 35 9227465 0.9594187 <too long> 36 14930352 0.9594187 <too long> 37 24157817 0.9594187 <too long> >>>
Generate an equivalent Python version of this C++ code.
#include <functional> #include <iostream> #include <iomanip> #include <math.h> #include <sstream> #include <vector> #include <boost/algorithm/string.hpp> template<typename T> T normalize(T a, double b) { return std::fmod(a, b); } inline double d2d(double a) { return normalize<double>(a, 360); } inline double g2g(double a) { return normalize<double>(a, 400); } inline double m2m(double a) { return normalize<double>(a, 6400); } inline double r2r(double a) { return normalize<double>(a, 2*M_PI); } double d2g(double a) { return g2g(a * 10 / 9); } double d2m(double a) { return m2m(a * 160 / 9); } double d2r(double a) { return r2r(a * M_PI / 180); } double g2d(double a) { return d2d(a * 9 / 10); } double g2m(double a) { return m2m(a * 16); } double g2r(double a) { return r2r(a * M_PI / 200); } double m2d(double a) { return d2d(a * 9 / 160); } double m2g(double a) { return g2g(a / 16); } double m2r(double a) { return r2r(a * M_PI / 3200); } double r2d(double a) { return d2d(a * 180 / M_PI); } double r2g(double a) { return g2g(a * 200 / M_PI); } double r2m(double a) { return m2m(a * 3200 / M_PI); } void print(const std::vector<double> &values, const char *s, std::function<double(double)> f) { using namespace std; ostringstream out; out << " ┌───────────────────┐\n"; out << " │ " << setw(17) << s << " │\n"; out << "┌─────────────────┼───────────────────┤\n"; for (double i : values) out << "│ " << setw(15) << fixed << i << defaultfloat << " │ " << setw(17) << fixed << f(i) << defaultfloat << " │\n"; out << "└─────────────────┴───────────────────┘\n"; auto str = out.str(); boost::algorithm::replace_all(str, ".000000", " "); cout << str; } int main() { std::vector<double> values = { -2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000 }; print(values, "normalized (deg)", d2d); print(values, "normalized (grad)", g2g); print(values, "normalized (mil)", m2m); print(values, "normalized (rad)", r2r); print(values, "deg -> grad ", d2g); print(values, "deg -> mil ", d2m); print(values, "deg -> rad ", d2r); print(values, "grad -> deg ", g2d); print(values, "grad -> mil ", g2m); print(values, "grad -> rad ", g2r); print(values, "mil -> deg ", m2d); print(values, "mil -> grad ", m2g); print(values, "mil -> rad ", m2r); print(values, "rad -> deg ", r2d); print(values, "rad -> grad ", r2g); print(values, "rad -> mil ", r2m); return 0; }
PI = 3.141592653589793 TWO_PI = 6.283185307179586 def normalize2deg(a): while a < 0: a += 360 while a >= 360: a -= 360 return a def normalize2grad(a): while a < 0: a += 400 while a >= 400: a -= 400 return a def normalize2mil(a): while a < 0: a += 6400 while a >= 6400: a -= 6400 return a def normalize2rad(a): while a < 0: a += TWO_PI while a >= TWO_PI: a -= TWO_PI return a def deg2grad(a): return a * 10.0 / 9.0 def deg2mil(a): return a * 160.0 / 9.0 def deg2rad(a): return a * PI / 180.0 def grad2deg(a): return a * 9.0 / 10.0 def grad2mil(a): return a * 16.0 def grad2rad(a): return a * PI / 200.0 def mil2deg(a): return a * 9.0 / 160.0 def mil2grad(a): return a / 16.0 def mil2rad(a): return a * PI / 3200.0 def rad2deg(a): return a * 180.0 / PI def rad2grad(a): return a * 200.0 / PI def rad2mil(a): return a * 3200.0 / PI
Produce a language-to-language conversion: from C++ to Python, same semantics.
#include <algorithm> #include <iostream> #include <string> #include <vector> std::string longestPath( const std::vector<std::string> & , char ) ; int main( ) { std::string dirs[ ] = { "/home/user1/tmp/coverage/test" , "/home/user1/tmp/covert/operator" , "/home/user1/tmp/coven/members" } ; std::vector<std::string> myDirs ( dirs , dirs + 3 ) ; std::cout << "The longest common path of the given directories is " << longestPath( myDirs , '/' ) << "!\n" ; return 0 ; } std::string longestPath( const std::vector<std::string> & dirs , char separator ) { std::vector<std::string>::const_iterator vsi = dirs.begin( ) ; int maxCharactersCommon = vsi->length( ) ; std::string compareString = *vsi ; for ( vsi = dirs.begin( ) + 1 ; vsi != dirs.end( ) ; vsi++ ) { std::pair<std::string::const_iterator , std::string::const_iterator> p = std::mismatch( compareString.begin( ) , compareString.end( ) , vsi->begin( ) ) ; if (( p.first - compareString.begin( ) ) < maxCharactersCommon ) maxCharactersCommon = p.first - compareString.begin( ) ; } std::string::size_type found = compareString.rfind( separator , maxCharactersCommon ) ; return compareString.substr( 0 , found ) ; }
>>> import os >>> os.path.commonpath(['/home/user1/tmp/coverage/test', '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members']) '/home/user1/tmp'
Ensure the translated Python code behaves exactly like the original C++ snippet.
#include <map> #include <iostream> #include <cmath> template<typename F> bool test_distribution(F f, int calls, double delta) { typedef std::map<int, int> distmap; distmap dist; for (int i = 0; i < calls; ++i) ++dist[f()]; double mean = 1.0/dist.size(); bool good = true; for (distmap::iterator i = dist.begin(); i != dist.end(); ++i) { if (std::abs((1.0 * i->second)/calls - mean) > delta) { std::cout << "Relative frequency " << i->second/(1.0*calls) << " of result " << i->first << " deviates by more than " << delta << " from the expected value " << mean << "\n"; good = false; } } return good; }
from collections import Counter from pprint import pprint as pp def distcheck(fn, repeats, delta): bin = Counter(fn() for i in range(repeats)) target = repeats // len(bin) deltacount = int(delta / 100. * target) assert all( abs(target - count) < deltacount for count in bin.values() ), "Bin distribution skewed from %i +/- %i: %s" % ( target, deltacount, [ (key, target - count) for key, count in sorted(bin.items()) ] ) pp(dict(bin))
Write a version of this C++ function in Python with identical behavior.
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class stirling2 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer stirling2::get(int n, int k) { if (k == n) return 1; if (k == 0 || k > n) return 0; auto p = std::make_pair(n, k); auto i = cache_.find(p); if (i != cache_.end()) return i->second; integer s = k * get(n - 1, k) + get(n - 1, k - 1); cache_.emplace(p, s); return s; } void print_stirling_numbers(stirling2& s2, int n) { std::cout << "Stirling numbers of the second kind:\nn/k"; for (int j = 0; j <= n; ++j) { std::cout << std::setw(j == 0 ? 2 : 8) << j; } std::cout << '\n'; for (int i = 0; i <= n; ++i) { std::cout << std::setw(2) << i << ' '; for (int j = 0; j <= i; ++j) std::cout << std::setw(j == 0 ? 2 : 8) << s2.get(i, j); std::cout << '\n'; } } int main() { stirling2 s2; print_stirling_numbers(s2, 12); std::cout << "Maximum value of S2(n,k) where n == 100:\n"; integer max = 0; for (int k = 0; k <= 100; ++k) max = std::max(max, s2.get(100, k)); std::cout << max << '\n'; return 0; }
computed = {} def sterling2(n, k): key = str(n) + "," + str(k) if key in computed.keys(): return computed[key] if n == k == 0: return 1 if (n > 0 and k == 0) or (n == 0 and k > 0): return 0 if n == k: return 1 if k > n: return 0 result = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1) computed[key] = result return result print("Stirling numbers of the second kind:") MAX = 12 print("n/k".ljust(10), end="") for n in range(MAX + 1): print(str(n).rjust(10), end="") print() for n in range(MAX + 1): print(str(n).ljust(10), end="") for k in range(n + 1): print(str(sterling2(n, k)).rjust(10), end="") print() print("The maximum value of S2(100, k) = ") previous = 0 for k in range(1, 100 + 1): current = sterling2(100, k) if current > previous: previous = current else: print("{0}\n({1} digits, k = {2})\n".format(previous, len(str(previous)), k - 1)) break
Convert the following code from C++ to Python, ensuring the logic remains intact.
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class stirling2 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer stirling2::get(int n, int k) { if (k == n) return 1; if (k == 0 || k > n) return 0; auto p = std::make_pair(n, k); auto i = cache_.find(p); if (i != cache_.end()) return i->second; integer s = k * get(n - 1, k) + get(n - 1, k - 1); cache_.emplace(p, s); return s; } void print_stirling_numbers(stirling2& s2, int n) { std::cout << "Stirling numbers of the second kind:\nn/k"; for (int j = 0; j <= n; ++j) { std::cout << std::setw(j == 0 ? 2 : 8) << j; } std::cout << '\n'; for (int i = 0; i <= n; ++i) { std::cout << std::setw(2) << i << ' '; for (int j = 0; j <= i; ++j) std::cout << std::setw(j == 0 ? 2 : 8) << s2.get(i, j); std::cout << '\n'; } } int main() { stirling2 s2; print_stirling_numbers(s2, 12); std::cout << "Maximum value of S2(n,k) where n == 100:\n"; integer max = 0; for (int k = 0; k <= 100; ++k) max = std::max(max, s2.get(100, k)); std::cout << max << '\n'; return 0; }
computed = {} def sterling2(n, k): key = str(n) + "," + str(k) if key in computed.keys(): return computed[key] if n == k == 0: return 1 if (n > 0 and k == 0) or (n == 0 and k > 0): return 0 if n == k: return 1 if k > n: return 0 result = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1) computed[key] = result return result print("Stirling numbers of the second kind:") MAX = 12 print("n/k".ljust(10), end="") for n in range(MAX + 1): print(str(n).rjust(10), end="") print() for n in range(MAX + 1): print(str(n).ljust(10), end="") for k in range(n + 1): print(str(sterling2(n, k)).rjust(10), end="") print() print("The maximum value of S2(100, k) = ") previous = 0 for k in range(1, 100 + 1): current = sterling2(100, k) if current > previous: previous = current else: print("{0}\n({1} digits, k = {2})\n".format(previous, len(str(previous)), k - 1)) break
Keep all operations the same but rewrite the snippet in Python.
#include <iostream> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto i = v.cbegin(); auto e = v.cend(); os << '['; if (i != e) { os << *i; i = std::next(i); } while (i != e) { os << ", " << *i; i = std::next(i); } return os << ']'; } int main() { using namespace std; vector<int> a{ 0 }; set<int> used{ 0 }; set<int> used1000{ 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a[n - 1] - n; if (next < 1 || used.find(next) != used.end()) { next += 2 * n; } bool alreadyUsed = used.find(next) != used.end(); a.push_back(next); if (!alreadyUsed) { used.insert(next); if (0 <= next && next <= 1000) { used1000.insert(next); } } if (n == 14) { cout << "The first 15 terms of the Recaman sequence are: " << a << '\n'; } if (!foundDup && alreadyUsed) { cout << "The first duplicated term is a[" << n << "] = " << next << '\n'; foundDup = true; } if (used1000.size() == 1001) { cout << "Terms up to a[" << n << "] are needed to generate 0 to 1000\n"; } n++; } return 0; }
from itertools import islice class Recamans(): "Recamán's sequence generator callable class" def __init__(self): self.a = None self.n = None def __call__(self): "Recamán's sequence generator" nxt = 0 a, n = {nxt}, 0 self.a = a self.n = n yield nxt while True: an1, n = nxt, n + 1 nxt = an1 - n if nxt < 0 or nxt in a: nxt = an1 + n a.add(nxt) self.n = n yield nxt if __name__ == '__main__': recamans = Recamans() print("First fifteen members of Recamans sequence:", list(islice(recamans(), 15))) so_far = set() for term in recamans(): if term in so_far: print(f"First duplicate number in series is: a({recamans.n}) = {term}") break so_far.add(term) n = 1_000 setn = set(range(n + 1)) for _ in recamans(): if setn.issubset(recamans.a): print(f"Range 0 ..{n} is covered by terms up to a({recamans.n})") break
Generate an equivalent Python version of this C++ code.
#include <iostream> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto i = v.cbegin(); auto e = v.cend(); os << '['; if (i != e) { os << *i; i = std::next(i); } while (i != e) { os << ", " << *i; i = std::next(i); } return os << ']'; } int main() { using namespace std; vector<int> a{ 0 }; set<int> used{ 0 }; set<int> used1000{ 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a[n - 1] - n; if (next < 1 || used.find(next) != used.end()) { next += 2 * n; } bool alreadyUsed = used.find(next) != used.end(); a.push_back(next); if (!alreadyUsed) { used.insert(next); if (0 <= next && next <= 1000) { used1000.insert(next); } } if (n == 14) { cout << "The first 15 terms of the Recaman sequence are: " << a << '\n'; } if (!foundDup && alreadyUsed) { cout << "The first duplicated term is a[" << n << "] = " << next << '\n'; foundDup = true; } if (used1000.size() == 1001) { cout << "Terms up to a[" << n << "] are needed to generate 0 to 1000\n"; } n++; } return 0; }
from itertools import islice class Recamans(): "Recamán's sequence generator callable class" def __init__(self): self.a = None self.n = None def __call__(self): "Recamán's sequence generator" nxt = 0 a, n = {nxt}, 0 self.a = a self.n = n yield nxt while True: an1, n = nxt, n + 1 nxt = an1 - n if nxt < 0 or nxt in a: nxt = an1 + n a.add(nxt) self.n = n yield nxt if __name__ == '__main__': recamans = Recamans() print("First fifteen members of Recamans sequence:", list(islice(recamans(), 15))) so_far = set() for term in recamans(): if term in so_far: print(f"First duplicate number in series is: a({recamans.n}) = {term}") break so_far.add(term) n = 1_000 setn = set(range(n + 1)) for _ in recamans(): if setn.issubset(recamans.a): print(f"Range 0 ..{n} is covered by terms up to a({recamans.n})") break
Rewrite the snippet below in Python so it works the same as the original C++ code.
#include <string> int main() { int* p; p = new int; delete p; p = new int(2); delete p; std::string* p2; p2 = new std::string; delete p2; p = new int[10]; delete[] p; p2 = new std::string[10]; delete[] p2; }
>>> from array import array >>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \u2641'), ('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])] >>> for typecode, initializer in argslist: a = array(typecode, initializer) print a del a array('l') array('c', 'hello world') array('u', u'hello \u2641') array('l', [1, 2, 3, 4, 5]) array('d', [1.0, 2.0, 3.1400000000000001]) >>>
Can you help me rewrite this code in Python instead of C++, keeping it the same logically?
#include <windows.h> #include <iostream> #include <string> using namespace std; enum players { Computer, Human, Draw, None }; const int iWin[8][3] = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }, { 0, 3, 6 }, { 1, 4, 7 }, { 2, 5, 8 }, { 0, 4, 8 }, { 2, 4, 6 } }; class ttt { public: ttt() { _p = rand() % 2; reset(); } void play() { int res = Draw; while( true ) { drawGrid(); while( true ) { if( _p ) getHumanMove(); else getComputerMove(); drawGrid(); res = checkVictory(); if( res != None ) break; ++_p %= 2; } if( res == Human ) cout << "CONGRATULATIONS HUMAN --- You won!"; else if( res == Computer ) cout << "NOT SO MUCH A SURPRISE --- I won!"; else cout << "It's a draw!"; cout << endl << endl; string r; cout << "Play again( Y / N )? "; cin >> r; if( r != "Y" && r != "y" ) return; ++_p %= 2; reset(); } } private: void reset() { for( int x = 0; x < 9; x++ ) _field[x] = None; } void drawGrid() { system( "cls" ); COORD c = { 0, 2 }; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c ); cout << " 1 | 2 | 3 " << endl; cout << "---+---+---" << endl; cout << " 4 | 5 | 6 " << endl; cout << "---+---+---" << endl; cout << " 7 | 8 | 9 " << endl << endl << endl; int f = 0; for( int y = 0; y < 5; y += 2 ) for( int x = 1; x < 11; x += 4 ) { if( _field[f] != None ) { COORD c = { x, 2 + y }; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c ); string o = _field[f] == Computer ? "X" : "O"; cout << o; } f++; } c.Y = 9; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c ); } int checkVictory() { for( int i = 0; i < 8; i++ ) { if( _field[iWin[i][0]] != None && _field[iWin[i][0]] == _field[iWin[i][1]] && _field[iWin[i][1]] == _field[iWin[i][2]] ) { return _field[iWin[i][0]]; } } int i = 0; for( int f = 0; f < 9; f++ ) { if( _field[f] != None ) i++; } if( i == 9 ) return Draw; return None; } void getHumanMove() { int m; cout << "Enter your move ( 1 - 9 ) "; while( true ) { m = 0; do { cin >> m; } while( m < 1 && m > 9 ); if( _field[m - 1] != None ) cout << "Invalid move. Try again!" << endl; else break; } _field[m - 1] = Human; } void getComputerMove() { int move = 0; do{ move = rand() % 9; } while( _field[move] != None ); for( int i = 0; i < 8; i++ ) { int try1 = iWin[i][0], try2 = iWin[i][1], try3 = iWin[i][2]; if( _field[try1] != None && _field[try1] == _field[try2] && _field[try3] == None ) { move = try3; if( _field[try1] == Computer ) break; } if( _field[try1] != None && _field[try1] == _field[try3] && _field[try2] == None ) { move = try2; if( _field[try1] == Computer ) break; } if( _field[try2] != None && _field[try2] == _field[try3] && _field[try1] == None ) { move = try1; if( _field[try2] == Computer ) break; } } _field[move] = Computer; } int _p; int _field[9]; }; int main( int argc, char* argv[] ) { srand( GetTickCount() ); ttt tic; tic.play(); return 0; }
import random board = list('123456789') wins = ((0,1,2), (3,4,5), (6,7,8), (0,3,6), (1,4,7), (2,5,8), (0,4,8), (2,4,6)) def printboard(): print('\n'.join(' '.join(board[x:x+3]) for x in(0,3,6))) def score(): for w in wins: b = board[w[0]] if b in 'XO' and all (board[i] == b for i in w): return b, [i+1 for i in w] return None, None def finished(): return all (b in 'XO' for b in board) def space(): return [ b for b in board if b not in 'XO'] def my_turn(xo): options = space() choice = random.choice(options) board[int(choice)-1] = xo return choice def your_turn(xo): options = space() while True: choice = input(" Put your %s in any of these positions: %s " % (xo, ''.join(options))).strip() if choice in options: break print( "Whoops I don't understand the input" ) board[int(choice)-1] = xo return choice def me(xo='X'): printboard() print('I go at', my_turn(xo)) return score() assert not s[0], "\n%s wins across %s" % s def you(xo='O'): printboard() print('You went at', your_turn(xo)) return score() assert not s[0], "\n%s wins across %s" % s print(__doc__) while not finished(): s = me('X') if s[0]: printboard() print("\n%s wins across %s" % s) break if not finished(): s = you('O') if s[0]: printboard() print("\n%s wins across %s" % s) break else: print('\nA draw')
Can you help me rewrite this code in Python instead of C++, keeping it the same logically?
#include <cstdint> #include <iostream> #include <limits> int main() { auto i = std::uintmax_t{}; while (i < std::numeric_limits<decltype(i)>::max()) std::cout << ++i << '\n'; }
i=1 while i: print(i) i += 1
Can you help me rewrite this code in Python instead of C++, keeping it the same logically?
#include <cstdint> #include <iostream> #include <limits> int main() { auto i = std::uintmax_t{}; while (i < std::numeric_limits<decltype(i)>::max()) std::cout << ++i << '\n'; }
i=1 while i: print(i) i += 1
Generate a Python translation of this C++ snippet without changing its computational steps.
#include <cstdint> #include <iostream> #include <limits> int main() { auto i = std::uintmax_t{}; while (i < std::numeric_limits<decltype(i)>::max()) std::cout << ++i << '\n'; }
i=1 while i: print(i) i += 1
Generate an equivalent Python version of this C++ code.
#include <iostream> #include <fstream> #include <cmath> using namespace std; string readFile (string path) { string contents; string line; ifstream inFile(path); while (getline (inFile, line)) { contents.append(line); contents.append("\n"); } inFile.close(); return contents; } double entropy (string X) { const int MAXCHAR = 127; int N = X.length(); int count[MAXCHAR]; double count_i; char ch; double sum = 0.0; for (int i = 0; i < MAXCHAR; i++) count[i] = 0; for (int pos = 0; pos < N; pos++) { ch = X[pos]; count[(int)ch]++; } for (int n_i = 0; n_i < MAXCHAR; n_i++) { count_i = count[n_i]; if (count_i > 0) sum -= count_i / N * log2(count_i / N); } return sum; } int main () { cout<<entropy(readFile("entropy.cpp")); return 0; }
import math from collections import Counter def entropy(s): p, lns = Counter(s), float(len(s)) return -sum( count/lns * math.log(count/lns, 2) for count in p.values()) with open(__file__) as f: b=f.read() print(entropy(b))
Write a version of this C function in C# with identical behavior.
void bitwise(int a, int b) { printf("a and b: %d\n", a & b); printf("a or b: %d\n", a | b); printf("a xor b: %d\n", a ^ b); printf("not a: %d\n", ~a); printf("a << n: %d\n", a << b); printf("a >> n: %d\n", a >> b); unsigned int c = a; printf("c >> b: %d\n", c >> b); return 0; }
static void bitwise(int a, int b) { Console.WriteLine("a and b is {0}", a & b); Console.WriteLine("a or b is {0}", a | b); Console.WriteLine("a xor b is {0}", a ^ b); Console.WriteLine("not a is {0}", ~a); Console.WriteLine("a lshift b is {0}", a << b); Console.WriteLine("a arshift b is {0}", a >> b); uint c = (uint)a; Console.WriteLine("c rshift b is {0}", c >> b); }
Write the same code in C# as shown below in C.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> long long x, y, dx, dy, scale, clen; typedef struct { double r, g, b; } rgb; rgb ** pix; void sc_up() { long long tmp = dx - dy; dy = dx + dy; dx = tmp; scale *= 2; x *= 2; y *= 2; } void h_rgb(long long x, long long y) { rgb *p = &pix[y][x]; # define SAT 1 double h = 6.0 * clen / scale; double VAL = 1 - (cos(3.141592653579 * 64 * clen / scale) - 1) / 4; double c = SAT * VAL; double X = c * (1 - fabs(fmod(h, 2) - 1)); switch((int)h) { case 0: p->r += c; p->g += X; return; case 1: p->r += X; p->g += c; return; case 2: p->g += c; p->b += X; return; case 3: p->g += X; p->b += c; return; case 4: p->r += X; p->b += c; return; default: p->r += c; p->b += X; } } void iter_string(const char * str, int d) { long tmp; # define LEFT tmp = -dy; dy = dx; dx = tmp # define RIGHT tmp = dy; dy = -dx; dx = tmp while (*str != '\0') { switch(*(str++)) { case 'X': if (d) iter_string("X+YF+", d - 1); continue; case 'Y': if (d) iter_string("-FX-Y", d - 1); continue; case '+': RIGHT; continue; case '-': LEFT; continue; case 'F': clen ++; h_rgb(x/scale, y/scale); x += dx; y += dy; continue; } } } void dragon(long leng, int depth) { long i, d = leng / 3 + 1; long h = leng + 3, w = leng + d * 3 / 2 + 2; rgb *buf = malloc(sizeof(rgb) * w * h); pix = malloc(sizeof(rgb *) * h); for (i = 0; i < h; i++) pix[i] = buf + w * i; memset(buf, 0, sizeof(rgb) * w * h); x = y = d; dx = leng; dy = 0; scale = 1; clen = 0; for (i = 0; i < depth; i++) sc_up(); iter_string("FX", depth); unsigned char *fpix = malloc(w * h * 3); double maxv = 0, *dbuf = (double*)buf; for (i = 3 * w * h - 1; i >= 0; i--) if (dbuf[i] > maxv) maxv = dbuf[i]; for (i = 3 * h * w - 1; i >= 0; i--) fpix[i] = 255 * dbuf[i] / maxv; printf("P6\n%ld %ld\n255\n", w, h); fflush(stdout); fwrite(fpix, h * w * 3, 1, stdout); } int main(int c, char ** v) { int size, depth; depth = (c > 1) ? atoi(v[1]) : 10; size = 1 << depth; fprintf(stderr, "size: %d depth: %d\n", size, depth); dragon(size, depth * 2); return 0; }
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; public class DragonCurve : Form { private List<int> turns; private double startingAngle, side; public DragonCurve(int iter) { Size = new Size(800, 600); StartPosition = FormStartPosition.CenterScreen; DoubleBuffered = true; BackColor = Color.White; startingAngle = -iter * (Math.PI / 4); side = 400 / Math.Pow(2, iter / 2.0); turns = getSequence(iter); } private List<int> getSequence(int iter) { var turnSequence = new List<int>(); for (int i = 0; i < iter; i++) { var copy = new List<int>(turnSequence); copy.Reverse(); turnSequence.Add(1); foreach (int turn in copy) { turnSequence.Add(-turn); } } return turnSequence; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; double angle = startingAngle; int x1 = 230, y1 = 350; int x2 = x1 + (int)(Math.Cos(angle) * side); int y2 = y1 + (int)(Math.Sin(angle) * side); e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2); x1 = x2; y1 = y2; foreach (int turn in turns) { angle += turn * (Math.PI / 2); x2 = x1 + (int)(Math.Cos(angle) * side); y2 = y1 + (int)(Math.Sin(angle) * side); e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2); x1 = x2; y1 = y2; } } [STAThread] static void Main() { Application.Run(new DragonCurve(14)); } }
Please provide an equivalent version of this C code in C#.
#include <conio.h> #include <stdio.h> int main() { int n1, n2, n3; printf( "\n Introduzca el primer n%cmero (entero): ", 163 ); scanf( "%d", &n1 ); printf( "\n Introduzca el segundo n%cmero (entero): ", 163 ); scanf( "%d", &n2 ); printf( "\n Introduzca el tercer n%cmero (entero): ", 163 ); scanf( "%d", &n3 ); if ( n1 >= n2 && n1 >= n3 ) printf( "\n %d es el mayor.", n1 ); else if ( n2 > n3 ) printf( "\n %d es el mayor.", n2 ); else printf( "\n %d es el mayor.", n3 ); getch(); return 0; }
foreach (string readLine in File.ReadLines("FileName")) DoSomething(readLine);
Write the same code in C# as shown below in C.
void insert(link* anchor, link* newlink) { newlink->next = anchor->next; newlink->prev = anchor; (newlink->next)->prev = newlink; anchor->next = newlink; }
static void InsertAfter(Link prev, int i) { if (prev.next != null) { prev.next.prev = new Link() { item = i, prev = prev, next = prev.next }; prev.next = prev.next.prev; } else prev.next = new Link() { item = i, prev = prev }; }
Translate the given C code snippet into C# without altering its behavior.
#include <stdio.h> #include <string.h> int qselect(int *v, int len, int k) { # define SWAP(a, b) { tmp = v[a]; v[a] = v[b]; v[b] = tmp; } int i, st, tmp; for (st = i = 0; i < len - 1; i++) { if (v[i] > v[len-1]) continue; SWAP(i, st); st++; } SWAP(len-1, st); return k == st ?v[st] :st > k ? qselect(v, st, k) : qselect(v + st, len - st, k - st); } int main(void) { # define N (sizeof(x)/sizeof(x[0])) int x[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}; int y[N]; int i; for (i = 0; i < 10; i++) { memcpy(y, x, sizeof(x)); printf("%d: %d\n", i, qselect(y, 10, i)); } return 0; }
using System; using System.Collections.Generic; using System.Linq; namespace QuickSelect { internal static class Program { #region Static Members private static void Main() { var inputArray = new[] {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}; Console.WriteLine( "Loop quick select 10 times." ); for( var i = 0 ; i < 10 ; i++ ) { Console.Write( inputArray.NthSmallestElement( i ) ); if( i < 9 ) Console.Write( ", " ); } Console.WriteLine(); Console.WriteLine( "Just sort 10 elements." ); Console.WriteLine( string.Join( ", ", inputArray.TakeSmallest( 10 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) ); Console.WriteLine( "Get 4 smallest and sort them." ); Console.WriteLine( string.Join( ", ", inputArray.TakeSmallest( 4 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) ); Console.WriteLine( "< Press any key >" ); Console.ReadKey(); } #endregion } internal static class ArrayExtension { #region Static Members public static IEnumerable<T> TakeSmallest<T>( this T[] array, int count ) where T : IComparable<T> { if( count < 0 ) throw new ArgumentOutOfRangeException( "count", "Count is smaller than 0." ); if( count == 0 ) return new T[0]; if( array.Length <= count ) return array; return QuickSelectSmallest( array, count - 1 ).Take( count ); } public static T NthSmallestElement<T>( this T[] array, int n ) where T : IComparable<T> { if( n < 0 || n > array.Length - 1 ) throw new ArgumentOutOfRangeException( "n", n, string.Format( "n should be between 0 and {0} it was {1}.", array.Length - 1, n ) ); if( array.Length == 0 ) throw new ArgumentException( "Array is empty.", "array" ); if( array.Length == 1 ) return array[ 0 ]; return QuickSelectSmallest( array, n )[ n ]; } private static T[] QuickSelectSmallest<T>( T[] input, int n ) where T : IComparable<T> { var partiallySortedArray = (T[]) input.Clone(); var startIndex = 0; var endIndex = input.Length - 1; var pivotIndex = n; var r = new Random(); while( endIndex > startIndex ) { pivotIndex = QuickSelectPartition( partiallySortedArray, startIndex, endIndex, pivotIndex ); if( pivotIndex == n ) break; if( pivotIndex > n ) endIndex = pivotIndex - 1; else startIndex = pivotIndex + 1; pivotIndex = r.Next( startIndex, endIndex ); } return partiallySortedArray; } private static int QuickSelectPartition<T>( this T[] array, int startIndex, int endIndex, int pivotIndex ) where T : IComparable<T> { var pivotValue = array[ pivotIndex ]; array.Swap( pivotIndex, endIndex ); for( var i = startIndex ; i < endIndex ; i++ ) { if( array[ i ].CompareTo( pivotValue ) > 0 ) continue; array.Swap( i, startIndex ); startIndex++; } array.Swap( endIndex, startIndex ); return startIndex; } private static void Swap<T>( this T[] array, int index1, int index2 ) { if( index1 == index2 ) return; var temp = array[ index1 ]; array[ index1 ] = array[ index2 ]; array[ index2 ] = temp; } #endregion } }
Translate this program into C# but keep the logic exactly as in C.
#include <stdio.h> #include <string.h> int qselect(int *v, int len, int k) { # define SWAP(a, b) { tmp = v[a]; v[a] = v[b]; v[b] = tmp; } int i, st, tmp; for (st = i = 0; i < len - 1; i++) { if (v[i] > v[len-1]) continue; SWAP(i, st); st++; } SWAP(len-1, st); return k == st ?v[st] :st > k ? qselect(v, st, k) : qselect(v + st, len - st, k - st); } int main(void) { # define N (sizeof(x)/sizeof(x[0])) int x[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}; int y[N]; int i; for (i = 0; i < 10; i++) { memcpy(y, x, sizeof(x)); printf("%d: %d\n", i, qselect(y, 10, i)); } return 0; }
using System; using System.Collections.Generic; using System.Linq; namespace QuickSelect { internal static class Program { #region Static Members private static void Main() { var inputArray = new[] {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}; Console.WriteLine( "Loop quick select 10 times." ); for( var i = 0 ; i < 10 ; i++ ) { Console.Write( inputArray.NthSmallestElement( i ) ); if( i < 9 ) Console.Write( ", " ); } Console.WriteLine(); Console.WriteLine( "Just sort 10 elements." ); Console.WriteLine( string.Join( ", ", inputArray.TakeSmallest( 10 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) ); Console.WriteLine( "Get 4 smallest and sort them." ); Console.WriteLine( string.Join( ", ", inputArray.TakeSmallest( 4 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) ); Console.WriteLine( "< Press any key >" ); Console.ReadKey(); } #endregion } internal static class ArrayExtension { #region Static Members public static IEnumerable<T> TakeSmallest<T>( this T[] array, int count ) where T : IComparable<T> { if( count < 0 ) throw new ArgumentOutOfRangeException( "count", "Count is smaller than 0." ); if( count == 0 ) return new T[0]; if( array.Length <= count ) return array; return QuickSelectSmallest( array, count - 1 ).Take( count ); } public static T NthSmallestElement<T>( this T[] array, int n ) where T : IComparable<T> { if( n < 0 || n > array.Length - 1 ) throw new ArgumentOutOfRangeException( "n", n, string.Format( "n should be between 0 and {0} it was {1}.", array.Length - 1, n ) ); if( array.Length == 0 ) throw new ArgumentException( "Array is empty.", "array" ); if( array.Length == 1 ) return array[ 0 ]; return QuickSelectSmallest( array, n )[ n ]; } private static T[] QuickSelectSmallest<T>( T[] input, int n ) where T : IComparable<T> { var partiallySortedArray = (T[]) input.Clone(); var startIndex = 0; var endIndex = input.Length - 1; var pivotIndex = n; var r = new Random(); while( endIndex > startIndex ) { pivotIndex = QuickSelectPartition( partiallySortedArray, startIndex, endIndex, pivotIndex ); if( pivotIndex == n ) break; if( pivotIndex > n ) endIndex = pivotIndex - 1; else startIndex = pivotIndex + 1; pivotIndex = r.Next( startIndex, endIndex ); } return partiallySortedArray; } private static int QuickSelectPartition<T>( this T[] array, int startIndex, int endIndex, int pivotIndex ) where T : IComparable<T> { var pivotValue = array[ pivotIndex ]; array.Swap( pivotIndex, endIndex ); for( var i = startIndex ; i < endIndex ; i++ ) { if( array[ i ].CompareTo( pivotValue ) > 0 ) continue; array.Swap( i, startIndex ); startIndex++; } array.Swap( endIndex, startIndex ); return startIndex; } private static void Swap<T>( this T[] array, int index1, int index2 ) { if( index1 == index2 ) return; var temp = array[ index1 ]; array[ index1 ] = array[ index2 ]; array[ index2 ] = temp; } #endregion } }
Can you help me rewrite this code in C# instead of C, keeping it the same logically?
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdint.h> char *to_base(int64_t num, int base) { char *tbl = "0123456789abcdefghijklmnopqrstuvwxyz"; char buf[66] = {'\0'}; char *out; uint64_t n; int i, len = 0, neg = 0; if (base > 36) { fprintf(stderr, "base %d too large\n", base); return 0; } n = ((neg = num < 0)) ? (~num) + 1 : num; do { buf[len++] = tbl[n % base]; } while(n /= base); out = malloc(len + neg + 1); for (i = neg; len > 0; i++) out[i] = buf[--len]; if (neg) out[0] = '-'; return out; } long from_base(const char *num_str, int base) { char *endptr; int result = strtol(num_str, &endptr, base); return result; } int main() { int64_t x; x = ~(1LL << 63) + 1; printf("%lld in base 2: %s\n", x, to_base(x, 2)); x = 383; printf("%lld in base 16: %s\n", x, to_base(x, 16)); return 0; }
public static class BaseConverter { public static long stringToLong(string s, int b) { if ( b < 2 || b > 36 ) throw new ArgumentException("Base must be between 2 and 36", "b"); checked { int slen = s.Length; long result = 0; bool isNegative = false; for ( int i = 0; i < slen; i++ ) { char c = s[i]; int num; if ( c == '-' ) { if ( i != 0 ) throw new ArgumentException("A negative sign is allowed only as the first character of the string.", "s"); isNegative = true; continue; } if ( c > 0x2F && c < 0x3A ) num = c - 0x30; else if ( c > 0x40 && c < 0x5B ) num = c - 0x37; else if ( c > 0x60 && c < 0x7B ) num = c - 0x57; else throw new ArgumentException("The string contains an invalid character '" + c + "'", "s"); if ( num >= b ) throw new ArgumentException("The string contains a character '" + c + "' which is not allowed in base " + b, "s"); result *= b; result += num; } if ( isNegative ) result = -result; return result; } } public static string longToString(long n, int b) { if ( b < 2 || b > 36 ) throw new ArgumentException("Base must be between 2 and 36", "b"); if ( b == 10 ) return n.ToString(); checked { long longBase = b; StringBuilder sb = new StringBuilder(); if ( n < 0 ) { n = -n; sb.Append('-'); } long div = 1; while ( n / div >= b ) div *= b; while ( true ) { byte digit = (byte) (n / div); if ( digit < 10 ) sb.Append((char) (digit + 0x30)); else sb.Append((char) (digit + 0x57)); if ( div == 1 ) break; n %= div; div /= b; } return sb.ToString(); } } }
Preserve the algorithm and functionality while converting the code from C to C#.
#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <regex.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <err.h> enum { WALK_OK = 0, WALK_BADPATTERN, WALK_NAMETOOLONG, WALK_BADIO, }; #define WS_NONE 0 #define WS_RECURSIVE (1 << 0) #define WS_DEFAULT WS_RECURSIVE #define WS_FOLLOWLINK (1 << 1) #define WS_DOTFILES (1 << 2) #define WS_MATCHDIRS (1 << 3) int walk_recur(char *dname, regex_t *reg, int spec) { struct dirent *dent; DIR *dir; struct stat st; char fn[FILENAME_MAX]; int res = WALK_OK; int len = strlen(dname); if (len >= FILENAME_MAX - 1) return WALK_NAMETOOLONG; strcpy(fn, dname); fn[len++] = '/'; if (!(dir = opendir(dname))) { warn("can't open %s", dname); return WALK_BADIO; } errno = 0; while ((dent = readdir(dir))) { if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.') continue; if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) continue; strncpy(fn + len, dent->d_name, FILENAME_MAX - len); if (lstat(fn, &st) == -1) { warn("Can't stat %s", fn); res = WALK_BADIO; continue; } if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK)) continue; if (S_ISDIR(st.st_mode)) { if ((spec & WS_RECURSIVE)) walk_recur(fn, reg, spec); if (!(spec & WS_MATCHDIRS)) continue; } if (!regexec(reg, fn, 0, 0, 0)) puts(fn); } if (dir) closedir(dir); return res ? res : errno ? WALK_BADIO : WALK_OK; } int walk_dir(char *dname, char *pattern, int spec) { regex_t r; int res; if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB)) return WALK_BADPATTERN; res = walk_recur(dname, &r, spec); regfree(&r); return res; } int main() { int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS); switch(r) { case WALK_OK: break; case WALK_BADIO: err(1, "IO error"); case WALK_BADPATTERN: err(1, "Bad pattern"); case WALK_NAMETOOLONG: err(1, "Filename too long"); default: err(1, "Unknown error?"); } return 0; }
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace RosettaRecursiveDirectory { class Program { static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern) { var directoryStack = new Stack<DirectoryInfo>(); directoryStack.Push(new DirectoryInfo(rootPath)); while (directoryStack.Count > 0) { var dir = directoryStack.Pop(); try { foreach (var i in dir.GetDirectories()) directoryStack.Push(i); } catch (UnauthorizedAccessException) { continue; } foreach (var f in dir.GetFiles().Where(Pattern)) yield return f; } } static void Main(string[] args) { foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv")) Console.WriteLine(file.FullName); Console.WriteLine("Done."); } } }
Please provide an equivalent version of this C code in C#.
#include <stdio.h> #include <string.h> #include <zlib.h> int main() { const char *s = "The quick brown fox jumps over the lazy dog"; printf("%lX\n", crc32(0, (const void*)s, strlen(s))); return 0; }
public class Crc32 { #region Constants private const UInt32 s_generator = 0xEDB88320; #endregion #region Constructors public Crc32() { m_checksumTable = Enumerable.Range(0, 256).Select(i => { var tableEntry = (uint)i; for (var j = 0; j < 8; ++j) { tableEntry = ((tableEntry & 1) != 0) ? (s_generator ^ (tableEntry >> 1)) : (tableEntry >> 1); } return tableEntry; }).ToArray(); } #endregion #region Methods public UInt32 Get<T>(IEnumerable<T> byteStream) { try { return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8))); } catch (FormatException e) { throw new CrcException("Could not read the stream out as bytes.", e); } catch (InvalidCastException e) { throw new CrcException("Could not read the stream out as bytes.", e); } catch (OverflowException e) { throw new CrcException("Could not read the stream out as bytes.", e); } } #endregion #region Fields private readonly UInt32[] m_checksumTable; #endregion }
Port the provided C code into C# while preserving the original functionality.
#include <stdlib.h> typedef struct sMyClass { int variable; } *MyClass; MyClass MyClass_new() { MyClass pthis = malloc(sizeof *pthis); pthis->variable = 0; return pthis; } void MyClass_delete(MyClass* pthis) { if (pthis) { free(*pthis); *pthis = NULL; } } void MyClass_someMethod(MyClass pthis) { pthis->variable = 1; } MyClass obj = MyClass_new(); MyClass_someMethod(obj); MyClass_delete(&obj);
public class MyClass { public MyClass() { } public void SomeMethod() { } private int _variable; public int Variable { get { return _variable; } set { _variable = value; } } public static void Main() { MyClass instance = new MyClass(); instance.SomeMethod(); instance.Variable = 99; System.Console.WriteLine( "Variable=" + instance.Variable.ToString() ); } }
Write the same algorithm in C# as shown in this C implementation.
#include <stdio.h> #include <stdint.h> typedef uint64_t ulong; int kaprekar(ulong n, int base) { ulong nn = n * n, r, tens = 1; if ((nn - n) % (base - 1)) return 0; while (tens < n) tens *= base; if (n == tens) return 1 == n; while ((r = nn % tens) < n) { if (nn / tens + r == n) return tens; tens *= base; } return 0; } void print_num(ulong n, int base) { ulong q, div = base; while (div < n) div *= base; while (n && (div /= base)) { q = n / div; if (q < 10) putchar(q + '0'); else putchar(q + 'a' - 10); n -= q * div; } } int main() { ulong i, tens; int cnt = 0; int base = 10; printf("base 10:\n"); for (i = 1; i < 1000000; i++) if (kaprekar(i, base)) printf("%3d: %llu\n", ++cnt, i); base = 17; printf("\nbase %d:\n 1: 1\n", base); for (i = 2, cnt = 1; i < 1000000; i++) if ((tens = kaprekar(i, base))) { printf("%3d: %llu", ++cnt, i); printf(" \t"); print_num(i, base); printf("\t"); print_num(i * i, base); printf("\t"); print_num(i * i / tens, base); printf(" + "); print_num(i * i % tens, base); printf("\n"); } return 0; }
using System; using System.Collections.Generic; public class KaprekarNumbers { public static void Main() { int count = 0; foreach ( ulong i in _kaprekarGenerator(999999) ) { Console.WriteLine(i); count++; } Console.WriteLine("There are {0} Kaprekar numbers less than 1000000.", count); } private static IEnumerable<ulong> _kaprekarGenerator(ulong max) { ulong next = 1; yield return next; for ( next = 2; next <= max; next++ ) { ulong square = next * next; for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) { if ( square <= check ) break; ulong r = square % check; ulong q = (square - r) / check; if ( r != 0 && q + r == next ) { yield return next; break; } } } } }