text
stringlengths
1
2.12k
source
dict
c++, object-oriented, console Pass by const reference where practical The third argument to Player::movePlayer is a Map but that causes the entire map to be duplicated. Better would be to make it const Map & because it is not modified and it doesn't need to be duplicated. Use standard functions where appropriate The current Player::movePlayer() function is this (with the modification mentioned above): void Player::movePlayer(int x, int y, const Map &m){ if(!(coord.x + x >= m.getWidth() || coord.x + x < 0)){//If not at the map limit, move coord.x += x; } if(!(coord.y + y >= m.getHeight() || coord.y + y < 0)){ coord.y += y; } } This is much easier to write using std::clamp(): void Player::movePlayer(int x, int y, const Map &m){ coord.x = std::clamp(coord.x + x, 0, m.getWidth()); coord.y = std::clamp(coord.y + y, 0, m.getHeight()); } Prefer modern initializers for constructors The constructor for Player is this: Player::Player(){ coord.x=0; coord.y=0; } Better would be to simply have a default constructor for the Coordinate and then you could omit the Player constructor and simply have the compiler write one. struct Coordinate{ int x{0}; int y{0}; }; See C.48 for details. Fix the bug The Game::processInput has a few bugs in it. First, it passes Player p which is not used and should therefore not be passed. Second, it has these lines: char movement; std::cin>>movement; tolower(movement); return movement; The tolower has no effect here. What you probably intended was this: return tolower(movement); The name is also not good. It isn't really processing the input, only getting it from the user. Rethink the interface The Game constructor doesn't just create the game but also runs it and never returns. Consequently, main looks like this: int main(){ Game game; }
{ "domain": "codereview.stackexchange", "id": 42610, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, console", "url": null }
c++, object-oriented, console A human reader would likely wonder why a game object is created and never used. Better would be to have separate public functions: the constructor should just construct the object, and the loop (or perhaps play()) with a possibly separate check for end of game function. A revised version of Game.hpp is this: #ifndef GAME_H #define GAME_H #include "Player.hpp" #include "Map.hpp" class Game{ public: bool play(); void draw() const; private: Player p; Map m{5, 5}; }; #endif Now main is this: int main(){ Game game; do { game.draw(); } while (game.play()); } Think of the user I know this is just a preliminary study, but there is no way to exit the program gracefully. That's an easy fix. I rewrote and renamed your update like this: bool Game::play() { bool playing{true}; char movement; std::cin >> movement; switch (tolower(movement)) { case 'w'://up p.movePlayer(0,-1,m); break; case 'a'://left p.movePlayer(-1,0,m); break; case 's'://down p.movePlayer(0,1,m); break; case 'd'://right p.movePlayer(1,0,m); break; case 'x': // exit playing = false; default: break; } return playing; } Simplify your constructors There is no reason for the Map constructor to call initMap. Instead the functionality of initMap should be incorporated into the constructor directly. Further, rather than stepping through every character, you can use std::vector and std::string constructor forms which take a count and a value. Map::Map(std::size_t h, std::size_t w) : width{w} , height{h} , level{height, std::string(width, '.')} { } Note that I've also converted width and height to std::size_t type. There would be little sense in specifying a negative value for either.
{ "domain": "codereview.stackexchange", "id": 42610, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, console", "url": null }
python Title: Calculating the grade of students using dictionaries. What can be used instead of eval? Question: I am a new coder and have seen people on Stack discuss why eval use is not recommended. In the following code, we have been given a set of dictionaries with the marks of the students, we take the student name as an input and provide the output as per the formula given (the formula for the calculation of marks). # 1. Jack's dictionary Jack = { "name":"Jack", "assignment" : [80, 50, 40, 20], "test" : [75, 75], "lab" : [78.20, 77.20] } # 2. James's dictionary james = { "name":"James", "assignment" : [82, 56, 44, 30], "test" : [80, 80], "lab" : [67.90, 78.72] } # 3. Dylan's dictionary dylan = { "name" : "Dylan", "assignment" : [77, 82, 23, 39], "test" : [78, 77], "lab" : [80, 80] } # 4. Jessica's dictionary jess = { "name" : "Jessica", "assignment" : [67, 55, 77, 21], "test" : [40, 50], "lab" : [69, 44.56] } # 5. Tom's dictionary tom = { "name" : "Tom", "assignment" : [29, 89, 60, 56], "test" : [65, 56], "lab" : [50, 40.6] } name = eval(input()) marks = (0.1*(sum(name['assignment'])/len(name['assignment']))) + (0.7*(sum(name['test'])/len(name['test']))) + (0.2*(sum(name['lab'])/len(name['lab']))) asci = 65 print('Average marks of {} is :'.format(name['name']),marks) def GradeAssign(a,marks,asci): if a >= 60: if marks >= a: print('Letter Grade of {} is :'.format(name['name']),chr(asci)) else : a -= 10 asci += 1 GradeAssign(a,marks,asci) else : print('Letter Grade of {} is :'.format(name['name']),'E') GradeAssign(90,marks,asci) Now I can't seem to figure out a way to not use eval in the following line: name = eval(input())
{ "domain": "codereview.stackexchange", "id": 42611, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python Now I can't seem to figure out a way to not use eval in the following line: name = eval(input()) Answer: Start with a solid foundation. Even simple scripts like this can benefit by following a simple rule: put all algorithmic code inside of functions. At the top level, you can perform imports or define constants, functions, or classes. Everything else must be in functions. For this program, we could start with the following sketch: jack = {...} james = {...} dylan = {...} jess = {...} tom = {...} def main(): student = get_student() score = compute_score(student) letter = compute_grade(score) print(score, letter) def get_student(): return jack def compute_score(student): return 100 def compute_grade(score): return 'A' if __name__ == '__main__': main() Take advantage of data structures. You have 5 constants in the form of student dicts. And you have a name that will be entered by the program user (e.g., 'jack'). You don't need exotic techniques like eval() to transform that user-entered string into a Python variable. Rather, you need a dict mapping each student name to its corresponding dict of information about the student. This simple function will do the trick: def collect_students(): return { d['name'].lower() : d for d in (jack, james, dylan, jess, tom) } Validate user input. Once we have that utility function, we can implement the behavior to get user input and return the corresponding student dict. Code to collect user input should normally be written with an awareness that people make mistakes. A while True loop is often the most flexible mechanism for these situations: get the input, validate it, and return if OK: def get_student(): students = collect_students() while True: name = input('Enter student name: ') try: return students[name.lower()] except KeyError: pass
{ "domain": "codereview.stackexchange", "id": 42611, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python Use data structures to simplify algorithms. Your code to compute the student's overall score is repetitive (it computes 3 different means) and hard to read (a long, dense line of code). However, if we define a simple data structure -- in this case, a dict mapping each type of coursework to its weight in the overall score -- we can compute the overall score more understandably: def compute_score(student): weights = {'assignment': 0.1, 'test': 0.7, 'lab': 0.2} return sum( w * mean(student[k]) for k, w in weights.items() ) def mean(vals): # Better: raise exception if vals is empty. # Even better: use statistics.mean(). return sum(vals) / len(vals) Use data structures to simplify algorithms -- yet again. Your code to compute the letter grade is algorithmically complex (relying on recursion) and opaque (with cryptic variable names like asci and a). None of that is needed if you define a dict mapping each minimum-score to its corresponding letter grade. (Note that this relies on the insertion-ordering property of dicts in modern Python.) def compute_grade(score): grades = {90: 'A', 80: 'B', 70: 'C', 60: 'D'} for min_score, letter in grades.items(): if score >= min_score: return letter return 'E'
{ "domain": "codereview.stackexchange", "id": 42611, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python, beginner, object-oriented, hangman Title: Objected-Oriented Hangman game In Python Question: I'm still a beginner in python and made this simple program to practice OOP, I've ended up using the self keyword a lot and I'm not sure if this is normal or if I just misunderstood something. Any criticism on the program itself or good practices in python are also greatly appreciated. (Text File 'Words' is just 3000+ English words listed) Edit: Instance variable cont was only used in 1 function so it was switched to a local variable inside function play Hangman.py import random from phases import hang_phases class HangMan: def __init__(self, random_word, letters): self.word = random_word self.letters = letters self.excluded_letters = [] self.included_letters = [] self.original_word = random_word self.chances = 9 def remove_letter(self, guessed_letter): self.word = self.word.replace(guessed_letter, "") self.included_letters.append(guessed_letter) def guess_letter(self): print(hang_phases[self.chances]) guessed_letter = input("Guess A Letter: ").upper() if guessed_letter in self.excluded_letters: print("You Already Guessed This Letter") elif guessed_letter in self.word: number_of_letter = self.word.count(guessed_letter) if number_of_letter == 1: print(f"There is {number_of_letter} {guessed_letter}") else: print(f"There are {number_of_letter} {guessed_letter}'s") self.remove_letter(guessed_letter) else: print(f"There are no {guessed_letter}'s") self.excluded_letters.append(guessed_letter) self.chances -= 1
{ "domain": "codereview.stackexchange", "id": 42612, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, object-oriented, hangman", "url": null }
python, beginner, object-oriented, hangman def play(self): cont = True while cont: if self.word == "": print(f"Congrats! The Word Was {self.original_word}") cont = False else: try: if self.chances == 0: print("The Man Has Been Hung! Better Luck Next Time :/") print(f"The Word Was {self.original_word}") print(hang_phases[0]) cont = False else: print() print("What Would You Like To Do?:\n*Please Enter The Integer Value Corresponding To The Action") print("1. Guess A Letter\n" "2. Check Included Guessed Letters\n" "3. Check Excluded Guessed Letters\n" "4. Get Length Of The Word\n" "5. Give Up\n")
{ "domain": "codereview.stackexchange", "id": 42612, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, object-oriented, hangman", "url": null }
python, beginner, object-oriented, hangman action = int(input("> ")) int(action) if action == 1: self.guess_letter() elif action == 2: if len(self.included_letters) == 0: print("You Have Not Guessed Any Letters That Are In The Word") else: print(self.included_letters) elif action == 3: if len(self.excluded_letters) == 0: print("You Have Not Guessed Any Letters That Are Not In The Word") else: print(self.excluded_letters) elif action == 4: print(len(self.original_word)) elif action == 5: print(f"The Word Is {self.original_word}") cont = False else: print("Pleas Enter A Value Between 1 & 5") except ValueError: print("Please Enter A Valid Integer") def main(): play = True while play: word_list = open('Words').read().split("\n") word = random.choice(word_list).upper() hm = HangMan(word, len(word)) hm.play() print("Play Again?") play_again = input("Y/n > ").upper() if play_again == "Y": print("Setting Up...") elif play_again == "N": print("Goodbye") play = False if __name__ == "__main__": main()
{ "domain": "codereview.stackexchange", "id": 42612, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, object-oriented, hangman", "url": null }
python, beginner, object-oriented, hangman if __name__ == "__main__": main() phases.py hang_phases = [ ''' ______ rip lol. | | | O | \|/ | | | _/ \_ _|_ ''' , ''' ______ | | | O | \|/ | | | _/ \\ _|_ ''' , ''' ______ | | | O | \|/ | | | _/ _|_ ''' , ''' ______ | | | O | \|/ | | | / _|_ ''' , ''' ______ | | | O | \|/ | | | _|_ ''' , ''' ______ | | | O | \|/ | | _|_ ''' , ''' ______ | | | O | \| | | _|_ ''' , ''' ______ | | | O | | | | _|_ ''' , ''' ______ | | | O | | | _|_ ''' , ''' ______ | | | | | | _|_ ''' ]
{ "domain": "codereview.stackexchange", "id": 42612, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, object-oriented, hangman", "url": null }
python, beginner, object-oriented, hangman Answer: Simpler UI. A lot of your code is devoted to managing the user-interface, which is organized around five numbered choices (guess letter, see successful guesses, see failed guesses, see length of word, or give up). As a user, I find that process very tedious: type 1, press enter, type a letter, press enter, press 1, type letter, press enter, type 4, see length of word, etc etc etc. All of that hassle is unnecessary because you could easily display all of the relevant information all of the time. Furthermore, that's what most Hangman implementations do. The other thing that most Hangman games do is tell you where the successful guesses reside within the entire word. Here's a mock-up showing everything the user needs to know, followed by a prompt waiting for the next guess. And if the user just presses enter, you can interpret that as "give up", which would eliminate the need for a numbered UI. That relatively simple adjustment to your plan would substantially reduce the amount of code needed while also making life better for users: ______ | | | O | \|/ | | | _|_ Word T _ D I O U _ Missses A C F R Z >
{ "domain": "codereview.stackexchange", "id": 42612, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, object-oriented, hangman", "url": null }
python, beginner, object-oriented, hangman Strings are sequences with stealth members. Python strings are great because they are built on top of sequences, which means you can easily iterate over them character by character. However, strings are not merely character sequences, and naive membership queries can sometimes go awry. In your case, if a user guessing a letter just presses enter rather than typing a letter, your program incorrectly reports that the "letter" (in this case the empty string) appears in the word N + 1 times, where N is the length of the word. And for strings, that is technically correct: the empty string can be found before every letter and at the end of the string. That makes sense from a computer-sciency point of view of strings, but it's not intuitive if we view strings purely as a sequence of characters. Don't force the caller to do routine work. A user of your HangMan class is required to supply both a word and the number of letters in that word. A friendlier hangman would do that computation for the victim, free of charge. Boundaries: consider the purpose of the HangMan class. It's good to find projects to practice OOP. One part of that learning process it developing solid instincts about boundaries: what belongs in the class and what does not. These can be tricky questions and software engineers have a variety of opinions about how to draw such lines. If it were me, I would probably treat HangMan as nothing more that a dataclass to keep basic facts about game state (the word, prior guesses) and a variety of derived or computable attributes (prior hits, prior misses, number of remaining guesses). In other words, the class would not collect user input or orchestrate the playing of the game. Such matters would be handled elsewhere, maybe in a different class, maybe in a static method of the class, or in an ordinary function (I would probably opt for the latter). Why that division? Because most of the algorithmic aspects of the
{ "domain": "codereview.stackexchange", "id": 42612, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, object-oriented, hangman", "url": null }
python, beginner, object-oriented, hangman Why that division? Because most of the algorithmic aspects of the code are questions about data: letters in the word, prior guesses, remaining guesses before death. I want algorithmic logic in data-oriented code that can be easily tested and debugged. I don't want such code to be burdened by the annoyances of user-interface. Meanwhile, I want the UI portions of the code to be very simple from an algorithmic/logical point of view so that I don't need to spend too much effort with testing and debugging. I want the inevitably annoying UI-oriented code to be as free of logical complexity as possible: just procedural step-by-step stuff whenever possible. Gary Bernhardt's talk on the subject of class boundaries is a classic in this line of thought.
{ "domain": "codereview.stackexchange", "id": 42612, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, object-oriented, hangman", "url": null }
c#, winforms Title: Simple stock taking program in C# Windows forms Question: so I've made a simple program meant to increase and decrease numbers, then save those numbers, basically a rubbish stock taking app, I want to make one I can use and well it's usable I'd say the code isn't refined enough to take it from this little program to a bigger better one. I want to make one because I want to practice programming more and I want a simple program that works well with a tablet. I'm wondering if there is a better way to program the buttons and the way it saves and loads more efficiently I don't want every button to have the same code but I can't seem to figure out how. Thanks This was done with C# in Windows forms The top section of my code saves it, the middle loads it and the long repetitive end are all the buttons, there is also an attempt to make a timer in there Code in text: using (StreamWriter outputfile = new StreamWriter($@"SaveData.txt")) { //Loads the stuff from the last session string OutPut = Item1.Text + "\n" + Amount1.Text + "\n" + Item2.Text + "\n" + Amount2.Text + "\n" + Item3.Text + "\n" + Amount3.Text + "\n" + Item4.Text + "\n" + Amount4.Text + "\n" + Item5.Text + "\n" + Amount5.Text + "\n" + Item6.Text + "\n" + Amount6.Text; outputfile.WriteLine(OutPut); }; z Save.Text = "Saved"; //My attempt to make a timer v { /* My attempt at making the saved button count up. for (int a = 0; a < 60; a++) { int savedSince = a; Save.Text = "Saved" + " " + Convert.ToString(savedSince); Task.Delay(1000); } Save.Text = "Saved <1 Min"; */ } } private void Load_Click(object sender, EventArgs e) { using (StreamReader inputfile = new StreamReader($@"SaveData.txt")) { //This is to load everything by reading the text file line by line for each thing.
{ "domain": "codereview.stackexchange", "id": 42613, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, winforms", "url": null }
c#, winforms //This is to load everything by reading the text file line by line for each thing. Item1.Text = inputfile.ReadLine(); Amount1.Text = inputfile.ReadLine(); Item2.Text = inputfile.ReadLine(); Amount2.Text = inputfile.ReadLine(); Item3.Text = inputfile.ReadLine(); Amount3.Text = inputfile.ReadLine(); Item4.Text = inputfile.ReadLine(); Amount4.Text = inputfile.ReadLine(); Item5.Text = inputfile.ReadLine(); Amount5.Text = inputfile.ReadLine(); Item6.Text = inputfile.ReadLine(); Amount6.Text = inputfile.ReadLine(); } } /* The first one adds 1 to the count by taking the text box and turning it into an int then taking the new int and turning it into a string and replacing the text box with it, same for the second one but it takes one off, then it repeats for the next two buttons and so on */ private void Add1_Click(object sender, EventArgs e) { int amount = Convert.ToInt32(Amount1.Text) + 1; Amount1.Text = Convert.ToString(amount); } private void Decrease1_Click(object sender, EventArgs e) { int amount = Convert.ToInt32(Amount1.Text) - 1; Amount1.Text = Convert.ToString(amount); } private void Add2_Click(object sender, EventArgs e) { int amount = Convert.ToInt32(Amount2.Text) + 1; Amount2.Text = Convert.ToString(amount); } private void Decrease2_Click(object sender, EventArgs e) { int amount = Convert.ToInt32(Amount2.Text) - 1; Amount2.Text = Convert.ToString(amount); } private void Add3_Click(object sender, EventArgs e) { int amount = Convert.ToInt32(Amount3.Text) + 1; Amount3.Text = Convert.ToString(amount); } private void Decrease3_Click(object sender, EventArgs e) { int amount = Convert.ToInt32(Amount3.Text) - 1; Amount3.Text = Convert.ToString(amount); } private void Add4_Click(object sender, EventArgs e) { int amount = Convert.ToInt32(Amount4.Text) + 1;
{ "domain": "codereview.stackexchange", "id": 42613, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, winforms", "url": null }
c#, winforms Amount4.Text = Convert.ToString(amount); } private void Decrease4_Click(object sender, EventArgs e) { int amount = Convert.ToInt32(Amount4.Text) - 1; Amount4.Text = Convert.ToString(amount); } private void Add5_Click(object sender, EventArgs e) { int amount = Convert.ToInt32(Amount5.Text) + 1; Amount5.Text = Convert.ToString(amount); } private void Decrease5_Click(object sender, EventArgs e) { int amount = Convert.ToInt32(Amount5.Text) - 1; Amount5.Text = Convert.ToString(amount); } private void Add6_Click(object sender, EventArgs e) { int amount = Convert.ToInt32(Amount6.Text) + 1 Answer: @jdt gave a decent answer and I particularly like the closing statement of using a DataGridView. For now, let's look at other alternative techniques using text boxes. To output the values to to text file, you can try var boxes = new List<TextBox>() { Item1, Amount1, Item2, Amount2, Item3, Amount3, Item4, Amount4, Item5, Amount5 }; string output = String.Join(Environment.NewLine, boxes.Select(x => x.Text)); File.WriteAllText("SaveData.txt", output); This uses the more proper Environment.NewLine , which is a new line AND carriage return. It also is OS independent so your app would run smoothly on Linux as well as Windows. There is no need for a using since we output the contents all at once. To Add or Decrease Amounts by 1 private void UpdateAmount(TextBox amountBox, int adjustment) { int amount = Convert.ToInt32(amountBox.Text) + adjustment; amountBox.Text = amount.ToString(); } private void Add1_Click(object sender, EventArgs e) => UpdateAmount(Amount1, 1); private void Decrease1_Click(object sender, EventArgs e) => UpdateAmount(Amount1, -1); // Repeat for Amount2 - 4 private void Add5_Click(object sender, EventArgs e) => UpdateAmount(Amount5, 1); private void Decrease5_Click(object sender, EventArgs e) => UpdateAmount(Amount5, -1);
{ "domain": "codereview.stackexchange", "id": 42613, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, winforms", "url": null }
c#, winforms Most C# developers would prefer to use the simple amount.ToString() rather than Convert.ToString(amount).
{ "domain": "codereview.stackexchange", "id": 42613, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, winforms", "url": null }
c++, wrapper, stl Title: Wrapper class to get pairs in range-for loop Question: This code implements a simple wrapper, intended to be used with range-for to manipulate items of a container as overlapping pairs, ie. 3 items will give 2 pairs. Code review focus: Is pair_range good modern C++? Any easily avoidable performance issues, like unnecessary copies? #include <iostream> #include <typeinfo> #include <iterator> #include <optional> #include <utility> template<class V, template<class...> class C> class pair_range { public: struct pair_iterator { using iterator_category = std::forward_iterator_tag; using difference_type = ssize_t; using value_type = std::pair<V, V>; using pointer = ssize_t; using reference = std::pair<V, V>; // no actual reference available pair_iterator(const pair_range & sequence, pointer index = 0) : m_sequence(sequence) , m_index(index) { }; const reference operator*() const { return value_type{m_sequence.at(m_index), m_sequence.at(m_index+1)}; } //operator->() not possible because pairs are not lvalues // prefix increment auto &operator++() { m_index++; return *this; } // postfix increment auto operator++(int) { auto tmp = *this; ++(*this); return tmp; } friend bool operator== (const pair_iterator &a, const pair_iterator &b) { return a.m_index == b.m_index && a.m_sequence.has_same_container(b.m_sequence); }; friend bool operator!= (const pair_iterator &a, const pair_iterator &b) { return a.m_index != b.m_index || !a.m_sequence.has_same_container(b.m_sequence); }; private: const pair_range &m_sequence; pointer m_index = 0; };
{ "domain": "codereview.stackexchange", "id": 42614, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, wrapper, stl", "url": null }
c++, wrapper, stl private: const pair_range &m_sequence; pointer m_index = 0; }; pair_range(const C<V> &source) : m_source_ptr(&source) { const std::type_info &ti = typeid(*this); std::cout << "&-constructor, type=" << ti.name() << std::endl; } pair_range(const C<V> &&source) : m_source_copy(std::move(source)), m_source_ptr(&m_source_copy.value()) { const std::type_info &ti = typeid(*this); std::cout << "&&-constructor, type=" << ti.name() << std::endl; } pair_iterator begin() const { return pair_iterator{*this}; } pair_iterator end() const { auto size = m_source_ptr->size(); auto end = static_cast<typename pair_iterator::pointer>(size == 0 ? 0 : size - 1); return pair_iterator{*this, end}; } bool has_same_container(const pair_range &other) const { return m_source_ptr == other.m_source_ptr; } private: const V &at(typename pair_iterator::pointer index) const { return (*m_source_ptr)[index]; } const std::optional<const C<V> > m_source_copy; const C<V> * const m_source_ptr = nullptr; }; // test code #include <algorithm> #include <map> #include <string> #include <vector> #include <variant> template <class T> void printPair(const T &pair) { const std::type_info &ti = typeid(pair); std::cout << std::get<0>(pair) << ' ' << std::get<1>(pair) << ", type=" << ti.name() << std::endl; } int main() { std::cout << "--- empty list ---\n"; const std::vector<int> list1{}; for(auto pair : pair_range(list1)) { printPair(pair); } std::cout << "--- 1 elements ---\n"; for(auto &pair : pair_range( std::vector{1} )) { printPair(pair); } std::cout << "--- 2 elements ---\n"; std::vector xy{ std::string("x"), std::string("y") }; for(auto &pair : pair_range(xy)) { printPair(pair); }
{ "domain": "codereview.stackexchange", "id": 42614, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, wrapper, stl", "url": null }
c++, wrapper, stl std::cout << "--- 4 elements ---\n"; const std::string abcd = {"abcd"}; for(const std::tuple<char, char> &pair : pair_range(abcd)) { printPair(pair); } } Here's the output of that code on my machine: --- empty list --- &-constructor, type=10pair_rangeIiSt6vectorE --- 1 elements --- &&-constructor, type=10pair_rangeIiSt6vectorE --- 2 elements --- &-constructor, type=10pair_rangeINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt6vectorE x y, type=St4pairINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES5_E --- 4 elements --- &-constructor, type=10pair_rangeIcNSt7__cxx1112basic_stringEE a b, type=St5tupleIJccEE b c, type=St5tupleIJccEE c d, type=St5tupleIJccEE Answer: std::cout << "&-constructor, type=" << ti.name() << std::endl; For this debugging output, consider using __PRETTY_FUNCTION__ (MSVC calls it __FUNCSIG__) instead of std::type_info. On GCC, your way prints &-constructor, type=10pair_rangeIiSt6vectorE &&-constructor, type=10pair_rangeIiSt6vectorE whereas a simple std::cout << __PRETTY_FUNCTION__ << '\n'; prints pair_range<V, C>::pair_range(const C<V>&) [with V = int; C = std::vector] pair_range<V, C>::pair_range(const C<V>&&) [with V = int; C = std::vector] Consider naming it pair_range::iterator instead of pair_range::pair_iterator. Consider naming it adjacent_pairs_range instead of just pair_range; the operation here is pretty similar to what happens inside std::adjacent_find and std::adjacent_difference. In fact, a great test of this code would be for you to reimplement std::adjacent_find in terms of std::find-over-an-adjacent_pairs_range! Your pair_range is trying to do something weird where if you pass its constructor an lvalue it captures a pointer to the lvalue, but if you pass it an rvalue it captures a copy of the rvalue and a pointer to its own copy. There are at least three things wrong here:
{ "domain": "codereview.stackexchange", "id": 42614, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, wrapper, stl", "url": null }
c++, wrapper, stl Value category is not lifetime. It's extremely easy to create a dangling pair_range, and worse, in some common cases where the user might think they were creating a dangling pair_range, the code happens to work anyway! It's hard to form a correct mental model of what's going on with this type. Capturing a pointer into yourself is never a great idea. It generally means that you need to follow the Rule of Three (or Five), instead of the Rule of Zero, because copying or moving such an object won't update its internal pointer-to-self. for (auto&& p : pair_range(std::vector{1,2,3})) // OK for (auto&& p : std::identity()(pair_range(std::vector{1,2,3}))) // UB, prints garbage For a simpler mental model, and a simpler implementation (more efficient and twice as easy to unit-test), I recommend giving your type only a constructor from const R& and always capturing a pointer to that lvalue. Let the caller worry about making sure the lvalue lives long enough to be used; and let the caller forget about any value-category-related gotchas built into pair_range. (This is the Unix philosophy, btw: simple, composable tools that do one thing, instead of being able to do two things and always having to guess which of them the user wants.) Typo or misunderstanding (or both) here: pair_range(const C<V> &&source) : m_source_copy(std::move(source)), m_source_ptr(&m_source_copy.value()) { }
{ "domain": "codereview.stackexchange", "id": 42614, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, wrapper, stl", "url": null }
c++, wrapper, stl Since source here is a reference to a const-qualified C<V>, there's really no point in trying to move from it. std::move is for when you have an rvalue that you can pilfer the guts of, i.e., source should be non-const-qualified. Also, all of these constructors should be explicit as a matter of course. The only reason to create a non-explicit ("implicit") constructor in C++ is when you want implicit conversion, either from a single argument (e.g. myBignum = 42 instead of myBignum = Bignum(42)) or from a braced sequence (e.g. myPair = {'x', 42} instead of myPair = Pair('x', 42), or myWidget = {} instead of myWidget = Widget()). //operator->() not possible because pairs are not lvalues It's possible; you need the arrow proxy idiom. And I think it's worth doing, because if I've got an iterator it that points into a range of pairs, you know I'm going to want to access it->first and it->second. If I can't do that, it's going to be annoying. As JDługosz mentioned, you can omit operator!= in C++20; and even in C++17, it's probably more readable in this case to implement its body as return !(a == b);. Your pair_iterator has a data member of reference type. Never use data members of const or reference type! In this particular case, it bites you by making pair_iterator's assignment operator implicitly deleted (because references are not rebindable). So pair_iterator does not satisfy C++20's input_or_output_iterator concept. Here's some good C++20 advice: If you're trying to implement a type that satisfies some library concept, such as "This type is an iterator" or "This type is a contiguous range" or "This type is regular" or "This type is three-way comparable" — static_assert is your friend! static_assert(std::input_or_output_iterator<adjacent_pair_range<int[10]>::iterator>); If that assertion fails, you know you have work to do. ...And waitaminute, what the heck is going on with these template parameters?! template<class V, template<class...> class C> class pair_range {
{ "domain": "codereview.stackexchange", "id": 42614, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, wrapper, stl", "url": null }
c++, wrapper, stl No no no. It should look more like template<class R> class adjacent_pair_range { where R is the type of the range to which you're capturing a pointer. Your pointer type shouldn't be ssize_t; that's an integer type. Use std::pair<V,V>* or perhaps just void (does that work? I haven't tested). Alternatively, in C++20 and later, just omit pointer because nobody cares anymore. Your operator* returns const reference, which is wrong: returning "by const value" is never meaningful, and if reference actually were a reference type (which it's not), then const reference would be exactly the same type as reference (because all references are const themselves; what you might have meant here was "reference to const," but that's not the same thing). Once you implement the arrow proxy idiom, your reference type will end up being std::pair<V&, V&>. This is good because it allows people to iterate over and mutate their ranges, like this: template<class R> void inclusive_scan(R&& r) { for (auto&& pair : adjacent_pairs_range(r)) { pair->second += pair->first; } } std::vector<int> v = {3,1,4,1,5}; inclusive_scan(v); assert(( v == std::vector<int>{3,4,8,9,14} )); I recommend fixing all this stuff — and whatever more you need to fix in order to make your type model forward_range; remember to use static_assert liberally in your test cases — and then ask a new question to get more reviews. :)
{ "domain": "codereview.stackexchange", "id": 42614, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, wrapper, stl", "url": null }
php Title: a php function to check if a value is 'falsy', but let pass 0 Question: I need to check if a variable is not: '', [], null, false But check must pass if variable is 0, 0.0, '0', [0], ['0'] At this time, I came up with this: function is_empty($item){ if(!isset($item)) return true; // null if(is_string($item)){ $s = trim($item); if($s != '0' && empty($s)) return true; // empty string, let '0' } if(is_array($item) && empty($item)) return true; // empty array return false; // not empty } Anything I can do better? Answer: You can use is_numeric() to cover all numeric-like values, including numeric strings, integers and floats. Non-numeric values don't need additional handling, they can all be covered by empty(). So this is enough: function is_empty($item) { return empty($item) && !is_numeric($item); } https://3v4l.org/LWc3M In case you also need to check if string is not empty after trim(): function is_empty($item) { return (empty($item) && !is_numeric($item)) || (is_string($item) && trim($item) === ''); } https://3v4l.org/UeF6F Note the parentheses are not necessary but I like to keep them for readability and to avoid potential errors due to operator precedence. If you're using PHP 7+, don't forget to add return typehint: function is_empty($item): bool And on PHP 8 you can add mixed argument typehint: function is_empty(mixed $item): bool
{ "domain": "codereview.stackexchange", "id": 42615, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php", "url": null }
c#, algorithm, .net, deque Title: Deque class for .Net (C#) Question: As .Net has no Deque class (Double-Ended Queue) in the Frameworks and I couldn't find an example implementation that I was happy with, I have written the following with the intent that I may post it as a canonical implementation. First the interface definition: /// <summary> /// Standard interface for a Double-Ended Queue (Deque) /// </summary> /// <remarks> /// The first six methods below (PushFront/Back, PopFront/Back and /// PeekFront/Back) represent the standard deque operations found in /// virtually every canonical and official language implementation /// (see: https://en.wikipedia.org/wiki/Double-ended_queue#Operations) /// of a DEQUE class. /// /// Unfortunately, there is no standard when it comes to the names of /// these operations, so I have chosen to use the names from the C++ Deque /// class template (https://www.cplusplus.com/reference/deque/deque/), /// but with standard .Net name styling . /// /// The Count and IsEmpty properties are logical additions to these, /// and reasonable to add as they have very low overhead in all /// implementations. /// </remarks> public interface IDeque<T> { /// <summary> Add a new element to the front of the queue. </summary> /// <param name="V"> The item to add to the queue</param> void PushFront(T V); /// <summary> Add a new element to the back of the queue. </summary> /// <param name="V"> The item to add to the queue</param> void PushBack(T V); /// <summary> Removes and returns the element at the front of the queue. </summary> /// <exception cref="InvalidOperationException">Thrown if Pop is called when the Deque is empty.</exception> T PopFront(); /// <summary> Removes and returns the element at the back of the queue. </summary> /// <exception cref="InvalidOperationException">Thrown if Pop is called when the Deque is empty.</exception> T PopBack();
{ "domain": "codereview.stackexchange", "id": 42616, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, algorithm, .net, deque", "url": null }
c#, algorithm, .net, deque /// <summary> Returns the element at the front of the queue without removing it. /// If the Deque is empty, the default for the type "T" is returned. </returns> T PeekFront { get; } /// <summary> Returns the element at the front of the queue without removing it. /// If the Deque is empty, the default for the type "T" is returned. </returns> T PeekBack { get; } /// <summary> Gets the number of elements in the queue. </summary> int Count { get; } /// <summary> True if there are no elements in the queue, false otherwise. </summary> bool IsEmpty { get; } }
{ "domain": "codereview.stackexchange", "id": 42616, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, algorithm, .net, deque", "url": null }
c#, algorithm, .net, deque And the class implementation: /// <summary> /// Fast implementation of IDeque, using a dynamically resizeable circular buffer (array) /// </summary> /// <inheritdoc cref="IDeque{T}"/> /// <remarks> /// This implements a Deque (Double-Ended Queue, see /// https://en.wikipedia.org/wiki/Double-ended_queue) in what I believe /// is the most efficient way (for a .Net managed language). The obvious /// way would be using a doubly-linked list (LinkedList{T}), but these /// are variously attested to be slow/inefficient in .Net compared to /// the List and Array classes, primarily because of locality and /// sequential access issues. /// /// The recommended approach is one of several different ways of using /// arrays: /// 1) Using a dynamic array with resizeable upper and lower bounds. Or /// 2) Storing contents in a circular buffer, with the Deque as a /// windowed range into the buffer. /// /// Approach (1) is technically possible using the special Array class, /// or more complexly with one or more List objects, but neither of these /// is as efficient as a language-native typed array and both involve /// boxing overhead and null-conversion issues if {T} is a value-type. /// /// This left approach (2), which I have never seen implemented for a /// Deque in a .Net managed language (C# or VB.net). I've also never seen /// a good type-generic implementation for .Net, which is what prompted /// me to write this class. /// </remarks> public class Deque<T> : IDeque<T> { #region Constructors public Deque(int InitialAllocation = 16) { size_ = InitialAllocation; buffer_ = new T[size_]; front_ = 0; back_ = decrement(front_);
{ "domain": "codereview.stackexchange", "id": 42616, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, algorithm, .net, deque", "url": null }
c#, algorithm, .net, deque front_ = 0; back_ = decrement(front_); empty_T = (new T[1])[0]; // Trick to get the default uninitialized //value for type <T>, without any boxing //or null-conversion issues. } #endregion #region IDeque Properties public T PeekFront { get { return buffer_[front_]; } } public T PeekBack { get { return buffer_[back_]; } } public int Count { get; protected set; } public bool IsEmpty => (Count == 0); #endregion #region IDeque Methods public T PopBack() { if (IsEmpty) throw new InvalidOperationException("Cannot Pop from empty Deque!"); T val = buffer_[back_]; // save the value buffer_[back_] = empty_T; // erase the cell back_ = decrement(back_); // move the array window Count--; // adjust the count return val; } public T PopFront() { if (IsEmpty) throw new InvalidOperationException("Cannot Pop from empty Deque!"); T val = buffer_[front_]; // save the value buffer_[front_] = empty_T; // erase the cell front_ = increment(front_); // move the array window Count--; // adjust the count return val; } public void PushBack(T V) { if (IsFull) expandBuffer(); back_ = increment(back_); buffer_[back_] = V; Count++; } public void PushFront(T V) { if (IsFull) expandBuffer(); front_ = decrement(front_); buffer_[front_] = V; Count++; } #endregion
{ "domain": "codereview.stackexchange", "id": 42616, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, algorithm, .net, deque", "url": null }
c#, algorithm, .net, deque #region Local Properties and Fields protected T[] buffer_; // holds the array window protected int size_; // allocation size of buffer protected int back_; // back is the tail or LEADING end protected int front_; // front is the head or TRAILING end protected T empty_T; // what should be in an uninitialized cell protected int RemainingAllocation => size_ - Count; /// <summary> True if there are no empty cells left in the buffer, false otherwise. </summary> protected bool IsFull => (RemainingAllocation <= 0); //protected bool IsFull => ((front_ == back_ + 1) || (front_ == 0 && back_ == size_ - 1)); #endregion #region Buffer Methods (local) /// <summary> returns the next cell's index in the circular buffer. </summary> protected int increment(int index) => index == size_ - 1 ? 0 : index+1; /// <summary> returns the preceding cell's index in the circular buffer. </summary> protected int decrement(int index) => index == 0 ? size_ - 1 : index-1; /// <summary> /// Double the size of the current buffer, without losing any contents /// </summary> /// <remarks> /// Makes a new buffer twice a large as the current one. Then copies /// the contents of the old buffer to the new one, then makes the new /// buffer the current ("buffer_"). /// </remarks> void expandBuffer() { // allocate the new buffer int newSize = size_ * 2; T[] newBuf = new T[newSize]; // copy the data over if (!IsEmpty) { // if the pointers are in-order, then all contents can // be copied to the same indexes in the new buffer if (front_ <= back_) { for (int i = front_; i <= back_; i++) { newBuf[i] = buffer_[i]; } }
{ "domain": "codereview.stackexchange", "id": 42616, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, algorithm, .net, deque", "url": null }
c#, algorithm, .net, deque // The contents are wrapped-around the circular buffer so // reposition the back (wrapped-around) contents to after // the front contents. else { // The front cells can be copied to the same indexes in the // new buffer. for (int i = front_; i < size_; i++) { newBuf[i] = buffer_[i]; } // The back cells are wrapped-around, so reposition them to // follow immediately after the front cells. for (int i = 0; i <= back_; i++) { newBuf[i + size_] = buffer_[i]; } } } // reposition the back_ pointer so it's not wrapped-around if (back_ < front_) back_ += size_; // save the new buffer buffer_ = newBuf; size_ = newSize; } #endregion } I would appreciate any feedback or reviews on how to improve this code, with an eye towards my possibly posting in StackOverflow as a canonical solution. Answer: First of all congratulation. It seems like a neat solution (I haven't played with it, I've just read it) The public API is using consistent naming The public methods are well documented The public methods implementation are short and concise Now let's talk about the improvement areas Naming In C# we normally use camel Casing for parameter names. But if you prefer Pascal Casing it is really up to you but please be consistent: public Deque(int InitialAllocation = 16) protected int increment(int index) In C# we normally use Pascal Casing for method names. Yet again, please try be consistent in naming: public T PopBack() protected int decrement(int index) In C# we normally use camel Casing for non-public member names. Please try be consistent: protected T empty_T; protected int RemainingAllocation => size_ - Count;
{ "domain": "codereview.stackexchange", "id": 42616, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, algorithm, .net, deque", "url": null }
c#, algorithm, .net, deque protected T empty_T; protected int RemainingAllocation => size_ - Count; Quite frankly I don't understand how do you determine when to use an underscore as suffix and when don't protected int front_; protected T empty_T; So in general: Use Pascal Casing for all class members except the private fields Use camel Casing for local variables and method parameters, as well as private fields Some people prefer to prefix private fields with an underscore _ Expand Buffer I would recommend to consider to use ArrayPool to rent and return arrays for a specify size rather than manually allocate them when needed newBuf: As I can see this is the only place in your code where you have used abbreviation. I assume it was just a typo and you wanted to write newBuffer Abusing the #region If you really want to separate things from each other then I would recommend to use partial classes A typical separation is that you have a file where there are only the public members and you have another one where you have all non-public ones Deque.cs Deque.nonpublic.cs or Deque.impl.cs UPDATE #1: Reflect to OP's questions Are you saying that the protected members would be styled the same as the public members? My habit has been to use PascalCase for all public members and camelCase for all local and protected members.
{ "domain": "codereview.stackexchange", "id": 42616, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, algorithm, .net, deque", "url": null }
c#, algorithm, .net, deque If you look at the MSDN documentation regarding C# Coding conventions then you can find the following paragraph: any of the guidance pertaining to elements marked public is also applicable when working with protected and protected internal elements, all of which are intended to be visible to external callers As always it is just a guidance and you can freely take a different path. But if you want to make this code open source for example then most of the developers will be familiar with the above naming convention. If you don't want to make it publicly available then you should follow your organization standards. There might be a group of static code analyzer rules that dictates the naming, indentation and other code formatting policies. I think that we have a philosophical difference on the use of Regions vs Partial classes, but I am happy to remove the #reqion markers for public posting as I know that many (most?) programmers dislike them. Even though most of the time partial classes are used for generated code there are other uses cases as well. We have used them heavily during unit testing. With that the helper methods for initializations, assertions were separated from the test cases. We have also found regions can be really villainous / scurvy. When you collapse the regions you do not realize how big is your class. By separating your class into multiple files it can help you later on to do proper separation, whereas region has different intent. But yet again it is up to you how to separate your code.
{ "domain": "codereview.stackexchange", "id": 42616, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, algorithm, .net, deque", "url": null }
python, game, connect-four Title: Four-in-a-Row game Question: I've made a working Four-in-a-Row game with grid lists and winning system. Both vertically and diagonally, is there some clear improvements to be made or common mistakes which could perhaps shorten it down? Is there any bad code or stupid logic which needs improving? I haven't gotten to making the diagonal victory but have kept a few ideas in mind. Tips here would also be appreciated. import os gw = False
{ "domain": "codereview.stackexchange", "id": 42617, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, game, connect-four", "url": null }
python, game, connect-four def cls(): os.system('cls') #Check vertical 4 in a row. def check_ver(): for row in range(6): xCounter = 0 for col in range(5): if (grid[col][row] == "X"): xCounter += 1 if xCounter == 4: xw() for row in range(6): oCounter = 0 for col in range(5): if (grid[col][row] == "O"): oCounter += 1 if oCounter == 4: ow() #Check horizontal 4 in a row. def check_hor(): for col in range(5): xCounter = 0 for row in range(6): if (grid[col][row] == "X"): xCounter += 1 if xCounter == 4: xw() for col in range(5): oCounter = 0 for row in range(6): if (grid[col][row] == "O"): oCounter += 1 if oCounter == 4: xw() #Checks all def check_all(): check_ver() check_hor() #Checks for win, prints the game def p(): cls() check_all() for x in range(5): print(*grid[x], sep=" | ") for x in range(2): print(*info[x], sep=" | ") #Empty prints for victory message def em(): for x in range(3): print("") #Victory message and stuff for O def ow(): cls() em() print("O, Wins!".center(16)) em() gw = True #Victory message and stuff for X def xw(): cls() em() print("X, Wins!".center(16)) em() gw = True #Grid system grid = [['.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']] info = [['==+===+===+===+===+=='], ['1', '2', '3', '4', '5', '6']] #Game while True: if gw == True: break else: p() row = int(input("X, column: ")) row -= 1 if 0 > row or row > 6: continue else: for x in range(4, -1, -1):
{ "domain": "codereview.stackexchange", "id": 42617, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, game, connect-four", "url": null }
python, game, connect-four continue else: for x in range(4, -1, -1): if grid[x][row] == '.': grid[x][row] = 'X' break p() row = int(input("O, column: ")) row -= 1 if 0 > row or row > 6: continue else: for x in range(4, -1, -1): if grid[x][row] == '.': grid[x][row] = 'O' break
{ "domain": "codereview.stackexchange", "id": 42617, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, game, connect-four", "url": null }
python, game, connect-four Answer: Stop repeating yourself. You have a lot of repetitive code. A function to check for horizontal win and a similar one for vertical win. Within each of those functions, nearly identical blocks of code for X and then for O. And within the main while-true loop, nearly identical blocks of code to get input for player X and player O. None of that repetition is needed, some of it causes bugs (eg, when X wins the program still asks for more input from O), and you'll probably get good advice from others for eliminating a lot of it. I'm going to focus on one topic: checking for wins. Checking one row is easy. In these two-dimenional grid situations, rows are typically the easy part, because the grid is naturally organized row by row. So let's start with a simple function to determine whether there is a win in a single row. We can use itertools.groupby to organize the row into each player's contiguous sequences of cells. Then we just find the longest sequence and return the player of that sequence, provided that it is long enough: from itertools import groupby def collect_runs(row): # Takes a row. Yields all contiguous non-None sequences. for player, cells in groupby(row): if player: yield list(cells) def check_row_win(row, win_size = 4): # Takes a row. Returns player of a winning run. runs = sorted(collect_runs(row), key = len) if not runs: return None long_run = runs[-1] player = long_run[0] return player if len(long_run) >= win_size else None Checking all rows is also easy. With those building blocks in place, we can check for horizontal wins by either player in one function -- in other words, no need to repeat ourselves: def check_horizontal_wins(grid): for row in grid: winner = check_row_win(row) if winner: return winner return None
{ "domain": "codereview.stackexchange", "id": 42617, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, game, connect-four", "url": null }
python, game, connect-four Use transpose to convert rows to columns. Transposing a grid is easy in Python. If we take our original grid and transpose it, we can use the same row-checking logic to check for both horizontal and vertical wins: def transpose(grid): return [list(tup) for tup in zip(*grid)] def check_wins(grid): # Now it handles horizontal and vertical. for row in grid + transpose(grid): winner = check_row_win(row) if winner: return winner return None Use the same mindset to handle diagonal wins. We've had good luck so far by using a simple strategy: rather than repeating code or writing complex logic for every case, we applied a fairly simple data transformation to re-use some basic win-checking logic. With a little experimentation we can figure out a way to convert diagonals to rows. For lack of a better term, I'll call the transformation we need a grid shift: # Consider a forward-diagonal win. . . . x . . . x . . . x . . . x . . . . # A grid shift converts the diagonal to vertical, which we can handle. # The process will include padding to fill in the empty quadrants. . . . x . . . x . . . x . . . x . . . . # Now consider a backward-diagonal win. . o . . . . . o . . . . . o . . . . . o # Reverse the rows and it becomes a forward-diagonal, which we can handle. . . . . o . . . o . . . o . . . o . . . Just use row-checking logic for everything. Here is one way to implement the shift transformation, along with the resulting function that can check for all types of wins: def shift(grid): return [ padding(r) + row + padding(len(row) - r - 1) for r, row in enumerate(grid) ] def padding(n): return [None for _ in range(n)]
{ "domain": "codereview.stackexchange", "id": 42617, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, game, connect-four", "url": null }
python, game, connect-four def padding(n): return [None for _ in range(n)] def check_wins(grid): all_rows = ( grid + # Horizontal transpose(grid) + # Vertical transpose(shift(grid)) + # Forward diagonal transpose(shift(reversed(grid))) # Backward diagonal ) for row in all_rows: winner = check_row_win(row) if winner: return winner return None
{ "domain": "codereview.stackexchange", "id": 42617, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, game, connect-four", "url": null }
c++, multithreading, thread-safety, queue, producer-consumer Title: Type-agnostic abortion condition in Producer-Consumer model queue Question: This is a follow-up post to the topic discussed here. Description I am trying to implement a robust, multi-threaded producer-consumer model with a single producer in the main thread and several consumers in other threads. After researching the topic, I also added a copy constructor and an assignment operator (or better, deleted it), to satisfy the rule of three. I did so, as being able to copy a thread managing class instance does not make sense. The operating mode is the same as before, e.g. the generator thread loops over data, recognizes through some condition which sort of data it is dealing with, and proceeds to delegate the sample to the respective worker thread (via pushBack(data)). When reaching the end of the source data, it queues a special value to the worker threads and waits for them to finish. Afterwards, it cleans up and exits. The queue implementation (found here) provides a blocking dequeue function, e.g. no polling is necessary. The downside is that the consumers do not necessarily register that the main thread has set m_running (a flag indicating if execution should be stopped) because they are stuck waiting. As mentioned before, this can be bypassed by queueing a special value. In the provided example, I quietly assume that the queue only manages pointer types (e.g. int*). In that case, the special value was determined to be nullptr. Credit goes to @G.Sliepen, who provided many suggestions in the previous topic. Code #include <chrono> #include <iostream> #include <thread> #include <functional> #include "readerwriterqueue.h" template<typename T> class Consumer { public: Consumer(int id, std::function<void(int, T&)> func) : m_id(id), m_func(func) {} ~Consumer(){ m_running = false; this->pushBack(nullptr); m_thread.join(); }
{ "domain": "codereview.stackexchange", "id": 42618, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, multithreading, thread-safety, queue, producer-consumer", "url": null }
c++, multithreading, thread-safety, queue, producer-consumer Consumer(const Consumer&) = delete; Consumer& operator=(const Consumer&) = delete; Consumer() : m_id(0) {}; void pushBack(const T& t){ m_BufferQueue.enqueue(t); } private: void work() { m_running = true; while(m_running || m_BufferQueue.peek()) { T t; m_BufferQueue.wait_dequeue(t); if (t == nullptr) break; m_func(m_id, t); } std::cout << "EXIT thread " << m_id << std::endl; } int m_id; std::function<void(int, T&)> m_func; moodycamel::BlockingReaderWriterQueue<T> m_BufferQueue{64}; std::thread m_thread{&Consumer::work, this}; std::atomic_bool m_running; }; int main() { auto func = [](int id, int* val){ std::cout << "Thread " << id << " received value " << *val << std::endl; delete val; }; Consumer<int*> c1(1, func); Consumer<int*> c2(2, func); // data generator for(int i = 0; i < 10; i++) { int* val = new int(i); if (i % 2 == 0) c1.pushBack(val); else c2.pushBack(val); } std::cout << "EXIT" << std::endl; return 0; } Question This implementation breaks when using a non-pointer datatype in the template. As far as I know, references always have to reference non-null objects, so checking for "null-references" does not make sense. And checking for every possible type seems to be very error-prone. I thought of adding a parametrized member variable that holds the abortion value, but I am not sure if this is the best way of doing it. In short: is there an elegant way to define an abortion value that is type-agnostic?
{ "domain": "codereview.stackexchange", "id": 42618, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, multithreading, thread-safety, queue, producer-consumer", "url": null }
c++, multithreading, thread-safety, queue, producer-consumer Answer: Avoid having T be a pointer I strongly recommend avoiding template parameters be pointers, instead let them be value types. You can easily turn them into pointers where needed. First of all, it is not very idiomatic to pass pointers as template arguments to container-like types, and a Consumer is just a container (the queue) and an associated thread. So as a user of your class, my first instinct would be to write: Consumer<int> c1(1, func); But this would fail to compile. Also consider that if you leave it up to the user to pass the pointer type, they could try to do something like: Consumer<const int*> c1(1, func); What would the semantics of that be? Another issue is that bad things will happen is a caller does something like: c1.pushBack(nullptr); c1.pushBack(new int(42)); The first call to pushBack() will cause the worker to stop processing the queue any further, which means the second call will have caused a memory leak. Of course it is unlikely that someone would intentionally push a nullptr, but consider that you might have code that looks like: c1.pushBack(get_the_thing(...)); Where the function you are calling might sometimes return a nullptr. This would lead to hard to debug problems. Finally, this design encourages the use of raw calls to new and delete, which should be avoided: Let the Consumer manage the lifetime of queue items In the previous version of your code, a Consumer took care of managing storage for the items in the queue. You can still do that, and avoid raw pointers, by having the queue store items of type std::unique_ptr<T>. And you can still have an empty std::unique_ptr, which you can use as a signal that the worker should stop: template<typename T> class Consumer { public: ... ~Consumer() { ... m_BufferQueue.enqueue(nullptr); ... } ... void pushBack(const T& t) { m_BufferQueue.enqueue(std::make_unique<T>(t)); }
{ "domain": "codereview.stackexchange", "id": 42618, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, multithreading, thread-safety, queue, producer-consumer", "url": null }
c++, multithreading, thread-safety, queue, producer-consumer private: void work() { ... while(...) { std::unique_ptr<T> ptr; m_BufferQueue.wait_dequeue(ptr); if (!ptr) break; m_func(m_id, *ptr); } ... } ... moodycamel::BlockingReaderWriterQueue<std::unique_ptr<T>> m_BufferQueue{64}; ... };
{ "domain": "codereview.stackexchange", "id": 42618, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, multithreading, thread-safety, queue, producer-consumer", "url": null }
c++, multithreading, thread-safety, queue, producer-consumer The drawback of using pointers, whether raw or smart ones, is that memory is allocated for every element you push to the queue, which is not great for performance. Alternatively, consider using std::optional<T> instead. You can use it as a drop-in replacement for std::unique_ptr<T> in the above code. Consider adding an emplaceBack() function as well Just like STL containers have a push_back() and emplace_back(), consider adding the latter as well. This avoids first having to construct an object of type T, which then has to be move- or copy-constructed into the queue. Of course, this requires your BlockingReaderWriterQueue() to also have an emplace() function. Having an emplace-like function is especially important if you want to be able to add uncopyable and unmovable object to the queue. m_running is no longer necessary Since you guarantee that a special value will always be pushed to the queue when the destructor of Consumer is running, you don't need m_running at all. You can safely remove it. Note that setting m_running to true at the start of the worker thread is also a bit dangerous; consider that a Consumer object might be destroyed immediately after it was created, then a race condition could happen between the m_running = false in the destructor and m_running = true in work(). Alternative solutions
{ "domain": "codereview.stackexchange", "id": 42618, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, multithreading, thread-safety, queue, producer-consumer", "url": null }
c++, multithreading, thread-safety, queue, producer-consumer Alternative solutions All approaches with pointers or optionals have the drawback that they increase the amount of storage necessary for every element in the queue. For very large queues with small elements that might be an issue. The only thing you want to know is whether you should break out of the loop in work() or not, and ideally just a single (atomic) boolean would be necessary, like m_running. But the problem is ensuring work() gets woken up if it's waiting on an empty queue. You could instead push this problem down to BlockingReadeWriterQueue, so that you signal the queue itself that it should terminate, and then wait_dequeue() should return false once the queue is terminated and no items are left. Your Consumer could then just do: ~Consumer() { m_BUfferQueue.terminate(); m_thread.join(); }
{ "domain": "codereview.stackexchange", "id": 42618, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, multithreading, thread-safety, queue, producer-consumer", "url": null }
c++, multithreading, thread-safety, queue, producer-consumer void work() { for (T t; m_BufferQueue.wait_dequeue(t);) m_func(m_id, t); }
{ "domain": "codereview.stackexchange", "id": 42618, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, multithreading, thread-safety, queue, producer-consumer", "url": null }
c++, random Title: Optimal random integer function Question: What I have Header file: int randomInt(int start, int end); Implementation file: int randomInt(int start, int end) { static std::random_device rd; // Obtain a random number from hardware static std::mt19937 eng(rd());// Seed the generator std::uniform_int_distribution<> dist(start, end); return dist(eng); } What I want to do Would it be optimal to make this function inline or anything else? If so, how would I deal with the static variables? Answer: Putting the ideas of your code and the remarks from @JDługosz. He's right about not wanting to recreate the distribution over and over again, that needs to be initialized only once to guarantee a good distribution, and this example also avoids calling the threadsafety blocks for statics by initializing a reference to the engine in the constructor. All in all it will look like this : // header file #include <random> namespace random { auto& get_engine() { static std::random_device rd; static std::mt19937 eng{ rd() }; return eng; } template<typename type_t> struct generator_t { generator_t(const type_t& start, const type_t& end) : m_distribution{ start,end }, m_engine{ random::get_engine() } // initialize reference to engine from static (performance optimization) { } inline type_t operator()() { return m_distribution(m_engine); } private: std::uniform_int_distribution<type_t> m_distribution; std::mt19937& m_engine; }; } // main file starts here : #include <iostream> int main() { random::generator_t<int> random_generator(1,10); for (std::size_t n = 0; n < 20; ++n) { auto value = random_generator(); std::cout << value << "\n"; } return 0; }
{ "domain": "codereview.stackexchange", "id": 42619, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, random", "url": null }
python, python-3.x Title: Prints matrix with different random numbers in each column Question: I wanna learn how to make my code more Pythonic, I'm still a newb. Advises on classes and functions I could've used are welcomed. import random as r n = 7 #This number defines the size of the square matrix def print_mat(mat): """ This function will be used to display the matrix """ for row in range(len(mat)): for line in range(len(mat[0])): print(mat[row][line],end="\t") print("\n") def is_used(test_num): """ This function tests if the argument has already been used in the column of the matrix thanks to the array already_used """ for used_num in already_used: if test_num == used_num: return True return False A = [[0]*n for _ in range(n)] #Creates matrix of size n*n for row in range(n): """ Will loop n times for each column of the matrix The array bellow will allow to sort out already used random numbers """ already_used = [0 for _ in range(n)] for line in range(n): """ Will loop n times for each line of the matrix """ rand_num = r.randint(1,n) #Generate random number between [1;n] while is_used(rand_num) == True: rand_num = r.randint(1,n) """ Will loop until rand_num is a num that hasn't been used """ A[line][row] = rand_num #Assignes the available rand_num to the matrix already_used[line] = rand_num print("\nMatrice A = ") print_mat(A) #Prints the matrix using the function defined above One previous output : Matrice A = 6 4 7 4 6 5 6 3 1 6 5 1 4 2 4 3 2 3 2 1 4 2 2 1 7 3 6 5 1 5 4 2 4 7 1 5 6 5 1 5 2 3 7 7 3 6 7 3 7 Thanks a lot <3
{ "domain": "codereview.stackexchange", "id": 42620, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x 7 7 3 6 7 3 7 Thanks a lot <3 Answer: As far as I understand, your objective is to create and print a square matrix, where each column must have unique values. If that is the case, and considering you are already using random module, it is better to use random.shuffle or random.sample. Now random.shuffle modifies a list in place, so that can create reference issues, and to avoid that we will need to create a copy anyways, so random.sample would be more suitable in this case. If you use random.sample there is no need to check whether a value has already been used while filling a cell, we can assign one row at a time. Furthermore, there is no need to build an empty matrix at all, we can directly create a matrix with random columns using zip. So first approach could be something like this: import random def generate_col(allowed_nums, length): """ This function will generate col of provided `length` with random ordering out of `allowed_nums`. """ return random.sample(allowed_nums, length) def print_matrix(mat): """ This function will be used to display the matrix """ for row in mat: print(*row, sep='\t', end=2*'\n') def build_matrix(n): """ Creates a square matrix of size n. """ allowed_nums = range(1, n+1) all_cols = [generate_col(allowed_nums, n) for _ in range(n)] return list(zip(*all_cols)) if __name__ == '__main__': n = 7 #This number defines the size of the square matrix A = build_matrix(n) print("\nMatrice A = ") print_matrix(A) #Prints the matrix using the function defined above  If you plan to work with multiple matrices, you can consider making a class. That would hide implementation details, and make the usage much cleaner: import random
{ "domain": "codereview.stackexchange", "id": 42620, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x class RandomSquareMatrix: ''' nxn Square Matrix filled with unique random numbers in range (1, n] in each column. ''' def __init__(self, n): self.n = n self.allowed_vals = range(1, n+1) self.matrix = self.build_matrix() def build_matrix(self): """ This function will generate col of provided `length` with random ordering out of `allowed_nums`. """ all_cols = [self.generate_col() for _ in range(self.n)] return list(zip(*all_cols)) def generate_col(self): return random.sample(self.allowed_vals, self.n) def __str__(self): """ This function will be used to display the matrix when it is printed """ row_sep = 2 * '\n' col_sep = '\t' return row_sep.join( [col_sep.join(map(str, row)) for row in self.matrix] ) def __repr__(self): """ This function will be used to display the matrix information. Example: >>> RandomSquareMatrix(3) <RandomSquareMatrix: 3x3> """ cls_name = type(self).__name__ if __name__ == '__main__': B = RandomSquareMatrix(7) print('Matrice B =') print(B) NOTE: I think, in this case, it is better to import random and use random.sample, instead of from random import sample. Because you are using it only in one place, shouldn't be that hard to write it once, also random.sample is more clear in my view. ```
{ "domain": "codereview.stackexchange", "id": 42620, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, programming-challenge, python-3.x, chess Title: Python Amazon Checkmate Question: Found this challenge on CodeFights and would love a review of my style. Description An amazon (also known as a queen+knight compound) is an imaginary chess piece that can move like a queen or a knight (or, equivalently, like a rook, bishop, or knight). The diagram below shows all squares which the amazon attacks from e4 (circles represent knight-like moves while crosses correspond to queen-like moves). Recently you've come across a diagram with only three pieces left on the board: a white amazon, white king and black king. It's black's move. You don't have time to determine whether the game is over or not, but you'd like to figure it out in your head. Unfortunately, the diagram is smudged and you can't see the position of the black's king, so it looks like you'll have to check them all. Given the positions of white pieces on a standard chessboard, determine the number of possible black king's positions such that: it's checkmate (i.e. black's king is under amazon's attack and it cannot make a valid move); it's check (i.e. black's king is under amazon's attack but it can reach a safe square in one move); it's stalemate (i.e. black's king is on a safe square but it cannot make a valid move); black's king is on a safe square and it can make a valid move. Note that two kings cannot be placed on two adjacent squares (including two diagonally adjacent ones). Example For king = "d3" and amazon = "e4", the output should be amazonCheckmate(king, amazon) = [5, 21, 0, 29]. Code def amazonCheckmate(king, amazon): # is in range of n for a and b def squared_range(a, b, n): return (a[0] >= b[0] -n and a[0] <= b[0] + n and a[1] >= b[1]-n and a[1] <= b[1] + n)
{ "domain": "codereview.stackexchange", "id": 42621, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, python-3.x, chess", "url": null }
python, programming-challenge, python-3.x, chess # if any square +1 // -1 for y and x are not under check ==> King escapes def no_valid_moves(a, b): if(a!=1): if([a-1,b] in notUnderCheck): return False if(b!=1): if([a-1,b-1] in notUnderCheck): return False if(b!=8): if([a-1,b+1] in notUnderCheck): return False if(a!=8): if([a+1,b] in notUnderCheck): return False if(b!=1): if([a+1,b-1] in notUnderCheck): return False if(b!=8): if([a+1,b+1] in notUnderCheck): return False if(b!=8): if([a,b+1] in notUnderCheck): return False if(b!=1): if([a,b-1] in notUnderCheck): return False return True # declaring variables result = [0, 0, 0, 0] letters = ['','a','b','c','d','e','f','g','h'] notUnderCheck = [] underCheck = [] k_file = letters.index(king[0]) k_col = int(king[1]) a_file = letters.index(amazon[0]) a_col = int(amazon[1]) k = [k_file, k_col] q = [a_file, a_col] # if king defends queen the square where queens stand is undercheck else not under check if(squared_range(k, q, 1)): underCheck.append(q) else: notUnderCheck.append(q) # a grid 8x8 check which squares are under check and which are not for x in range(1, 9): for y in range(1, 9): # Squares to excldue are defended by King or postion of Amazon if(not squared_range([x,y], k, 1) and not [x,y] == q): # if in deadly square of queen 5x5 # if(squared_range([x,y],q, 2)): underCheck.append([x,y])
{ "domain": "codereview.stackexchange", "id": 42621, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, python-3.x, chess", "url": null }
python, programming-challenge, python-3.x, chess # Check if on the same file and not if king is in between elif (x == a_file): if(not (k_file == a_file and (y > k_col > a_col or y < k_col < a_col))): underCheck.append([x,y]) # Check if on the same column and not if king in between elif( y == a_col): if(not (k_col == a_col and ( x > k_file > a_file or x < k_file < a_file))): underCheck.append([x,y]) # Check diagonal and not if king in between # Black_King on Diagonaal van Queen elif(abs(x - a_file) == abs(y - a_col)): if( not(abs(k_file - a_file) == abs(k_col - a_col) and ( ( x < k_file < a_file and y < k_col < a_col) or (x < k_file < a_file and y > k_col > a_col) or (x > k_file > a_file and y < k_col < a_col) or (x > k_file > a_file and y < k_col < a_col) ) ) ): underCheck.append([x,y]) else: notUnderCheck.append([x, y]) # Add the squares where to White_King stands to checksquares elif(squared_range([x,y], k, 1)): underCheck.append([x,y])
{ "domain": "codereview.stackexchange", "id": 42621, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, python-3.x, chess", "url": null }
python, programming-challenge, python-3.x, chess # for each cell in grid check surounding cells strengths update result accordingly for x in range(1, 9): for y in range(1, 9): # Exclude q and kings range if(not squared_range([x,y], k, 1) and not [x,y] == q): # if current square under Check if([x, y] in underCheck): # if no possible moves result[0]++ # else result[1]++ if(no_valid_moves(x, y)): print("Checkmate at: [" + str(x) + ", " + str(y) + "]") result[0] += 1 else: print("Check at: [" + str(x) + ", " + str(y) + "]") result[1] += 1 else: # if no possible moves result[2]++ # else result[3]++ if(no_valid_moves(x, y)): print("Stuck at: [" + str(x) + ", " + str(y) + "]") result[2] += 1 else: print("Safe at: [" + str(x) + ", " + str(y) + "]") result[3] += 1 return result Question no_valid_moves looks clunky as hell! How can this be made beautifull again? Is my general logic ok, or should I have divided the problem in easier to comprehend functions? Any stylistic review is welcome too. Answer: Clunky methods can be the result of awkward setups. In your case, yes, you should have divided the problem up in smaller chunks. Your algorithm is so tightly bound to the current problem that it'd be extremely hard to adapt it later on, say, should you need to add another piece in the equation, and it's likely your logic has bugs (it does) because it's tough to cover all corner cases when you have to explicitly check all cases, instead of allowing them to emerge as a consequence of combining the solution to smaller problems.
{ "domain": "codereview.stackexchange", "id": 42621, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, python-3.x, chess", "url": null }
python, programming-challenge, python-3.x, chess Your problem can be broken down as: find all the squares under attack by the white pieces generate all valid black king squares for each square make two checks: is the black king under attack and does he have any safe squares to run to? 1. Can be further broken down to generating the attacking squares for each white piece individually and taking their union at the end. For example, generating the squares a king can move into contributes to all 3 steps above. For step 2 it is by figuring out which square placements are not valid for the black king, since he can't start at any squares the white king can move into. In terms of movements, there are two types of pieces we are concerned with. Ray-like pieces, i.e., bishops and rooks, can move outwards in various directions, but their movement can be blocked if another piece is in their path. And we also have occupying pieces, i.e., king and knight, which can influence certain squares regardless of any piece arrangement. To generate the amazon moves, I would write rules for a bishop, rook and knight individually. Then, the first two would have to be filtered depending on whether the white king is in the amazon's way. In terms of stylistic comments
{ "domain": "codereview.stackexchange", "id": 42621, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, python-3.x, chess", "url": null }
python, programming-challenge, python-3.x, chess In terms of stylistic comments write your functions/methods in snake_case. CamelCase should be reserved for classes only. Don't exceed 80 characters per line. Use docstrings to describe what a function does or how to use it. Comments aren't meant for this. Avoid using comments to describe what the code does when it's trivial. The code should ideally explain itself and comments should be reserved for why you did something the way you did. Or if you're using a complex algorithm, a summary of its implementation. Don't use brackets in statements when it isn't required, e.g., if a in b: is fine, while if (a in b): is visual clutter. Use descriptive names. If the code is complicated, it's hard to keep track what k_col and k represent. Also, the chess terms for rows/columns are rank/file. So, I would have used king_file, king_rank and king_coords. Use str.format() for complicated strings instead of concatenating them together. For example, 'Checkmate at [{}, {}]'.format(x, y). A function that returns a boolean should have a name like is_something, can_do_something, has_something, etc. You hardcode magic numbers, e.g, the size of the board. It's better if you define a constant (all-caps) at the top, so if you ever need to change it, it'll be trivial and error-free. You convert the files a-h to the numbers 1-9, when it's more natural to work with 0-based indices for iterables. letters = ['','a','b','c','d','e','f','g','h'] is an obvious hack, trying to fight against what is most convenient. You should consider validating the inputs, because nothing prevents someone from feeding in 'j9', or other garbage. Or that the king's and amazon's positions don't overlap. Overall, here is how I would have tackled it. import itertools from string import ascii_lowercase as files SIZE = 8 squares = tuple(''.join(square[::-1]) for square in itertools.product(map(str, range(1, SIZE+1)), files[:SIZE])) coords = tuple(itertools.product(range(SIZE), range(SIZE)))
{ "domain": "codereview.stackexchange", "id": 42621, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, python-3.x, chess", "url": null }
python, programming-challenge, python-3.x, chess def is_in_bounds(square): return 0 <= square < SIZE def king_moves(rank, file): moves = [] if rank - 1 >= 0: moves += [(rank-1, f) for f in range(file-1, file+2) if is_in_bounds(f)] moves += [(rank, f) for f in (file-1, file+1) if is_in_bounds(f)] if rank + 1 < SIZE: moves += [(rank+1, f) for f in range(file-1, file+2) if is_in_bounds(f)] return moves def rook_moves(rank, file): moves = [[(r, file) for r in range(rank-1, -1, -1)]] moves += [[(r, file) for r in range(rank+1, SIZE)]] moves += [[(rank, f) for f in range(file-1, -1, -1)]] moves += [[(rank, f) for f in range(file+1, SIZE)]] return moves def bishop_moves(rank, file): down = range(-1, -rank-1, -1) up = range(1, SIZE-rank) moves = [[(rank+i, file-i) for i in down if is_in_bounds(file-i)]] moves += [[(rank+i, file+i) for i in down if is_in_bounds(file+i)]] moves += [[(rank+i, file-i) for i in up if is_in_bounds(file-i)]] moves += [[(rank+i, file+i) for i in up if is_in_bounds(file+i)]] return moves def knight_moves(rank, file): offsets = ((-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)) moves = [(rank+x, file+y) for x, y in offsets if is_in_bounds(rank+x) and is_in_bounds(file+y)] return moves def filter_ray_attacks(moves, piece_coords): filtered_moves = [] for direction in moves: if piece_coords in direction: # +1 because it can influence the friendly occupied square direction = direction[:direction.index(piece_coords)+1] filtered_moves += direction return filtered_moves def amazon_moves(rank, file, king): moves = (filter_ray_attacks(rook_moves(rank, file), king) + filter_ray_attacks(bishop_moves(rank, file), king) + knight_moves(rank, file)) return moves
{ "domain": "codereview.stackexchange", "id": 42621, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, python-3.x, chess", "url": null }
python, programming-challenge, python-3.x, chess def has_escape_squares(square, piece_moves, attacks): for move in piece_moves: if move not in attacks: return True return False def solve_amazon_problem(king, amazon): for piece in (king, amazon): if piece not in squares: raise ValueError('{} is not a valid square.'.format(piece)) if king == amazon: raise ValueError('The king and amazon must not occupy the same square.') king = coords[squares.index(king)] amazon = coords[squares.index(amazon)] king_attacks = king_moves(*king) all_attacks = set(king_attacks + amazon_moves(*amazon, king)) black_not_allowed_squares = set([king, amazon] + king_attacks) black_king_positions = (square for square in coords if square not in black_not_allowed_squares) # `result` is 4-item list: # 0 - checkmate # 1 - check # 2 - stalemate # 3 - safe # 0-1 means the king is initially in check and 2-3 not. # Therefore, we define `check_offset` as either 0 or 2. # Between 0 and 1 (or 2 and 3) the difference is whether the king # has any safe moves. This is represented by the `escape_offset`, which # is either 0 or 1. # The final state is then `check_offset + escape_offset`. result = [0] * 4 for square in black_king_positions: black_king_moves = king_moves(*square) check_offset = 2 * (1 - (square in all_attacks)) escape_offset = has_escape_squares( square, black_king_moves, all_attacks) result[check_offset + escape_offset] += 1 return result By the way, for various inputs your code seems to produce incorrect results. For example, for king at 'f7' and amazon at 'e7', your program claims there is a stalemate when the king starts at 'h8', while 'h7' is a safe escape. It's likely you didn't properly calculate that the king blocks the amazon's movements along the 7th rank right from the king.
{ "domain": "codereview.stackexchange", "id": 42621, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, python-3.x, chess", "url": null }
c++, beginner, palindrome Title: Determine if a word is a palindrome Question: I'm a newbie programmer and was given a task to find if the input word is a palindrome or not. Now, I've written the program to the best of my ability but would like to know how it could be improved. Also, enlighten me if there are any errors in my program or any other way to make my program more efficient and easy to read! #include<iostream> using namespace std; int main(){ int a; cin>>a; char word[a]; cin>>word; bool palindrome= false; for(int i=0;i<a;i++) { if(word[i]==word[a-i-1]) { palindrome=true; } else { break; } } if(palindrome) { cout<<"palindrome"; } else { cout<<"not a palindrome"; } } Answer: Here are some observations that may help you improve your code. Don't abuse using namespace std Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid. Use more whitespace to enhance readability of the code Instead of crowding things together like this: if(word[i]==word[a-i-1]) most people find it more easily readable if you use more space: if (word[i] == word[a - i - 1]) Fix the bug ISO C++ forbids the use of a variable length array, which is what you're attempting to create here: char word[a];
{ "domain": "codereview.stackexchange", "id": 42622, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, palindrome", "url": null }
c++, beginner, palindrome It might work in your compiler, but it's not standard. Instead, I'd recommend using std::string. This also allows you to improve the user interface, as per the next suggestion. Think of the user Computers are rather good at counting, so why don't we let the computer count the letters instead of relying on the human to do so? I'd suggest changing the interface to only ask for a string from the user and then having the computer count, if that's necessary. Decompose your program into functions All of the logic here is in main in one chunk of code. It would be better to create a separate is_palindrome() function to separate that from the input and output. Carefully consider your algorithm The algorithm is not wrong in your program, but I think I'd write it a bit differently. Algorithmic efficiency First, we don't really need to check the entire length of the string, since we're checking the beginning and the ending, we really only need to check half. Simplicity/Coherence A clearer way to write this would avoid the use of confusing and error-prone control flow (for with break nested in an if else clause). If this is put inside a function, as suggested above, you could write this: for (size_t i{0}; i < a; ++i ) { if (word[i] != word[a - i - 1]) { return false; } } return true; Start with an obviously correct version It's good to start with an obviously correct version, in my view, rather than seeking to optimize from the start. In this case, we could use some standard library functions to mimic the way we'd describe a palindrome in English: "it is a word that is the same forwards as backwards." bool is_palindrome(const std::string& word) { auto revword{word}; std::reverse(revword.begin(),revword.end()); return word == revword; }
{ "domain": "codereview.stackexchange", "id": 42622, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, palindrome", "url": null }
c++, beginner, palindrome This is not as efficient because it allocates and de-allocates a copy of the input word, but it's very obviously correct, which has a lot of advantages when trying to troubleshoot or re-use a function. Not least, if you ultimately decide you need to write a faster version, you can use the obviously correct version to verify that the faster version is also correct.
{ "domain": "codereview.stackexchange", "id": 42622, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, palindrome", "url": null }
c++, object-oriented, playing-cards Title: UNO card game with AI players Question: I had lost a lot of cards of my UNO deck, and was frustrated, and that's when this idea struck my mind. I chose C++, knowing it would be hard, just to improve my understanding of the language. Proudly, I was able to make a basic functioning UNO game in C++!! UNO is a multiplayer card game, and the objective is to finish your cards as soon as possible. My implemention is very basic, no penalties, nor any house rules. Currently, you can play with any number of bots, and the bots are not very smart, they just play the first card they see playable. I would appreciate any improvements or suggestions on my current implementation, be it performance or readability. Directory structure: UNO++ - card.h - deck.h - player.h - cycle.h - game.h - main.cpp card.h #pragma once #include <string> #include <array> #include <vector> #include <map> namespace UNO { const std::array<std::string, 4> COMMON_COLORS = {"BLUE", "GREEN", "RED", "YELLOW"}; const std::array<std::string, 1> SPECIAL_COLORS = {"BLACK"}; const std::array<std::string, 10> NUMBERS = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}; const std::array<std::string, 3> ACTION_TYPES = {"REVERSE", "SKIP", "2 PLUS"}; const std::array<std::string, 2> WILD_TYPES = {"COLOR CHANGE", "4 PLUS"}; std::map<std::string, std::string> COLOR_MAP = { {"BLUE", "\033[34m"}, {"GREEN", "\033[32m"}, {"RED", "\033[31m"}, {"YELLOW", "\033[93m"}, {"BLACK", "\033[30m"}, }; const std::string RESET_COLOR = "\033[0m"; class Card { public: std::string color; std::string type; Card(): color{"BLUE"}, type{"0"}{}; Card(std::string color_, std::string type_): color{color_}, type{type_}{};
{ "domain": "codereview.stackexchange", "id": 42623, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, playing-cards", "url": null }
c++, object-oriented, playing-cards operator std::string() const { return COLOR_MAP[color] + type + RESET_COLOR; } friend std::ostream& operator<<(std::ostream& os, const Card& card) { os << COLOR_MAP[card.color] << card.type << RESET_COLOR; return os; } }; bool can_play_card(const Card& play_card, const Card& top_card) { if ( top_card.color == play_card.color || top_card.type == play_card.type || play_card.color == "BLACK" ) { return true; } return false; }; std::string cards_to_str(const std::vector<Card>& cards) { int len_cards = cards.size(); std::string str_cards = "["; for (int i = 0; i < len_cards; ++i) { str_cards += std::string(cards[i]); if (i != len_cards - 1) str_cards += ", "; } str_cards += "]"; return str_cards; } }; deck.h #pragma once #include <algorithm> #include "card.h" namespace UNO { std::vector<Card> create_cards( int cards_num=2, int cards_action=1, int cards_wild=2 ) { std::vector<Card> cards; for (auto color : COMMON_COLORS) { for (auto num_type : NUMBERS) { for (int i = 0; i < cards_num; ++i) cards.push_back(Card(color, num_type)); } for (auto action_type : ACTION_TYPES) { for (int i = 0; i < cards_action; ++i) cards.push_back(Card(color, action_type)); } } for (auto wild_type : WILD_TYPES) { for (int i = 0; i < cards_wild; ++i) cards.push_back(Card("BLACK", wild_type)); } return cards; } class Deck { public: std::vector<Card> cards;
{ "domain": "codereview.stackexchange", "id": 42623, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, playing-cards", "url": null }
c++, object-oriented, playing-cards return cards; } class Deck { public: std::vector<Card> cards; Deck(): cards{create_cards()}{}; Deck(std::vector<Card> cards_): cards{cards_}{}; friend std::ostream& operator<<(std::ostream& os, const Deck& deck) { os << cards_to_str(deck.cards); return os; } void shuffle() { std::random_shuffle(cards.begin(), cards.end()); } std::vector<Card> deal_cards(int amount) { if (cards.size() < amount) { for (const Card& card : create_cards()) cards.push_back(card); } std::vector<Card> dealt_cards; for (int i = 0; i < amount; ++i) { dealt_cards.push_back(cards.back()); cards.pop_back(); } return dealt_cards; } }; } player.h #pragma once #include <iostream> #include "deck.h" namespace UNO { class Player { public: std::string name; std::vector<Card> cards; Player(std::string name_, std::vector<Card> cards_): name{name_}, cards{cards_}{}; friend std::ostream& operator<<(std::ostream& os, const Player& player) { os << player.name; return os; } int get_play_card_index(const Card& top_card) const { for (int i = 0; i < cards.size(); ++i) { if (can_play_card(cards[i], top_card)) return i; } return -1; } Card pop_card(int index) { Card popped_card = cards[index]; cards.erase(cards.begin() + index); return popped_card; } bool is_win() const { return (cards.size() == 0); } }; } cycle.h #pragma once #include <vector>
{ "domain": "codereview.stackexchange", "id": 42623, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, playing-cards", "url": null }
c++, object-oriented, playing-cards cycle.h #pragma once #include <vector> namespace UNO { template <typename Type> class Cycle { private: int index = -1; bool reversed = false; public: std::vector<Type> items; Cycle(){}; Cycle(std::vector<Type> items_): items{items_}{}; Type* next() { index += (reversed) ? -1 : 1; if (index == items.size()) index = 0; else if (index == -1) index = items.size() - 1; return &items[index]; } void reverse() { reversed = !reversed; } }; } game.h #pragma once #include <iostream> #include <ctime> #include <algorithm> #include <windows.h> #include "card.h" #include "deck.h" #include "player.h" #include "cycle.h" namespace UNO { class Game { public: Deck cards_deck; std::vector<Player> players; Cycle<Player> player_cycle; Card top_card; Game() { int no_of_players; std::cout << "Enter number of players: "; std::cin >> no_of_players; if (std::cin.fail()) std::cerr << "Input Failure"; std::string player_name; std::cout << "Enter your name: "; std::cin >> player_name; if (std::cin.fail()) std::cerr << "Input Failure"; cards_deck.shuffle(); players.push_back(Player(player_name + " #1", cards_deck.deal_cards(7))); for (int i = 0; i < no_of_players - 1; ++i) { players.push_back( Player( "Player #" + std::to_string(i + 2), cards_deck.deal_cards(7)) ); } top_card = cards_deck.deal_cards(1)[0]; player_cycle.items = players; };
{ "domain": "codereview.stackexchange", "id": 42623, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, playing-cards", "url": null }
c++, object-oriented, playing-cards Game(Deck cards, Cycle<Player> player_cycle_): cards_deck{cards}, player_cycle{player_cycle_}{}; bool human_player(const Player& player) const { return (player.name.back() == '1'); } void play_game() { print_intro(); while (true) { Sleep(3500); Player* player = next_player(); print_turn(*player); handle_player(player); if (player->is_win()) { std::cout << *player << " wins the game!!\n"; break; } } }; void handle_player(Player* player) { if (human_player(*player)) handle_human_player(player); else handle_ai_player(player); } void print_intro() const { std::cout << "Welcome to UNO!\n"; std::cout << "Finish your cards as fast as possible!\n\n"; } void print_turn(Player& player) const { if (human_player(player)) { std::cout << "You have " << player.cards.size() << " cards left - " << cards_to_str(player.cards) << '\n'; } else { std::cout << player << " has " << player.cards.size() << " cards left...\n"; } std::cout << "Top card - " << top_card << "\n\n"; } void handle_human_player(Player* player) { bool any_play_card = false; for (const Card& card : player->cards) { if (can_play_card(card, top_card)) { any_play_card = true; break; } }
{ "domain": "codereview.stackexchange", "id": 42623, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, playing-cards", "url": null }
c++, object-oriented, playing-cards char choice = 'd'; if (any_play_card) { while (true) { std::cout << "Play or Draw? (p/d): "; std::cin >> choice; if (std::cin.fail()) std::cerr << "Input Failure"; choice = tolower(choice); if (choice == 'p' || choice == 'd') break; else std::cout << "Invalid Input\n"; } } if (choice == 'p') { int index; while (true) { std::cout << "Enter card index " << '(' << "1 - " << player->cards.size() << ')' << ": "; std::cin >> index; if (std::cin.fail()) std::cerr << "Input Failure"; if (index < 0 || index > player->cards.size()) std::cout << "Invalid index!\n"; else if (!can_play_card(player->cards[index - 1], top_card)) std::cout << "Can not play " << player->cards[index - 1] << "!\n"; else break; } Card card = player->pop_card(index - 1); top_card = card; std::cout << *player << " plays " << card << '\n'; handle_card_effect(&card, player); } else if (choice == 'd') { Card card = cards_deck.deal_cards(1)[0]; player->cards.push_back(card); std::cout << "You got a " << card << "...\n"; Sleep(2000);
{ "domain": "codereview.stackexchange", "id": 42623, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, playing-cards", "url": null }
c++, object-oriented, playing-cards if (can_play_card(card, top_card)) { std::cout << "Do you want to play " << card << "? (y/n): "; char choice; std::cin >> choice; if (std::cin.fail()) std::cerr << "Input Failure"; choice = tolower(choice); if (choice == 'y') { top_card = card; player->cards.pop_back(); std::cout << *player << " plays " << card << '\n'; handle_card_effect(&card, player); } } std::cout << '\n'; } } void handle_ai_player(Player* player) { int card_index = player->get_play_card_index(top_card); if (card_index != -1) { Card play_card = player->pop_card(card_index); std::cout << *player << " plays " << play_card << '\n'; handle_card_effect(&play_card, player); } else { Card card = cards_deck.deal_cards(1)[0]; std::cout << "Dealing 1 card to " << *player << "...\n"; if (can_play_card(card, top_card)) { top_card = card; Sleep(3500); std::cout << *player << " plays " << card << '\n'; handle_card_effect(&card, player); } else player->cards.push_back(card); std::cout << '\n'; } } void handle_card_effect(Card* card, Player* card_player) { bool card_is_number = (std::find( NUMBERS.begin(), NUMBERS.end(), card->type) != NUMBERS.end()); top_card = *card;
{ "domain": "codereview.stackexchange", "id": 42623, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, playing-cards", "url": null }
c++, object-oriented, playing-cards if (card_is_number) {} else if (card->type == "REVERSE") { player_cycle.reverse(); std::cout << "Cycle reversed...\n"; } else if (card->type == "SKIP") { Player* skip_player = next_player(); std::cout << *skip_player << " skipped...\n"; } else if (card->type == "2 PLUS") { Player* player = next_player(); std::vector<Card> deal_cards = cards_deck.deal_cards(2); for (int i = 0; i < 2; ++i) player->cards.push_back(deal_cards[i]); std::cout << "Dealing 2 cards to " << *player << ", skipped...\n"; } else if (card->type == "COLOR CHANGE") { if (human_player(*card_player)) top_card.color = get_color_input(); else top_card.color = COMMON_COLORS[rand() % 4]; std::cout << "Color changed to " << COLOR_MAP[top_card.color] << top_card.color << RESET_COLOR << '\n'; } else if (card->type == "4 PLUS") { if (human_player(*card_player)) top_card.color = get_color_input(); else top_card.color = COMMON_COLORS[rand() % 4]; std::cout << "Color changed to " << COLOR_MAP[top_card.color] << top_card.color << RESET_COLOR << '\n'; Player* player = next_player(); std::vector<Card> deal_cards = cards_deck.deal_cards(4); for (int i = 0; i < 4; ++i) player->cards.push_back(deal_cards[i]); std::cout << "Dealing 4 cards to " << *player << ", skipped...\n"; } std::cout << '\n'; }
{ "domain": "codereview.stackexchange", "id": 42623, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, playing-cards", "url": null }
c++, object-oriented, playing-cards Player* next_player() { while (true) { Player* player = player_cycle.next(); if (!player->is_win()) return player; } }; std::string get_color_input() { std::string color; do { std::cout << "Enter color: "; std::cin >> color; if (std::cin.fail()) std::cerr << "Input Failure"; for (int i = 0; i < color.length(); ++i) color[i] = toupper(color[i]); } while ( std::find(COMMON_COLORS.begin(), COMMON_COLORS.end(), color) == COMMON_COLORS.end() ); return color; }; }; } main.cpp - A minimal example #include <iostream> #include <ctime> #include "game.h" using namespace UNO; int main() { srand(time(0)); /* Can also handle creating players and cards deck Deck cards; std::vector<Player> players = { Player("Taha #1", cards.deal_cards(7)), Player("player #2", cards.deal_cards(7)), Player("player #3", cards.deal_cards(7)), Player("player #4", cards.deal_cards(7)), }; Cycle<Player> player_cycle(players); Game my_game(cards, player_cycle); */ // Or use the default constructor Game my_game; my_game.play_game(); return 0; } Some points to know before review: I have approached a object-oriented style. I have create the Cycle a template class, so it could be used for other purposes as well. You may see a lot of random '\n' in between blocks of code, they are just to make the console look clean. I said this, but again, the bots are not very smart. It took me a lot of time and errors to reach at this point, so there may be some bugs, but the ones I observed, I have fixed them.
{ "domain": "codereview.stackexchange", "id": 42623, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, playing-cards", "url": null }
c++, object-oriented, playing-cards Answer: Avoid using stringly-types class Card is storing its color and card type as std::strings. This has several issues. Apart from using a lot of memory per card, what happens if someone creates a Card with color and type set to names that are not valid UNO card colors and types? Epsecially in a larger program, mistakes are easily made, consider: Card card1{"Red", "3"}; // wrong capitalization Card card2{"COLOR CHANGE", "BLACK"}; // wrong order The way to solve these problems is to create enum types, or better enum class types, for both color and card type: enum class Color { BLUE, GREEN, RED, YELLOW, BLACK }; enum class Type { _0, _1, _2, ..., _9, REVERSE, SKIP, ... }; class Card { public: Color color; Type type; Card(): color{Color::BLUE}, type{Type::_0} {} Card(Color color, Type type): color{color}, type{type} {} ... }; And for example, can_play_card() now looks like: bool can_play_card(const Card& play_card, const Card& top_card) { return top_card.color == play_card.color || top_card.type == play_card.type || play_card.color == Color::BLACK; }
{ "domain": "codereview.stackexchange", "id": 42623, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, playing-cards", "url": null }
c++, object-oriented, playing-cards You still need some way to map between std::strings and Colors and Types, unfortunately enums don't help you with that. Use Deck everywhere instead of std::vector<Card> You are using both Decks and std::vector<Card>s in your code for sets of cards. I suggest that you try to make it possible to use Deck everywhere (except inside class Deck you still have to use a std::vector<Card> of course). To make this work, you should add member functions to Deck that make it act like a std::vector would, for example size(), begin() and end(), push_back(), erase(), and so on. A possible shortcut is to make Deck inherit from std::vector<Card>. You could also consider moving the code from create_cards() into a constructor of Deck. Possible out-of-bounds access in Cycle It is possible to have Cycle::next() read out of bounds. For example, if items is empty, it will always try to return a pointer to a non-existing item. But it is also possible to construct a Cycle with multiple players, but call reverse() before the first call to next(), in which case the first call to next() will cause index will become -2. While this situation is perhaps not possible in a game of UNO (since you always start in the forward direction, and you can't reverse until the next_player() has been called at least once), it is a good idea that a class doesn't rely too much on the behavior of its users for its correctness. You can easily make next() behave correctly even if reverse() was called as the first thing. As for calling next() on an empty cycle, you could argue that a caller should never do that. It might still be nice to assert(!items.empty()), so debugging the program is easier in case this does happen. You could also consider forbidding the construction of an empty Cycle, by deleting the default constructor and making the one that takes a vector of items throw if items.empty(). Don't arbitrarily sleep
{ "domain": "codereview.stackexchange", "id": 42623, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, playing-cards", "url": null }
c++, object-oriented, playing-cards Don't arbitrarily sleep Sleeping for 3.5 seconds between players quickly gets annoying. Also, Sleep() is not portable C++, if you really want to use it, use std::this_thread::sleep_for() instead. But even better might be to just wait for the user to hit Enter on the keyboard to advance to the next player; that allows the human player to control the speed as they like. Consider using std::getline() to read input Reading input with std::cin >> variable can be problematic, as this doesn't read a whole line, it reads a single number (if variable is an int), or a single word (if it is a std::string). Consider: std::string player_name; std::cout << "Enter your name: "; std::cin >> player_name;
{ "domain": "codereview.stackexchange", "id": 42623, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, playing-cards", "url": null }
c++, object-oriented, playing-cards What if I use my first and last name? This will cause player_name to be filled with my first name, and it will probably cause Invalid Input to be printed the first time handle_human_player() is called. To ensure you read whole lines of input, use std::getline(): std::string player_name; std::cout << "Enter your name: "; if (!std::getline(std::cin, player_name)) { std::cerr << "Input failure\n"; return; } When you want to read numbers, you will have to convert the string containing the line you just read to a number, for example using std::stoi(): std::string line; std::cout << "Enter number of players: "; if (!std::getline(std::cin, line)) { std::cerr << "Input failure\n"; return; } int no_of_players = std::stoi(line); But be aware that std::stoi(), just like std::cin >> number, stops parsing as soon as it hits the first character that is not a valid part of a number. Avoid using std::random_shuffle() std::random_shuffle() was deprecated in C++14 and removed in C++17. Avoid using it, instead use std::shuffle(). Pass large objects by (const) reference While you do use (const) references in some places, there are others where you are passing parameters by value unnecessarily. For example, the constructor of Player() should take the name and deck of cards as const references. Pass Player by reference instead of by pointer In Game::handle_player(), you pass the player by pointer, but in print_turn() it is by reference. Unless there is a reason for passing it as a pointer (like nullptr being a valid pointer value, or because you have virtual classes), prefer passing objects by reference.
{ "domain": "codereview.stackexchange", "id": 42623, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, playing-cards", "url": null }
javascript, node.js, error-handling Title: Implementation of exponential backoff algorithm Question: You can read about the algorithm here. An exponential backoff algorithm retries requests exponentially, increasing the waiting time between retries up to a maximum backoff time. An example is: Make a request to Cloud Storage. If the request fails, wait 1 + random_number_milliseconds seconds and retry the request. If the request fails, wait 2 + random_number_milliseconds seconds and retry the request. If the request fails, wait 4 + random_number_milliseconds seconds and retry the request. And so on, up to a maximum_backoff time. Continue waiting and retrying up to a maximum amount of time (deadline), but do not increase the maximum_backoff wait period between retries. where: The wait time is min((2n +random_number_milliseconds), maximum_backoff), with n incremented by 1 for each iteration (request). random_number_milliseconds is a random number of milliseconds less than or equal to 1000. This helps to avoid cases where many clients become synchronized and all retry at once, sending requests in synchronized waves. The value of random_number_milliseconds is recalculated after each retry request. maximum_backoff is typically 32 or 64 seconds. The appropriate value depends on the use case. You can continue retrying once you reach the maximum_backoff time, but we recommend your request fail out after an amount of time to prevent your application from becoming unresponsive. For example, if a client uses a maximum_backoff time of 64 seconds, then after reaching this value, the client can retry every 64 seconds. The client then stops retrying after a deadline of 600 seconds. EBARetrier.js const utils = require("./utils"); async function EBARetrier(callback, argsList) { const context = getEBAContext(callback, argsList); while (isProcessingEntities(context)) { try { await processEntity(context); } catch (error) { handleFailedEntity(context, error); } } }
{ "domain": "codereview.stackexchange", "id": 42624, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, node.js, error-handling", "url": null }
javascript, node.js, error-handling function getEBAContext(callback, argsList) { return { maximumBackoff: 64, deadline: 600, startTime: Date.now(), totalEntities: argsList.length, failedEntities: [], retryAttempt: 0, processedEntities: 0, lastProcessFailed: false, args: null, callback, argsList, }; } function isProcessingEntities(context) { return ( utils.getTimeElapsed(context.startTime) < context.deadline && context.processedEntities < context.totalEntities ); } async function processEntity(context) { const args = context.failedEntities.shift() || context.argsList.shift(); context.args = args; if (context.lastProcessFailed) { const ms = getWaitTime(context); await utils.wait(ms); } await context.callback(...args); context.processedEntities++; context.lastProcessFailed = false; context.retryAttempt = 0; } function handleFailedEntity(context, error) { console.error(error); context.failedEntities.push(context.args); context.lastProcessFailed = true; context.retryAttempt++; } function getWaitTime(context) { const randomMS = utils.getRandomInt(1001); const attempt = context.retryAttempt - 1; const ms = Math.pow(2, attempt) * 1000 + randomMS; const maxBackoffMs = context.maximumBackoff * 1000; if (ms > maxBackoffMs) { return maxBackoffMs; } return ms; } module.exports = { EBARetrier, }; utils.js function getRandomInt(max) { return Math.floor(Math.random() * max); } function getTimeElapsed(startTime) { return (Date.now() - startTime) / 1000; } function wait(ms) { return new Promise((resolve) => { setTimeout(resolve, ms); }); } module.exports = { getRandomInt, getTimeElapsed, wait, }; Any help will be appreciated! Thanks! Answer: Code should be correct, maintainable, robust, reasonably efficient, and, most importantly, readable. Your code appears to be mathematically unsound. You write: deadline: 600, startTime: Date.now(),
{ "domain": "codereview.stackexchange", "id": 42624, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, node.js, error-handling", "url": null }
javascript, node.js, error-handling Your code appears to be mathematically unsound. You write: deadline: 600, startTime: Date.now(), . function getTimeElapsed(startTime) { return (Date.now() - startTime) / 1000; } . getTimeElapsed(context.startTime) < context.deadline The Javascript Date.now() and performance.now() methods are documented in MDN: JavaScript and elsewhere. Also unlike Date.now(), the values returned by performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like NTP). and To offer protection against timing attacks and fingerprinting, the precision of Date.now() might get rounded depending on browser settings. In Firefox, the privacy.reduceTimerPrecision preference is enabled by default and defaults to 20µs in Firefox 59; in 60 it will be 2ms. Your getTimeElapsed function may return variable rate positive, negative, or zero values. Use monotonic clock values that increase at a constant rate. Write: deadline: 600, startTime: performance.now(), . function getTimeElapsed(startTime) { return (performance.now() - startTime) / 1000; } . getTimeElapsed(context.startTime) < context.deadline Your getWaitTime function is based on an exponential backoff algorithm that appears to be mathematically unsound. function getWaitTime(context) { const randomMS = utils.getRandomInt(1001); const attempt = context.retryAttempt - 1; const ms = Math.pow(2, attempt) * 1000 + randomMS; const maxBackoffMs = context.maximumBackoff * 1000; if (ms > maxBackoffMs) { return maxBackoffMs; } return ms; } The algorithm definition states: random_number_milliseconds is a random number of milliseconds less than or equal to 1000. This helps to avoid cases where many clients become synchronized and all retry at once, sending requests in synchronized waves. The value of random_number_milliseconds is recalculated after each retry request.
{ "domain": "codereview.stackexchange", "id": 42624, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, node.js, error-handling", "url": null }
javascript, node.js, error-handling If we implement the algorithm from the definition, we can see that it appears to be mathematically unsound. It does not avoid synchronized waves once it reaches the backoff value. retry.js: 'use strict'; // Truncated exponential backoff wait time in milliseconds. // https://cloud.google.com/storage/docs/retry-strategy#exponential-backoff // https://en.wikipedia.org/wiki/Exponential_backoff function tebWait(backoff, deadline) { let n = 0; let sum = 0; return function waitTime() { let wait = Math.pow(2, n++); wait += Math.random(); wait = Math.min(wait, backoff); sum+=wait; if (sum > deadline) { return null; } return Math.ceil(wait * 1000); } } let backoff = 64; let deadline = 600; let retryWait = tebWait(backoff, deadline); for (let wait = 0; (wait = retryWait()) != null; ) { console.log(wait); } . $ node retry.js 1361 2848 4065 8746 16236 32305 64000 64000 64000 64000 64000 64000 64000 64000 Here's a revised version of the algorithm that does avoid synchronized waves once it reaches the backoff value. retry.js: 'use strict'; // Truncated exponential backoff wait time in milliseconds. // https://cloud.google.com/storage/docs/retry-strategy#exponential-backoff // https://en.wikipedia.org/wiki/Exponential_backoff function tebWait(backoff, deadline) { let n = 0; let sum = 0; return function waitTime() { let wait = Math.pow(2, n++); wait = Math.min(wait, backoff); sum+=wait; if (sum > deadline) { return null; } wait += Math.random(); return Math.ceil(wait * 1000); } } let backoff = 64; let deadline = 600; let retryWait = tebWait(backoff, deadline); for (let wait = 0; (wait = retryWait()) != null; ) { console.log(wait); } . $ node retry.js 1344 2548 4239 8110 16564 32013 64615 64397 64501 64318 64602 64680 64477 64123
{ "domain": "codereview.stackexchange", "id": 42624, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, node.js, error-handling", "url": null }
python, performance, beginner, algorithm, python-2.x Title: Use Python to determine the repeating pattern in a string Question: I am writing an algorithm to count the number of times a substring repeats itself. The string is between 1-200 characters ranging from letters a-z. There should be no left overs at the end of the pattern either and it should be split into the smallest possible combination. answer("abcabcabcabc"):output = 4 answer("abccbaabccba"): output = 2 answer("abcabcd"): output = 1 My code: import re def answer(s): length = len(s) x=[] reg = "" for i in range(1, length+1): if length % i == 0: x.append(i) repeat = len(x)*10 for _ in range(0, repeat): a = length/max(x) print(length) print(max(x)) print(a) for _ in range(0, a): reg = reg + "." exp = re.findall(reg, s) print exp if all(check==exp[0] for check in exp): print len(exp) return len(exp) elif all(check!=exp[0] for check in exp): x.remove(max(x)) This is Python 2.7 code and I don't have to use regex. It just seemed like the easiest way. Is there a better/faster/more optimal way to do this? NOTE: it breaks if the string size is too big. EDIT: Fixed indentation Answer: I see that there already is an accepted answer, before I got around to writing this answer. That is a little discouraging for me as a reviewer, but I've written a code alternative and have some thoughts regarding your code. Code review
{ "domain": "codereview.stackexchange", "id": 42625, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, beginner, algorithm, python-2.x", "url": null }
python, performance, beginner, algorithm, python-2.x Document your code – To guess what your code is doing by simply reading it is not very easy. It could very well have a few comments on what it tries to achieve. Better variable names – In general try to use variable names describing the content. Names like x, a, exp (which I would read as expression?), and so on, are not very informative. Regex are generally expensive – In general regex, whilst being a fantastic too, are somewhat overused. Do note that it takes time to build the patterns and match the patterns, especially compared to simple string matches. Some new(?) constructs I'm not sure if you know these already, but there are a few new constructs I would like to show you: String repeat – Strings can be multiplied (aka duplicated) using the multiplication operator. text = "abc" print text * 3 # Will output "abcabcabc" divmod with multiple outputs – divmod(a, b) will divide a by b and return the divisor and the rest. This can be stored directly into a tuple like in the following: div, rest = divmod(13, 5) # Giving div == 2, rest = 3 Slice and dice strings – As of Python 2.3 one can slice strings. The most common variants indicates how many characters you want from start like text[:3] or if you want the rest of the text like text[3:]. This can be very useful... A slightly fancier print varant – Using .format in combination with print can produce nicer output rather easily: print 'i: {}, sub: {}, div: {}, mod: {}'.format(i, source[:i], div, rest) This would output on the same line, something like: i: 4, sub: abcd, div: 2, mod: 3
{ "domain": "codereview.stackexchange", "id": 42625, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, beginner, algorithm, python-2.x", "url": null }
python, performance, beginner, algorithm, python-2.x This would output on the same line, something like: i: 4, sub: abcd, div: 2, mod: 3 else-block after for?! – This will make sense later on, but if a for loop completes normally, it'll not enter the optional else:-block. In other words, if you break out of a for loop Python won't enter the else block. This can be used to verify that the for loop actually found/did something, and provide an alternative if it didn't. for i in range(5): print i if i == 3: break else: print "Nothing larger than 3..." Code alternative I haven't commented too much on your chosen algorithm, as I find it a little confusing, so I thought what is he trying to achieve and what is an alternative approach. I then came up with these demands for the code: You're looking for the maximum repeated substring completely filling out the original string. This means: The candidate substring length, must then divide the original string length without any leftover (or rest characters) The candidate substring can't be more than half the length of the original string, as it then can't be duplicated The first (and shortest) candidate substring will always give the most repeats, if it matches the other criteria So one way to write this out is like this: def repeatedSubstring(source): """Look for the shortest substring which when repeated equals the source string, without any left over characters. """ length = len(source) print '\nOriginal text: {}. Length: {}'.format(source, length) # Check candidate strings for i in range(1, length/2+1): repeat_count, leftovers = divmod(length, i) # print 'i: {}, sub: {}, div: {}, mod: {}'.format(i, source[:i], repeat_count, leftovers) # print 'repeated: {}'.format(source[:i]*repeat_count)
{ "domain": "codereview.stackexchange", "id": 42625, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, beginner, algorithm, python-2.x", "url": null }
python, performance, beginner, algorithm, python-2.x # Check for no leftovers characters, and equality when repeated if (leftovers == 0) and (source == source[:i]*repeat_count): print 'Found repeated substring: {}, count: {}'.format(source[:i], repeat_count) break else: print "Couldn't find any repeated substring" repeatedSubstring("abcdeabcde") repeatedSubstring("abcdeabcdef") repeatedSubstring("aaaaa") I've commented out some debug print statements, and left it a little more verbose than the original code. If you want, you can easily replace the remaining print statements with return div and return 1. A stripped down version would then look like: def repeatedSubstringCount(source): """Look for the shortest substring which when repeated equals the source string, without any left over characters. Return the maximum repeat count, 1 if none found. """ length = len(source) # Check candidate strings for i in range(1, length/2+1): repeat_count, leftovers = divmod(length, i) # Check for no leftovers characters, and equality when repeated if (leftovers == 0) and (source == source[:i]*repeat_count): return repeat_count return 1 I still left a few comments in there, so that it possible to have some idea on what is happening. I've also changed the name to "repeatedSubstringCount" to indicate both what the function does, but also what it returns.
{ "domain": "codereview.stackexchange", "id": 42625, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, beginner, algorithm, python-2.x", "url": null }
python-3.x, pandas Title: Binning multicolumn Pandas Dataframe Question: I'm trying to bin multicolumn Pandas Dataframe, and use the upper limit of the interval for further analysis. This is my approach: # Creating a dummy dataframe: df=pd.DataFrame({'A':np.random.randint(10, size=5),'B':np.random.randint(20, size=5)}). # Binning dataframe for all columns, and use the upper interval value as a separate column: df2 = df[['A','B']].apply(lambda x: x.value_counts(bins=np.arange(0, max(df.B)+2, 2), sort=False)).reset_index().rename({'index':'binName'}, axis = 'columns') df2['binName'] = df2['binName'].map(attrgetter('right')).astype(int) df2 Result: binName A B 0 2 3 0 1 4 1 0 2 6 1 0 3 8 0 3 4 10 0 0 5 12 0 2 Is there a better solution, I think I'm overdoing it. I'm aware of pandas cut but it does not work for multiple column (I could be wrong). Thanks! Answer: Instead of applying value_counts to each column individually, the more common approach in pandas would be to reshape to long format (a single column), perform the binning operations on the Series, then return to wide format. Reproducible setup: import numpy as np import pandas as pd from numpy.random import Generator, MT19937 rng = Generator(MT19937(10)) size = 5 df = pd.DataFrame({'A': rng.integers(10, size=size), 'B': rng.integers(20, size=size)}) df: A B 0 7 9 1 9 3 2 8 8 3 8 10 4 3 17
{ "domain": "codereview.stackexchange", "id": 42626, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python-3.x, pandas", "url": null }
python-3.x, pandas df: A B 0 7 9 1 9 3 2 8 8 3 8 10 4 3 17 We can first stack to go to long format, then use groupby apply to use the Series.value_counts function on each group ('A' and 'B' here). unstack allows us to go back from a single column Series to a multiple column DataFrame. Lastly some cleanup, rename_axis to handle the axis names created when unstacking and reset_index to restore the range index. Since the upperbound for each bin is an already calculated value, we can simply use the bins variable to insert a new column 'binName' to the front of the DataFrame. bins_size = 2 # Get Maximum value from entire DataFrame df_max_value = df.max().max() # Build Bins bins = np.arange(0, df_max_value + bins_size, bins_size) df2 = ( df.stack().droplevel(0) # Convert to long format .groupby(level=0) # Group by "columns" now in index .apply(pd.Series.value_counts, bins=bins, sort=False) .unstack(level=0) # Convert back to wide .rename_axis(columns=None) .reset_index(drop=True) ) df2.insert(0, 'binName', bins[1:]) df2: binName A B 0 2 0 0 1 4 1 1 2 6 0 0 3 8 3 1 4 10 1 2 5 12 0 0 6 14 0 0 7 16 0 0 8 18 0 1 Ideally we should be able to use groupby value_counts with bins: bins_size = 2 # Get Maximum value from entire DataFrame df_max_value = df.max().max() # Build Bins bins = np.arange(0, df_max_value + bins_size, bins_size) df2 = ( df.stack() # Convert to long format .groupby(level=1) .value_counts(bins=bins, sort=False) .unstack(level=0) # Convert back to wide .rename_axis(columns=None) # cleanup columns .reset_index(drop=True) # Restore range index ) # Add binName column to beginning df2.insert(0, 'binName', bins[1:])
{ "domain": "codereview.stackexchange", "id": 42626, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python-3.x, pandas", "url": null }
python-3.x, pandas Unfortunately, there is an issue which causes categorical values to function incorrectly (though this may be resolved in future). Currently, this results in incorrect values being produced: binName A B 0 2 1 1 # Incorrect 1 4 3 1 # Incorrect 2 6 1 2 # Incorrect 3 8 0 1 # Incorrect 4 10 0 0 # Incorrect 5 12 0 0 6 14 0 0 7 16 0 0 8 18 0 0 # Incorrect For a less idiomatic, but much faster approach, we can use NumPy instead. Use np.searchsorted to determine where which bin the value should fall in. Then use the results of binning to calculate the total for each column. Create an empty array of the counts with np.zeros then np.add with ufunc.at on each column to add 1 for each index value stored in a. Then convert this 2D array into the DataFrame constructor with the came columns as df had. Lastly, insert the bins into the front of the DataFrame. bins_size = 2 # Get Maximum value from entire DataFrame df_max_value = df.max().max() # Build Bins bins = np.arange(0, df_max_value + bins_size, bins_size, dtype=np.float32) # Reduce initial lowerbound below 0 # (this is done automatically by Series.value_counts) bins[0] -= 0.001 # Use searchsorted to determine which bin the value belongs in a = np.searchsorted(bins, df, side='left') # Create Empty Count Array of Zeros c = np.zeros((len(bins), df.columns.size), dtype=np.int32) # Add bin counts from each column for i in range(df.columns.size): np.add.at(c[:, i], a[:, i], 1) # Build New DataFrame (excluding unused lower bound bin) df2 = pd.DataFrame(c[1:], columns=df.columns) # Add binName to beginning of DataFrame df2.insert(0, 'binName', bins[1:].astype(int)) df2: binName A B 0 2 0 0 1 4 1 1 2 6 0 0 3 8 3 1 4 10 1 2 5 12 0 0 6 14 0 0 7 16 0 0 8 18 0 1
{ "domain": "codereview.stackexchange", "id": 42626, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python-3.x, pandas", "url": null }
python-3.x, pandas For testing, I increased the length of the DataFrame to 5000, with maximum of 100 bins: from operator import attrgetter import numpy as np import pandas as pd from numpy.random import Generator, MT19937 rng = Generator(MT19937(10)) size = 5000 df = pd.DataFrame({'A': rng.integers(100, size=size), 'B': rng.integers(200, size=size)}) def pandas_way(df_): bins_size = 2 df_max_value = df_.max().max() bins = np.arange(0, df_max_value + bins_size, bins_size) df2 = ( df_.stack().droplevel(0) .groupby(level=0) .apply(pd.Series.value_counts, bins=bins, sort=False) .unstack(level=0) .rename_axis(columns=None) .reset_index(drop=True) ) df2.insert(0, 'binName', bins[1:]) return df2 def numpy_way(df_): bins_size = 2 df_max_value = df_.max().max() bins = np.arange(0, df_max_value + bins_size, bins_size, dtype=np.float32) bins[0] -= 0.001 a = np.searchsorted(bins, df_, side='left') c = np.zeros((len(bins), len(df_.columns)), dtype=np.int32) for i in range(df_.columns.size): np.add.at(c[:, i], a[:, i], 1) df2 = pd.DataFrame(c[1:], columns=df_.columns) df2.insert(0, 'binName', bins[1:].astype(int)) return df2 def original_way(df_): df2 = df_[['A', 'B']].apply( lambda x: x.value_counts(bins=np.arange(0, max(df_.B) + 2, 2), sort=False)).reset_index().rename( {'index': 'binName'}, axis='columns') df2['binName'] = df2['binName'].map(attrgetter('right')).astype(int) return df2 # Sanity Checks that all ways produce the same results print(original_way(df).eq(numpy_way(df)).all(axis=None)) print(original_way(df).eq(pandas_way(df)).all(axis=None)) print(numpy_way(df).eq(pandas_way(df)).all(axis=None))
{ "domain": "codereview.stackexchange", "id": 42626, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python-3.x, pandas", "url": null }
python-3.x, pandas Some timings via %timeit: %timeit numpy_way(df) 1.55 ms ± 16.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) %timeit pandas_way(df) 11.1 ms ± 173 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) %timeit original_way(df) 11.4 ms ± 315 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) Note: while timings may vary, NumPy is significantly faster than pandas.
{ "domain": "codereview.stackexchange", "id": 42626, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python-3.x, pandas", "url": null }
javascript, algorithm, html, sorting Title: A New Sorting Algorithm Question: I have designed an Algorithm for sorting numbers. This algorithm works by sorting an array of any length with random, non-repeating whole numbers in a linear manner by ascending order. Under the inspiration of Binary Search Algorithm, although inefficient the algorithm is able to sort the given array correctly. What is missing here is that the algorithm isn't fast enough tho I modified it to bring the sence of being involved with the software. Why All This... Soon after knowing how to code in JavaScript I wanted to make a little awesome project with my programming skills. I wanted to show it to the world and to other smart programmers out there but I never knew how... So I stumbled upon here... My hopes are that anyone will show some love and review it on their free time and give out their opinions about it on how to improve it and make it faster if possible. The HTML page for it is <!DOCTYPE html> <html> <head> <title>P-sort Algo</title> </head> <body> <h1>Move To The Console</h1> <script type="text/javascript" src="Js\p-sort Algo.js"></script> </body> </html> And the Algo.js file for the JavaScript codes is ////////////////////////////// The Algorithim /////////////////////////////////
{ "domain": "codereview.stackexchange", "id": 42627, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, algorithm, html, sorting", "url": null }
javascript, algorithm, html, sorting //Variables... var oldNumb; var newNumb; var firstNo; var lastNo; var low; var high; var mean; var attachment; var phase1; var random; var counter; var pointer; var n; var z; ///// The Intro Of The User To The Program..... /////////// console.log("Hello There..... "); console.log('Welcome To "P-Sort Algorithim" Software!'); console.log("Lets Get Started...."); console.log("Please Generate Random Numbers By The Function rand(x , y)"); console.log( 'Where "x" is The Approximate Number Of Elements You Want To Generate &' ); console.log(' "y" is The Range Of Your Numbers From 1!'); console.log( 'NOTE: For Better Review Of The Algorithim, It Is Recommended "y" > "x"' ); /////// Random Number Generation... function rand(x, y) { oldNumb = []; newNumb = []; console.log("........... Working On It! ..........."); console.log("This Might Take A While!!!"); console.log(" "); for (let i = 0; i < x; i++) { random = Math.floor(Math.random() * y + 1); if (!oldNumb.includes(random)) { oldNumb.push(random); } } counter = oldNumb.length - 1; z = oldNumb.length - 1; console.log("Completed!!!!"); /////////////// Thus... Given Random Numbers Are........ console.log("Random Batch"); console.log(oldNumb); console.log(newNumb); console.log( "................................................................................." ); console.log( "Good! Now You Can Sort That Array Of Numbers By A Function pSort()" ); return "___________________________________________________________________________________";
{ "domain": "codereview.stackexchange", "id": 42627, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, algorithm, html, sorting", "url": null }
javascript, algorithm, html, sorting } ///////////////// The Algo.... ///////////////////////////// function reco() { if (attachment < newNumb[mean]) { high = mean; mean = Math.round((low + mean) / 2); } else if (attachment > newNumb[mean]) { low = mean; mean = Math.round((mean + high) / 2); } if (low + 1 == high) { phase1 = newNumb.splice(high, newNumb.length); newNumb.push(attachment); newNumb = newNumb.concat(phase1); phase1 = []; oldNumb.pop(); return -1; } else if (low + 1 != high) { reco(); } return -1; } function universal() { pointer = Math.floor(z / 10); n = 1; console.log( ".......... Process='sorting-data'; Type='numbers'; Quantity ='" + (z + 1) + "'; Phase: " + n + "/10 .........." ); console.log(" "); n = n + 1; for (let i = 0; i < z + 1; i++) { counter = 0; firstNo = newNumb[counter]; lastNo = newNumb[newNumb.length - 1]; attachment = oldNumb[oldNumb.length - 1]; if (attachment < firstNo) { newNumb.unshift(attachment); oldNumb.pop(); } else if (attachment > lastNo) { newNumb.push(attachment); oldNumb.pop(); } else if (attachment > firstNo && attachment < lastNo) { //Binary Search.... low = 0; high = newNumb.length - 1; mean = Math.round((low + high) / 2); reco(); } if (i == n * pointer) { console.log( ".......... Process='sorting-data'; Type='numbers'; Quantity='" + (z + 1) + "'; Phase: " + n + "/10 .........." );
{ "domain": "codereview.stackexchange", "id": 42627, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, algorithm, html, sorting", "url": null }
javascript, algorithm, html, sorting "'; Phase: " + n + "/10 .........." ); console.log(" "); n = n + 1; } } console.log( "...................................................................................................." ); console.log("Final Batch"); console.log(newNumb); console.log(oldNumb); return -1; } function pSort() { /////////////////// Starter ////////////////// firstNo = oldNumb[counter]; lastNo = oldNumb[(counter = counter - 1)]; if (firstNo > lastNo) { newNumb.unshift(lastNo); newNumb.push(firstNo); } else if (firstNo < lastNo) { newNumb.unshift(firstNo); newNumb.push(lastNo); } oldNumb.pop(); oldNumb.pop(); universal(); console.log('Done'); console.log('.......................................................................'); console.log(" ") console.log('P-Sort Algorithim'); return "_________________________________________________________________________________________"; }
{ "domain": "codereview.stackexchange", "id": 42627, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, algorithm, html, sorting", "url": null }
javascript, algorithm, html, sorting Answer: Line length: you want to avoid long lines of code when you can. With some lines this is unavoidable, but you shouldn't have a long line just because you wanted to print a spacer to the console. You should prefer const when you can, and let when you can't. I don't think there are cases where you'd need to use var. Functions should do something or print something, but not both. (The idea is that you should be able to add the js file to a website and then just call the sort function without worrying about it printing stuff to the console.) There's no reason to return "-------"; reco and universal are bad function names. They should better describe what they're doing. rand should probably be randInts. But it's not really the point of the algorithm, so I'm going to just hard code that part and not worry about it. reco is a binary search and insertion, so I'll name it binaryInsertion. Instead of console.log the instructions, you should put them in the comments. phase1 = []; is never used again and should be deleted. Your variable naming needs a little work. You should be able to look at a variable and know what it does. I'm going to do the following: x -> size y -> range oldNumb -> oldNumbers newNumb -> newNumbers attachment -> newNumber phase1 -> tail
{ "domain": "codereview.stackexchange", "id": 42627, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, algorithm, html, sorting", "url": null }
javascript, algorithm, html, sorting Avoid global variables as much as possible ("possible" should be "entirely" for a library function like sorting). The easiest of those to fix is if you are always assigning to it before using it, like firstno, lastno, phase1, pointer, random. binaryInsertion (aka reco) can pass itself the arguments it needs. oldNumb[(counter = counter - 1)] is asking for trouble. Don't assign within an expression. But you always know what counter is, so just use that value instead of saving it to a variable. It seems like n and pointer are only there to help with logging how far you've progressed through the algorithm (and if z%10 is large, then you get interesting output like being in "Phase 15/10"). Let's take out this logging. If we need to figure out what's happening, developer tools like breakpoints can work almost as well, and that won't print stuff to the console when we're not debugging. You should return something useful, or not return at all. ------ was bad. -1 is also bad (unless it means something). You have a couple of if ( condition ) { ... } else if ( ! condition ) { ... }, leaving me wondering if the else if might not happen, and what that function would do in that case. Since you know it's going to be one or the other, just have if ( condition ) { ... } else { ... }. The second argument to array.splice defaults to the rest of the elements. Let's make use of that. binaryInsertion and univesal have 3 oldNumbers.pop();, but exactly one will happen. Let's move them to the end of universal's for loop. If you have a base case initialization and then a loop or recursion, try to make the initialization as simple as possible by moving things into the loop or recusion. In this case, pSort only needs to put a single element into newNumbers, not two, before handing things off to universal. z is set to oldNumbers.length - 1 and then never changed again. And it's only use is < z+1 in a for loop. Let's get rid of z.
{ "domain": "codereview.stackexchange", "id": 42627, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, algorithm, html, sorting", "url": null }
javascript, algorithm, html, sorting someArray.pop() returns the value that was popped. We can use that instead of someArray[ someArray.length-1 ] and popping later. But if we iterate through oldNumbers instead of popping, then we don't destroy the old array. That seems worthwhile. pSort is now short enough that we can move it into universal, and rename that to pSort.
{ "domain": "codereview.stackexchange", "id": 42627, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, algorithm, html, sorting", "url": null }
javascript, algorithm, html, sorting The code so far: let oldNumbers = [], newNumbers = []; let low, high, mean, newNumber; const size = 20, range = 100; for ( let i = 0 ; i < size ; i++ ) { const random = Math.floor(Math.random() * range + 1); if ( !oldNumbers.includes(random) ) { oldNumbers.push(random); } } console.log(oldNumbers); function binaryInsertion() { if ( newNumber < newNumbers[mean] ) { high = mean; mean = Math.round((low + mean) / 2); } else if ( newNumbers[mean] < newNumber ) { low = mean; mean = Math.round((mean + high) / 2); } if (low + 1 == high) { const tail = newNumbers.splice(high); newNumbers.push(newNumber); newNumbers = newNumbers.concat(tail); } else { binaryInsertion(); } } function pSort() { const firstNo = oldNumbers.pop(); newNumbers = [firstNo]; for ( let i = 0 ; i < oldNumbers.length ; i++ ) { const firstNo = newNumbers[0]; const lastNo = newNumbers[newNumbers.length - 1]; newNumber = oldNumbers[i]; if ( newNumber < firstNo ) { newNumbers.unshift(newNumber); } else if ( lastNo < newNumber ) { newNumbers.push(newNumber); } else { //Binary Search.... low = 0; high = newNumbers.length - 1; mean = Math.round((low + high) / 2); binaryInsertion(); } } } pSort(); console.log(newNumbers);
{ "domain": "codereview.stackexchange", "id": 42627, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, algorithm, html, sorting", "url": null }
javascript, algorithm, html, sorting We want to eliminate the global variables low, high, mean, and newNumber, which are primarily used by binaryInsertion. The thing to realize is that the function is doing two different things: finding the new location and doing the insertion. If we split finding the index into a separate binarySearch function, we can incorporate the variables as parameters instead of global variables. The newNumber < firstNo and lastNo < newNumber cases are handled by the general binaryInsertion, so it's questionable whether you should actually separate them out. I'm going to remove them, because it simplifies the code. At this point, pSort is short enough that we can combine it with binaryInsertion. We can also remove the restriction that the numbers be unique. Finally, we can pass oldNumbers as a parameter to pSort, and have it return newNumbers, removing the last global variables. Here's the final product: let oldNumbers = []; const size = 20, range = 100; for ( let i = 0 ; i < size ; i++ ) { const random = Math.floor(Math.random() * range + 1); oldNumbers.push(random); } console.log(oldNumbers);
{ "domain": "codereview.stackexchange", "id": 42627, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, algorithm, html, sorting", "url": null }
javascript, algorithm, html, sorting function binarySearch(haystack,needle,low,high) { if ( haystack.length===0 ) { return 0; } if ( low===undefined || high===undefined ) { low = 0; high = haystack.length-1; } if ( high <= low ) { if ( needle < haystack[low] ) { return low; } return low+1; } const mean = Math.floor((low + high) / 2); if ( needle < haystack[mean] ) { return binarySearch(haystack,needle,low,mean); } if ( haystack[mean] < needle ) { return binarySearch(haystack,needle,mean+1,high); } // at this point, haystack[mean] === needle return mean; } function pSort(oldNumbers) { let newNumbers = []; for ( let i = 0 ; i < oldNumbers.length ; i++ ) { newNumber = oldNumbers[i]; const newLocation = binarySearch(newNumbers,newNumber); const tail = newNumbers.splice(newLocation,newNumbers.length); newNumbers.push(newNumber); newNumbers = newNumbers.concat(tail); } return newNumbers; } newNumbers = pSort(oldNumbers); console.log(newNumbers); We now have a binarySearch function, and a sort function, which are worthwhile additions to any library (our implementation is probably not the best, but that's another matter). If we're feeling a bit cocky, we can even add them to the array prototype: Array.prototype.pSort = function() { return pSort(this); }, so that we can write oldNumbers.pSort() It's been a long time since my computer science class, but I think this is an insertion sort.
{ "domain": "codereview.stackexchange", "id": 42627, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, algorithm, html, sorting", "url": null }
php, security, image, .htaccess Title: Serve rescaled jpg images on demand with myphoto!500.jpg syntax (here 500px-width rescaled) Question: On web pages, obviously large photos (e.g. 4000x4000px) cannot be served with a reliance on CSS to do the resizing: it would be too slow for end users and too bandwidth-consuming for the server. So it's important to rescale photos to the desired size that will be actually used on the website. For this reason I usually resized the image with a tool like Photoshop to, say 800px width. But then later you always have the case "I would finally have preferred 10000px instead! and then ... you have to export the JPG again, re-upload, etc. Annoying! Instead here is an automated solution in which you upload the top-quality version (never served to end users because it would be too big), and the tool automatically resizes on-demand. Here is code that: serves myphoto.jpg if present in current folder serves myphoto!500.jpg if present in current folder creates myphoto!500.jpg by rescaling myphoto.jpg with a width of 500px if it is not done yet. So as it will be saved/cached to a file, next requests will be fast because the server will just serve the pre-cooked file .htaccess RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.php [QSA,L] index.php <?php $req = urldecode(basename($_SERVER['REQUEST_URI'])); list($f, $size) = explode('!', $req); list($size, $ext) = explode('.', $size); $size = intval($size); if (($size > 2000) || ($size % 50 != 0)) die(); $f .= '.' . $ext; list($width, $height) = getimagesize($f); $src = imagecreatefromstring(file_get_contents($f)); $dst = imagescale($src, $size); imagejpeg($dst, $req); ?>
{ "domain": "codereview.stackexchange", "id": 42628, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, security, image, .htaccess", "url": null }
php, security, image, .htaccess Question for code review: is there something to improve in terms of security? Note: To avoid the scenario that someone requests myimage!1.jpg, myimage!2.jpg, ..., myimage!1999.jpg, myimage!2000.jpg in loop, filling the disk for nothing, the code only accepts size as integer multiples of 50. At most 50 100 150 ... 1900 1950 2000 will be written, i.e. 40 versions. Answer: Analysis The code looks acceptable; it is not difficult to read. The description does not state which image formats should be supported however the code appears to output resized images as JPEG images. It may be wise to maintain the image format - e.g. GIF, PNG, JPG, etc. Suggestions Consider using pattern matching to validate the request URI A regular expression could be used to both ensure the request URI matches the expected format and also parse out the components. While it may be slightly slower the difference should be negligible. One could use preg_match() or if Unicode string support is needed then mb_eregi() could be used. A pattern could be crafted to ensure: there is not more than one exclamation mark The number that follows the exclamation mark is positive and has a number of digits within a certain range (e.g. 1-5) The extension is within the acceptable list of extensions Doing this should allow removal of the multiple calls to split the string using explode(). For example: preg_match('#^([^!\./]+)!(\d+)\.(png|jpg|gif)#i', $req, $matches); if (!$matches) { die(); } [$uri, $name, $size, $ext] = $matches; ^ asserts position at start of the string 1st Capturing Group ([^!\./]+) Match a single character not present in the list below [^!\./] + matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy) Could be changed to ([a-z0-9]+) to only allow alphanumeric characters or (\w+) to allow [A-Za-z0-9_] ! matches the character ! with index 3310 (2116 or 418) literally (case insensitive) 2nd Capturing Group (\d+)
{ "domain": "codereview.stackexchange", "id": 42628, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, security, image, .htaccess", "url": null }
php, security, image, .htaccess \d matches a digit (equivalent to [0-9]) + matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy) \. matches the character . with index 4610 (2E16 or 568) literally (case insensitive) 3rd Capturing Group (png|jpg|gif) 1st Alternative png png matches the characters png literally (case insensitive) 2nd Alternative jpg jpg matches the characters jpg literally (case insensitive) 3rd Alternative gif gif matches the characters gif literally (case insensitive) Global pattern flags i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z]) See the regular expression pattern explained here. Named sub-patterns can be named to allow the array of matches to have keys that are easier to work with. For example: preg_match('#^(?P<name>[^!\./]+)!(?P<size>\d+)\.(?P<ext>png|jpg|gif)#i', $req, $matches); Here are the parts of the pattern explained: opening delimiter: # Start of line anchor: ^ match one or more chars for file name- anything that isn’t an exclamation mark, dot or slash: (?P<name>[^!\./]+) Could be changed to (?P<name>[a-z0-9]+) to only allow those characters the exclamation mark: ! The size - digits only (?P<size>\d+) Match a literal dot \. The extension (?P<ext>png|jpg|gif) closing delimiter: # Case insensitive modifier flag i If the pattern is matched then the array $matches would look like this: array ( 0 => 'myphoto!500.jpg', 'name' => 'myphoto', 1 => 'myphoto', 'size' => '500', 2 => '500', 'extension' => 'jpg', 3 => 'jpg', ) Simplify variable assignment using Array Destructuring syntax Like was used in the previous section, As of PHP 7.1 array assignment can be used to destructure arrays1. Instead of using list() when exploding strings like the request into two parts, a simple array can be used. This may not save much processing time since list() is just a language construct2 but it is simpler to type. So instead of these lines:
{ "domain": "codereview.stackexchange", "id": 42628, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, security, image, .htaccess", "url": null }
php, security, image, .htaccess list($f, $size) = explode('!', $req); list($size, $ext) = explode('.', $size); Those could be simplified to: [$f, $size] = explode('!', $req); [$size, $ext] = explode('.', $size); Remove unused variables The variables declared here: list($width, $height) = getimagesize($f); appear to be unused. While the memory allocation for those may not be significant, those can be eliminated to save resources and make the code simpler. Updated code I created a repository with a docker file and container file so I could test it on http://localhost:8082. I also updated the code to utilize the suggestions above and output the image to the browser. <?php $req = urldecode(basename($_SERVER['REQUEST_URI'])); preg_match('#^(\w+)!(\d+)\.(png|jpg|gif)#i', $req, $matches); if (!$matches) { die(); } [, $name, $size, $ext] = $matches; $size = intval($size); if (($size > 2000) || ($size % 50 != 0)) die(); $src = imagecreatefromstring(file_get_contents($name . '.' . $ext)); $dst = imagescale($src, $size); $function = 'image' . ($ext == 'jpg' ? 'jpeg' : strtolower($ext)); header('Content-Type: image/' . strtolower($ext)); $function($dst, $req); $function($dst); //send the image to the browser
{ "domain": "codereview.stackexchange", "id": 42628, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, security, image, .htaccess", "url": null }
python, beginner, object-oriented, hangman Title: Object-Oriented Hangman In Python [Follow-Up] Question: This is a follow up after revisions made from this question. I've separated the program into 2 classes. The HangManData class is used to store game data such as the word, letters guessed(separating the ones actually in the word from those that arent), remaining number of guesses and the phase of the image. The second class UI controls user interaction and sends the data back to the HangManData class to be stored. This is definitely a lot more readable compared to the original code. Let me know of any improvements I could make, especially if there is something I've done unnecessarily that could be simplified. I'll be leaving the unnecessary phases file and word file out to prevent any repetition, refer to original question if required import random from phases import hang_phases class HangManData: def __init__(self, random_word): self.word = random_word self.missed_letters = [] self.successful_letters = [] self.man = hang_phases self.remaining_chances = 9 def get_man(self): self.man = hang_phases[self.remaining_chances] return self.man def get_word(self): return self.word def set_successful_letters(self, letter): self.successful_letters.append(letter) def get_successful_letters(self): return self.successful_letters def set_missed_letters(self, letter): self.missed_letters.append(letter) def get_missed_letters(self): return self.missed_letters class UI: def __init__(self): self.word_list = open('Words').read().split("\n") self.word = random.choice(self.word_list).upper() self.filled = "" def generate_word(self): return self.word
{ "domain": "codereview.stackexchange", "id": 42629, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, object-oriented, hangman", "url": null }